From 294af94be2e54b2a88e780db0419c6fc602b69bb Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Sun, 9 Aug 2026 14:41:28 -0700 Subject: [PATCH] Publish POST /v0/beads/issues/{id}:release: give a claim back (ga-lzcuv) (#5507) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Publish POST /v0/beads/issues/{id}:release: give a claim back (ga-lzcuv) The claim has had a wire since v0 and its inverse has had none. `bd unclaim` is a subprocess for every client of this surface, and a release-if-current has no route at all — so the one verb that frees stranded work is the one verb an automation client cannot reach. `releaseIssue` publishes issueops.Releaser whole: `actor`, the `expected_assignee` compare-and-set, and `force`. The response carries the issue, `changed`, and `revision` — the last for `updateIssue`'s reason, and one of its own: a release REMINTS the row's token by design, so a caller that guarded its next write on a version read before the release would miss, and this member is the only place the new one exists. THE REFUSAL CODES ARE THREE, AND ONLY ONE IS NEW. `already_claimed` is the ownership fence — an unforced, unguarded release by an actor that is not the holder. That is `updateIssue`'s assignee-fence situation exactly, down to having two bypasses, so it takes that operation's code rather than a fourth spelling of "a live foreign owner refused your write". Like there, no `assignee` member: the fence refuses without naming the holder, so absence means re-read the row. `precondition_failed` is the guard, inherited from the same operation and carrying the same members for the same reason — `expected_assignee` is the REQUEST's value, and there is no `actual_assignee` beside it, because the refusal rolled its transaction back and ErrAssigneeMismatch is a bare sentinel that formats the holder it saw into prose. There is no ClaimConflictError equivalent to read, and this surface does not scrape its own messages. `not_releasable` is minted, covering ErrNotReleasable and ErrNotClaimed. `not_claimable` is the nearest existing code and covers a superset of the same statuses today, but the coincidence is not a contract — the release transition is pinned to {open, in_progress} by releasableStatus and the claim's eligibility is a separate predicate — and for the unheld half the reuse would be an outright lie: an open, unassigned row is the most claimable row a workspace has. The two conditions share ONE code with no discriminating member, which is the narrow choice rather than the convenient one: neither sentinel carries a typed observation, and splitting later is an ADDITION the document already tells clients to tolerate, while merging two published codes is the removal that breaks the wire. IT IS NOT IDEMPOTENT, and the wire says so rather than inventing an answer the role refused to give. An unheld row is 409, never a 200 carrying `changed: false` — that value is one no role produces (ReleaseResult.Changed is true on every non-error answer), and it would report one answer for "I released this twice", "a reaper beat me to it" and "nothing ever claimed it", because the post-state is anonymous and nothing is left on the row to tell them apart. A client for which "already released" is the ordinary path maps the code to success in one line it writes knowingly. `expected_assignee` disagrees with `updateIssue`'s same-named member in exactly one place, and the schema says so: the empty string is a 400 here rather than a guard meaning "expected unassigned". It also documents what the comparison ACTUALLY does — separator-insensitive over runs of `.`/`_`/`-`, per actorMatches, and nothing else forgiven — rather than repeating the role doc's "byte for byte", which the implementation stopped being at ga-5ksp5. failRelease matches all four sentinels TYPED and BEFORE its ErrValidation and ErrNotFound arms. None of them is wrapped in ErrValidation on any leg, so below a generic arm every one would have been a 500 on every leg. The real-Dolt leg asserts the property a fake cannot: after every refusal it reads the row back through the CLI, so "nothing was written" — and above all the CLAIM SURVIVING a wrong-holder refusal — is a fact about the stored row. Co-authored-by: Claude Fable 5 * Fix the release document's three review findings (ga-lzcuv) The mint stands; what the review caught is that the document was written as though `not_releasable` meant one thing, and it means two. THE SAFETY ONE. "A caller for which 'already released' is the ordinary path treats that code as success" was true of the sentinel it was written against and is FALSE of the code it shipped as. `not_releasable` also covers the status refusal, and a row parked in a status this workspace configured is refused WHILE STILL ASSIGNED — so a reaper following that sentence books a claim as dropped while it stands, held by an agent that is already gone, with nothing left to free it. That is the stranding this operation resolves ids across both planes to prevent, reintroduced through the refusal vocabulary instead of through the id. It now says the opposite, in the operation description and again on the 409: on `not_releasable`, READ THE ROW. The row carries the one fact that separates the two — an assignee, or none. One extra request on an uncommon path is the honest price of one code rather than two, and the handler's `detail` says so too, since that is the string an operator actually reads. THE ACCURACY ONE. CodeNotReleasable claimed "neither refusal is typed", which is wrong and misleads the person who eventually splits it: ErrNotClaimed and ErrNotReleasable are two distinct typed sentinels and failRelease holds both in one case arm, so a split is a mapping change in that arm — no archaeology and no prose-scraping. What is genuinely unavailable typed is the OBSERVATION each refusal made, the status seen and the emptiness of the assignee, which is why the code carries no extension member. That is a narrower claim than the one the comment made, and it is the true one. The merge is recorded as what it is: a deliberate start-narrow choice, kept because adding a code later is the reversible direction. THE WIDENING. The 200 now states it: the transition is defined over `open` AND `in_progress`, so a row already open that STILL HOLDS AN ASSIGNEE is released here — the state a partial write or an out-of-band status edit leaves behind, and one a release-if-current guarding on `in_progress` did nothing for and reported no error about. A client porting such a guard has to know that before it ports one. Beside it, the code-to-outcome mapping a release-if-current client wants, so that mapping is written against a documented fact: `not_releasable`, `precondition_failed`, `already_claimed` and `404` all mean "no release happened, and that is not an error" — `(false, nil)` to a client spelling it as a pair. With the reading that pair does NOT license, stated beside it, because it is the same reading the safety finding is about: it means no release happened, never that the claim is gone. Co-authored-by: Claude Fable 5 --------- Co-authored-by: Review Sim Co-authored-by: Claude Fable 5 --- cmd/bd/serve.go | 12 +- cmd/bd/serve_proxied_integration_test.go | 4 +- .../serve_release_proxied_integration_test.go | 233 +++++++++ cmd/bd/serve_source_test.go | 31 ++ cmd/bd/serve_store_identity_test.go | 2 + internal/httpapi/apigen/types.gen.go | 49 +- internal/httpapi/claim.go | 9 + internal/httpapi/claim_test.go | 7 + internal/httpapi/problem.go | 73 +++ internal/httpapi/release.go | 268 ++++++++++ internal/httpapi/release_test.go | 480 ++++++++++++++++++ internal/httpapi/roles.go | 22 + internal/httpapi/roles_test.go | 31 ++ internal/httpapi/routes.go | 13 + internal/httpapi/server.go | 33 +- internal/httpapi/server_test.go | 2 +- internal/httpapi/spec/openapi.v0.yaml | 359 ++++++++++++- internal/httpapi/spec_parity_test.go | 31 ++ 18 files changed, 1649 insertions(+), 10 deletions(-) create mode 100644 cmd/bd/serve_release_proxied_integration_test.go create mode 100644 internal/httpapi/release.go create mode 100644 internal/httpapi/release_test.go diff --git a/cmd/bd/serve.go b/cmd/bd/serve.go index 0619588ca..5802aea26 100644 --- a/cmd/bd/serve.go +++ b/cmd/bd/serve.go @@ -184,6 +184,7 @@ func runServe() error { AllowNonLoopback: serveAllowNonLoopback, Reader: roles.reader, Claimer: roles.claimer, + Releaser: roles.releaser, Lifecycle: roles.lifecycle, Settings: roles.settings, Stats: roles.stats, @@ -500,6 +501,7 @@ func serveIssueRoles(src storage.DoltStorage, journalEnabled bool) (serveRoles, for _, b := range []binding{ {"issue reader", func() (err error) { roles.reader, err = src.IssueReader(); return }}, {"issue claimer", func() (err error) { roles.claimer, err = src.IssueClaimer(); return }}, + {"issue releaser", func() (err error) { roles.releaser, err = src.Releaser(); return }}, {"issue lifecycle", func() (err error) { roles.lifecycle, err = src.IssueLifecycle(); return }}, {"workspace config", func() (err error) { roles.settings, err = src.WorkspaceConfig(); return }}, {"stats reporter", func() (err error) { roles.stats, err = src.StatsReporter(); return }}, @@ -553,8 +555,14 @@ func serveIssueRoles(src storage.DoltStorage, journalEnabled bool) (serveRoles, // requires every httpapi.Config literal in this package to sit in a function // that consulted serveDatabaseSource. type serveRoles struct { - reader issueops.Reader - claimer issueops.Claimer + reader issueops.Reader + claimer issueops.Claimer + // releaser is the claim's inverse, behind + // POST /v0/beads/issues/{id}:release. Its accessor recurses through the + // hook decorator like the two below it — a release is an update, so + // HookFiringStore.Releaser fires the workspace's on_update script — which + // is why it comes off the PEELED store with the rest. + releaser issueops.Releaser lifecycle issueops.Lifecycle settings issueops.WorkspaceConfig stats issueops.StatsReporter diff --git a/cmd/bd/serve_proxied_integration_test.go b/cmd/bd/serve_proxied_integration_test.go index 4116ccab6..88b487d48 100644 --- a/cmd/bd/serve_proxied_integration_test.go +++ b/cmd/bd/serve_proxied_integration_test.go @@ -149,8 +149,8 @@ var servedCapabilities = []any{ "events.list", "events.watch", "issues.batchApply", "issues.batchCreate", "issues.casMetadata", "issues.claim", "issues.close", "issues.create", "issues.delete", - "issues.get", "issues.list", "issues.query", "issues.reopen", "issues.sweep", - "issues.update", + "issues.get", "issues.list", "issues.query", "issues.release", "issues.reopen", + "issues.sweep", "issues.update", "memories.forget", "memories.get", "memories.list", "memories.remember", "ready.count", "ready.list", "stats.get", } diff --git a/cmd/bd/serve_release_proxied_integration_test.go b/cmd/bd/serve_release_proxied_integration_test.go new file mode 100644 index 000000000..bdb817bf2 --- /dev/null +++ b/cmd/bd/serve_release_proxied_integration_test.go @@ -0,0 +1,233 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "io" + "net/http" + "strings" + "testing" +) + +// End-to-end for the release, against real Dolt through a real `bd serve` +// subprocess. The pure tests in internal/httpapi cover the wire edge on a fake +// role; what only this level can prove is the TRANSACTION, and here that is a +// sharper claim than usual: a REFUSED release must leave the claim STANDING. +// +// A fake role cannot show that. It reports whatever error the case handed it +// and holds no row, so a handler that refused a wrong-holder release AFTER the +// row was already emptied would look identical. This test reads the row back +// through the CLI's own path after every refusal, so "nothing was written" is +// asserted against the stored row rather than against a fake's bookkeeping. +// +// The role-level transition — what the row looks like afterwards, the dropped +// lease, the recorded event — is owned against a real store by +// internal/storage/uow/releaser_contract_test.go. This test owns the +// wire-to-role seam and cites that one rather than duplicating it. + +// releaseIssue posts a release for id and returns the status and decoded body. +func (sp *serveProcess) releaseIssue(t *testing.T, id, body string) (int, map[string]any) { + t.Helper() + req, err := http.NewRequest(http.MethodPost, sp.url("/v0/beads/issues/"+id+":release"), strings.NewReader(body)) + if err != nil { + t.Fatalf("new release request: %v", err) + } + req.Header.Set("Content-Type", "application/json") + resp, err := sp.client.Do(req) + if err != nil { + t.Fatalf("POST release %s: %v\nstderr:\n%s", id, err, sp.stderr.String()) + } + defer func() { _ = resp.Body.Close() }() + raw, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read release body: %v", err) + } + var m map[string]any + if len(raw) > 0 { + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatalf("decode release body %q: %v", raw, err) + } + } + return resp.StatusCode, m +} + +func TestProxiedServerServeRelease(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "srvrel") + sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir)) + + // The loop this operation completes: claim it, give it back, and see the + // row available to the next taker. The post-state is the ANONYMOUS one the + // document describes, read back through the CLI rather than off the + // response the release itself composed. + t.Run("a holder releases its own claim", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "release over http", "-p", "1") + + if status, body := sp.claim(t, issue.ID, "http-agent"); status != http.StatusOK { + t.Fatalf("claim: status = %d, want 200: %v", status, body) + } + + status, body := sp.releaseIssue(t, issue.ID, `{"actor":"http-agent"}`) + if status != http.StatusOK { + t.Fatalf("release: status = %d, want 200: %v", status, body) + } + if body["changed"] != true { + t.Errorf("changed = %v, want true; the role reports it true on every answer it returns without an error", body["changed"]) + } + if body["revision"] == nil { + t.Errorf("the response carries no revision; a caller composing its next expected_version has nothing to read") + } + + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if string(shown.Status) != "open" || shown.Assignee != "" { + t.Fatalf("bd show reports status %q assignee %q; the HTTP release did not land", + shown.Status, shown.Assignee) + } + }) + + // THE GUARD SATISFIED. A supervisor that can NAME the holder releases it + // without being the holder — the fence replaced rather than bypassed. + t.Run("a satisfied expected_assignee releases another actor's claim", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "release-if-current over http", "-p", "1") + + if status, body := sp.claim(t, issue.ID, "worker-a"); status != http.StatusOK { + t.Fatalf("claim: status = %d, want 200: %v", status, body) + } + + status, body := sp.releaseIssue(t, issue.ID, `{"actor":"supervisor","expected_assignee":"worker-a"}`) + if status != http.StatusOK { + t.Fatalf("guarded release: status = %d, want 200: %v", status, body) + } + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if string(shown.Status) != "open" || shown.Assignee != "" { + t.Fatalf("bd show reports status %q assignee %q; the guarded release did not land", + shown.Status, shown.Assignee) + } + }) + + // THE PROOF THE FAKE CANNOT GIVE. Each refusal is followed by a read of the + // stored row, so "nothing was written" is asserted rather than assumed — + // and the claim SURVIVING a wrong-holder refusal is the property the whole + // ownership fence exists for. + t.Run("a refused release leaves the claim standing", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "refused releases over http", "-p", "1") + + if status, body := sp.claim(t, issue.ID, "worker-a"); status != http.StatusOK { + t.Fatalf("claim: status = %d, want 200: %v", status, body) + } + + // The fence: an unforced, unguarded release by somebody else. + status, body := sp.releaseIssue(t, issue.ID, `{"actor":"mallory"}`) + if status != http.StatusConflict { + t.Fatalf("foreign release: status = %d, want 409: %v", status, body) + } + if body["code"] != "already_claimed" { + t.Errorf("code = %v, want already_claimed", body["code"]) + } + assertStillHeldBy(t, bd, p.dir, issue.ID, "worker-a", "the ownership fence") + + // The guard, missed. It is a precondition_failed rather than the + // fence's code, and it echoes the REQUEST's expectation with no + // observation beside it. + status, body = sp.releaseIssue(t, issue.ID, `{"actor":"supervisor","expected_assignee":"worker-b"}`) + if status != http.StatusConflict { + t.Fatalf("stale guard: status = %d, want 409: %v", status, body) + } + if body["code"] != "precondition_failed" { + t.Errorf("code = %v, want precondition_failed", body["code"]) + } + if body["expected_assignee"] != "worker-b" { + t.Errorf("expected_assignee = %v, want the value the request sent", body["expected_assignee"]) + } + if _, present := body["actual_assignee"]; present { + t.Errorf("actual_assignee = %v; the role reports the holder in prose only, so this member cannot be honestly filled", + body["actual_assignee"]) + } + assertStillHeldBy(t, bd, p.dir, issue.ID, "worker-a", "a missed guard") + }) + + // NOT IDEMPOTENT, proved against a real row: the second release of a row + // the first one emptied is a refusal, not a 200. This is the case a client + // mapping the code to "already released" is written against. + t.Run("releasing an unheld row is a refusal", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "unheld release over http", "-p", "1") + + if status, body := sp.claim(t, issue.ID, "worker-a"); status != http.StatusOK { + t.Fatalf("claim: status = %d, want 200: %v", status, body) + } + if status, body := sp.releaseIssue(t, issue.ID, `{"actor":"worker-a"}`); status != http.StatusOK { + t.Fatalf("first release: status = %d, want 200: %v", status, body) + } + + status, body := sp.releaseIssue(t, issue.ID, `{"actor":"worker-a"}`) + if status != http.StatusConflict { + t.Fatalf("second release: status = %d, want 409: %v", status, body) + } + if body["code"] != "not_releasable" { + t.Errorf("code = %v, want not_releasable", body["code"]) + } + // A row that was never claimed at all answers the SAME way, which is + // the anonymity the non-idempotence argument rests on: there is nothing + // left on either row to tell the two situations apart. + fresh := bdProxiedCreate(t, bd, p.dir, "never claimed", "-p", "1") + status, body = sp.releaseIssue(t, fresh.ID, `{"actor":"worker-a"}`) + if status != http.StatusConflict || body["code"] != "not_releasable" { + t.Errorf("a never-claimed row answers %d/%v; it must be indistinguishable from a re-release", + status, body["code"]) + } + }) + + // The status half of the same code, over a row the CLI closed. `force` does + // not reach it — it answers "may I release someone else's claim", and this + // is not a question about ownership. + t.Run("a closed row refuses a release, forced or not", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "closed release over http", "-p", "1") + + if status, body := sp.claim(t, issue.ID, "worker-a"); status != http.StatusOK { + t.Fatalf("claim: status = %d, want 200: %v", status, body) + } + if status, body := sp.closeIssue(t, issue.ID, `{"actor":"worker-a","force":true}`); status != http.StatusOK { + t.Fatalf("close: status = %d, want 200: %v", status, body) + } + + for _, body := range []string{`{"actor":"worker-a"}`, `{"actor":"worker-a","force":true}`} { + status, decoded := sp.releaseIssue(t, issue.ID, body) + if status != http.StatusConflict { + t.Fatalf("release of a closed row with %s: status = %d, want 409: %v", body, status, decoded) + } + if decoded["code"] != "not_releasable" { + t.Errorf("release of a closed row with %s: code = %v, want not_releasable", body, decoded["code"]) + } + } + }) + + t.Run("an id naming nothing is a 404", func(t *testing.T) { + status, body := sp.releaseIssue(t, "bd-does-not-exist", `{"actor":"worker-a"}`) + if status != http.StatusNotFound { + t.Fatalf("status = %d, want 404: %v", status, body) + } + if body["code"] != "not_found" { + t.Errorf("code = %v, want not_found", body["code"]) + } + }) +} + +// assertStillHeldBy reads the row through the CLI and fails unless the claim is +// intact. It is the assertion this file exists for: every refusal above is +// followed by one, because a handler that emptied the row and THEN refused +// would be indistinguishable from a correct one at the wire. +func assertStillHeldBy(t *testing.T, bd, dir, id, holder, what string) { + t.Helper() + shown := bdProxiedShow(t, bd, dir, id) + if shown.Assignee != holder { + t.Fatalf("after %s refused the release, %s is held by %q, want %q: the refusal wrote to the row", + what, id, shown.Assignee, holder) + } + if string(shown.Status) != "in_progress" { + t.Fatalf("after %s refused the release, %s has status %q, want in_progress: the refusal wrote to the row", + what, id, shown.Status) + } +} diff --git a/cmd/bd/serve_source_test.go b/cmd/bd/serve_source_test.go index 32025f5e2..d552bf7e6 100644 --- a/cmd/bd/serve_source_test.go +++ b/cmd/bd/serve_source_test.go @@ -96,6 +96,7 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) { return &serveRolesStore{ reader: &serveStubReader{}, claimer: &serveStubClaimer{}, + releaser: &serveStubReleaser{}, lifecycle: &serveStubLifecycle{}, dependencies: &serveStubDependencyEditor{}, batchApplier: &serveStubBatchApplier{}, @@ -164,10 +165,27 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) { t.Fatal("the store's own accessor no longer returns a hook-firing compare-and-set; this test proves nothing") } + // And for the releaser, the SIXTH. Its case in the RoleFiresHooks switch + // would otherwise be held only by a comment, which is exactly how the + // compare-and-set's case above spent time silently empty. + releaserFromTheStore, err := chained.Releaser() + if err != nil { + t.Fatalf("Releaser: %v", err) + } + if !storage.RoleFiresHooks(releaserFromTheStore) { + t.Fatal("the store's own accessor no longer returns a hook-firing releaser; this test proves nothing") + } + roles, err := serveIssueRoles(chained, false) if err != nil { t.Fatalf("serveIssueRoles: %v", err) } + if storage.RoleFiresHooks(roles.releaser) { + t.Error("bd serve would run this workspace's hooks on every HTTP release") + } + if roles.releaser != issueops.Releaser(middle.releaser) { + t.Errorf("releaser came from %p, want the layer directly beneath the hooks (%p)", roles.releaser, middle.releaser) + } reader, claimer := roles.reader, roles.claimer // The same predicate httpapi.Listen refuses on, so a regression here is a // server that refuses to boot rather than one that runs hooks silently. @@ -319,6 +337,7 @@ type serveRolesStore struct { storage.DoltStorage reader *serveStubReader claimer *serveStubClaimer + releaser *serveStubReleaser lifecycle *serveStubLifecycle dependencies *serveStubDependencyEditor batchApplier *serveStubBatchApplier @@ -330,6 +349,12 @@ func (s *serveRolesStore) IssueReader() (issueops.Reader, error) { return s.re func (s *serveRolesStore) IssueClaimer() (issueops.Claimer, error) { return s.claimer, nil } func (s *serveRolesStore) Unwrap() storage.DoltStorage { return s.inner } +// Releaser carries an identifiable value for the same reason, and it is the +// SIXTH role the decorator wraps: a peel of the wrong depth would hand bd serve +// a releaser that runs the workspace's hooks once per claim it frees — which a +// reaper draining abandoned work does in a tight loop. +func (s *serveRolesStore) Releaser() (issueops.Releaser, error) { return s.releaser, nil } + // IssueLifecycle carries an identifiable value for the same reason the reader // and the claimer do: it is one of the roles the hook decorator wraps, so a peel // of the wrong depth would hand bd serve a lifecycle that runs the workspace's @@ -391,6 +416,12 @@ func (*serveStubClaimer) Claim(context.Context, issueops.ClaimRequest) (issueops return issueops.ClaimResult{}, errors.ErrUnsupported } +type serveStubReleaser struct{} + +func (*serveStubReleaser) Release(context.Context, issueops.ReleaseRequest) (issueops.ReleaseResult, error) { + return issueops.ReleaseResult{}, errors.ErrUnsupported +} + type serveStubLifecycle struct{} func (*serveStubLifecycle) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) { diff --git a/cmd/bd/serve_store_identity_test.go b/cmd/bd/serve_store_identity_test.go index 5c1363497..e7058bdb4 100644 --- a/cmd/bd/serve_store_identity_test.go +++ b/cmd/bd/serve_store_identity_test.go @@ -182,6 +182,7 @@ func (s *serveIdentityStore) Close() error { return nil } // They hand back serveIdentityRole, which satisfies each interface by // EMBEDDING it rather than implementing it: non-nil, so the set is complete, // while an actual call panics naming the method it reached. +func (*serveIdentityStore) Releaser() (issueops.Releaser, error) { return serveIdentityRole{}, nil } func (*serveIdentityStore) IssueLifecycle() (issueops.Lifecycle, error) { return serveIdentityRole{}, nil } @@ -227,6 +228,7 @@ func (*serveIdentityStore) MetadataCAS() (issueops.MetadataCAS, error) { // being promoted and the build would say so. type serveIdentityRole struct { issueops.Lifecycle + issueops.Releaser issueops.MetadataCAS issueops.WorkspaceConfig issueops.StatsReporter diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index a9d9e8d70..0de37326d 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -734,7 +734,7 @@ type ContextResponse struct { // BeadsDir Absolute path of the served workspace's `.beads` directory. A host path, kept because it is the single-workspace server's only workspace-identity handshake; disclosing it to network peers is part of what an operator accepts when binding beyond loopback. BeadsDir string `json:"beads_dir"` - // Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.create`, `issues.claim`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string. + // Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.create`, `issues.claim`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string. // // THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive. Capabilities []string `json:"capabilities"` @@ -1158,7 +1158,7 @@ type Problem struct { // BlockerIsAncestor With `dependency_cycle`, hierarchy refusal only: true when `blocker_id` is an ANCESTOR of `issue_id` (which cannot close until its descendants finish, so the gate would never clear), false when it is a DESCENDANT (blocked status cascades, so it would inherit the block and never close). Both polarities are reported; this member is never omitted to mean false. See `issue_id`. BlockerIsAncestor *bool `json:"blocker_is_ancestor,omitempty"` - // Code The stable machine-readable reason, and the ONLY member a client may dispatch on. v0's vocabulary: `invalid_argument` (400, also emitted by the Host-header middleware on any route), `invalid_cursor` (400), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), `busy` (503), `db_unavailable` (503), `events_watch_saturated` (503), `internal` (500). Renaming or removing a status+code pair is a breaking change; ADDING one is not, so clients MUST default-branch on unknown values and fall back to the status class (unknown 4xx → client bug, fail loud; unknown 503 → retry per `Retry-After`; other unknown 5xx → server fault). + // Code The stable machine-readable reason, and the ONLY member a client may dispatch on. v0's vocabulary: `invalid_argument` (400, also emitted by the Host-header middleware on any route), `invalid_cursor` (400), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), `not_releasable` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), `busy` (503), `db_unavailable` (503), `events_watch_saturated` (503), `internal` (500). Renaming or removing a status+code pair is a breaking change; ADDING one is not, so clients MUST default-branch on unknown values and fall back to the status class (unknown 4xx → client bug, fail loud; unknown 503 → retry per `Retry-After`; other unknown 5xx → server fault). Code string `json:"code"` // DeclaredLater With `invalid_argument` on a batch operation whose items may name each other: whether the unresolvable key IS declared by the request, at a LATER index. @@ -1286,6 +1286,48 @@ type Ref struct { Key *string `json:"key,omitempty"` } +// ReleaseIssueRequest defines model for ReleaseIssueRequest. +type ReleaseIssueRequest struct { + // Actor Who is releasing the claim. `ClaimRequest.actor`'s rules exactly: the server trims it, then refuses an empty result, anything longer than 256 BYTES (the `maxLength` above counts characters — the byte limit is the binding one), and any control character including newline. The value reaches the event the release records and the storage commit message, so an unvalidated newline would forge audit-trail lines. + // + // It is REQUIRED, and for one reason beyond the audit trail: a release is the moment work stops being owned, and the one question asked of its history entry afterwards is who let it go. On the unconditional path it is ALSO the ownership fence's subject — see the operation description. + Actor string `json:"actor"` + + // ExpectedAssignee Compare-and-set on the holder: the release proceeds only while the issue is still assigned to this actor, and otherwise refuses with `409` / `precondition_failed` naming this value, having written nothing. + // + // A MATCH REPLACES THE OWNERSHIP FENCE, so `actor` need not be the holder. Sending it beside `force` is a 400: the two are answers to the same question and they disagree. + // + // THE COMPARISON IS SEPARATOR-INSENSITIVE AND NOTHING ELSE. A run of `.`, `_` or `-` matches any other such run, so `agent-a`, `agent_a` and `agent.a` are one holder — that is deliberate, so a caller naming the holder under a different layer's spelling is a match rather than a mismatch. NOTHING ELSE IS FORGIVEN: the value is not trimmed and not case-folded, so `" agent-a"` and `Agent-a` are both refusals. The server trims only far enough to tell a blank expectation from a real one and never sends the trimmed form on, so a caller that pads its expectation loses EVERY time rather than intermittently. Compose it from a holder a read gave you. + // + // THE EMPTY STRING IS A 400, and this is the one place this member disagrees with `UpdateIssueRequest.expected_assignee`, where an empty string is a real guard meaning "expected unassigned". Here "release a row nobody holds" describes no release at all; a caller that wants to assert a row is unheld is asking a READER a question, not asking this operation to do nothing. Absent, and only absent, selects the unconditional path. + // + // IT IS NOT LENGTH- OR PATTERN-BOUNDED the way `actor` is, and the asymmetry is deliberate: this value is COMPARED and never stored, so a value no assignee column could hold simply cannot match, and refusing it at the edge would be a refusal the role does not have. + ExpectedAssignee *string `json:"expected_assignee,omitempty"` + + // Force Bypass the ownership fence, so an actor that is not the holder may release the claim. It is the escape hatch `bd unclaim --force` spells, for an abandoned claim whose holder crashed. + // + // IT BYPASSES THE FENCE AND NOTHING ELSE. It does not make an unheld row releasable, it does not make a closed one releasable, and it never bypasses a precondition — sending it beside `expected_assignee` is a 400 rather than a silent win for either. + Force *bool `json:"force,omitempty"` +} + +// ReleaseIssueResponse defines model for ReleaseIssueResponse. +type ReleaseIssueResponse struct { + // Changed Whether the release WROTE the row. It is TRUE on every 200 this operation returns, because every shape that would not write is refused above it — an unheld row is a 409, not an idempotent no-op. DO NOT WRITE A `changed: false` BRANCH: no request reaches one. + // + // It is published rather than omitted because `claimIssue` and `updateIssue` publish the same fact, and a caller holding all three should not have to read them two ways. It is also the negative space that answers "where is the `already_released` member" — there is none, and the operation description says why. + Changed bool `json:"changed"` + + // Issue A tracked work item. Property semantics documented here apply to every schema that repeats them below. + Issue Issue `json:"issue"` + + // Revision The row's optimistic-concurrency token AFTER the release, spelled the way `UpdateIssueResponse.revision` spells it and carrying the same promise: a read-modify-write loop composes its next `expected_version` from THIS value, never from a number it incremented itself. + // + // A release REMINTS the token by design, so a caller that guarded a following write on a version it read BEFORE the release will miss. That is the point — a concurrent reclaim or close conflicts rather than silently merging — and this member is how the caller stays in step. + // + // DECODE IT AS A 64-BIT INTEGER, for the reason `UpdateIssueRequest.expected_version` spells out: an IEEE-754-double parser corrupts it silently, and the corruption only shows up as a `precondition_failed` on the NEXT request. + Revision int64 `json:"revision"` +} + // RememberRequest What to remember, and optionally under what key. type RememberRequest struct { // Content The memory itself, stored VERBATIM: newlines, surrounding space and unicode all survive. Flattening it to one line is what a front door does when it prints, not what this plane does when it stores. @@ -1911,6 +1953,9 @@ type ClaimIssueJSONRequestBody = ClaimRequest // CloseIssueJSONRequestBody defines body for CloseIssue for application/json ContentType. type CloseIssueJSONRequestBody = CloseIssueRequest +// ReleaseIssueJSONRequestBody defines body for ReleaseIssue for application/json ContentType. +type ReleaseIssueJSONRequestBody = ReleaseIssueRequest + // ReopenIssueJSONRequestBody defines body for ReopenIssue for application/json ContentType. type ReopenIssueJSONRequestBody = ReopenIssueRequest diff --git a/internal/httpapi/claim.go b/internal/httpapi/claim.go index 957a1674f..b0c9916c0 100644 --- a/internal/httpapi/claim.go +++ b/internal/httpapi/claim.go @@ -311,6 +311,7 @@ type timedProvider struct { var ( _ uow.IssueReaderSource = timedProvider{} _ uow.IssueClaimerSource = timedProvider{} + _ uow.ReleaserSource = timedProvider{} _ uow.IssueLifecycleSource = timedProvider{} _ uow.WorkspaceConfigSource = timedProvider{} _ uow.StatsReporterSource = timedProvider{} @@ -367,6 +368,14 @@ func (p timedProvider) IssueClaimer() (issueops.Claimer, error) { return uow.NewIssueClaimer(p) } +// Releaser builds the claim-release role OVER THIS WRAPPER, for the same reason +// and with the same hazard as IssueClaimer: a release opens a write transaction +// per call, so a recursion here would report uow_ms=0.000 for every one of +// them. +func (p timedProvider) Releaser() (issueops.Releaser, error) { + return uow.NewReleaser(p) +} + // IssueLifecycle builds the guarded-mutation role OVER THIS WRAPPER, for the // same reason and with the same hazard as IssueClaimer: this role opens the // longest write transactions on the surface, so a claimer-style recursion here diff --git a/internal/httpapi/claim_test.go b/internal/httpapi/claim_test.go index e139b4382..8b739a172 100644 --- a/internal/httpapi/claim_test.go +++ b/internal/httpapi/claim_test.go @@ -650,7 +650,14 @@ func TestCustomMethodsNarrowThePOSTSurface(t *testing.T) { "/v0/beads/issues/bd-1:Close", // nor is this one "/v0/beads/issues/bd-1:claim-not", // a suffix that merely starts the same "/v0/beads/issues/bd-1:close-not", + // `unclaim` is the CLI's spelling of the release and is deliberately not + // a second name for it here: one verb per operation, and a client that + // guessed from the command name gets the same 404 any other unrouted + // suffix gets. "/v0/beads/issues/bd-1:unclaim", + "/v0/beads/issues/:release", + "/v0/beads/issues/bd-1:Release", + "/v0/beads/issues/bd-1:released", "/v0/beads/issues/:reopen", "/v0/beads/issues/bd-1:Reopen", "/v0/beads/issues/bd-1:reopened", diff --git a/internal/httpapi/problem.go b/internal/httpapi/problem.go index b0c1e038a..29bef2f5e 100644 --- a/internal/httpapi/problem.go +++ b/internal/httpapi/problem.go @@ -59,6 +59,45 @@ const ( // sentinel's message text. CodeAlreadyClaimed Code = "already_claimed" CodeNotClaimable Code = "not_claimable" + // CodeNotReleasable is a row refusing to give up a claim, and it covers + // the two conditions releaseIssue's role reports for that: the row holds + // no claim, or its status is neither open nor in_progress. + // + // A 409 for CodeNotClosable's reason: the body is well-formed and STATE + // refuses it, so the same request succeeds or fails on something the client + // cannot see without reading it. + // + // IT IS MINTED RATHER THAN FOLDED INTO CodeNotClaimable, which is the + // nearest existing code and covers a superset of the same statuses today. + // The coincidence is not a contract: the release transition is pinned to + // {open, in_progress} by releasableStatus and the claim's eligibility is a + // separate predicate, so the two sets are free to diverge and would then be + // one code meaning two things. Worse, the unheld half would be an outright + // lie — an open, unassigned row is the MOST claimable row a workspace has, + // and answering `not_claimable` about it would send a client somewhere + // there is nothing to find. + // + // IT COVERS BOTH CONDITIONS UNDER ONE CODE, and that is a deliberate + // start-narrow CHOICE rather than a consequence of missing information. + // + // THE TWO CONDITIONS ARE FULLY DISTINGUISHABLE HERE. ErrNotClaimed and + // ErrNotReleasable are two distinct typed sentinels, and failRelease holds + // both in one case arm — so a future split needs no archaeology and no + // prose-scraping: it is a mapping change in that arm plus a code in this + // block and a line in the document. What IS unavailable typed is the + // OBSERVATION either refusal made — the status it saw, the emptiness of the + // assignee — because both format those into their messages and this surface + // does not scrape its own prose. That is why the code carries no extension + // member, and it is a narrower statement than "the refusals are + // indistinguishable", which they are not. + // + // The split is deferred rather than refused because one code is the + // reversible direction: splitting later is an ADDITION, which the document + // already tells clients to tolerate, while merging two published codes into + // one is the removal that breaks the wire. A client that needs the + // distinction before then reads the row, which the operation description + // tells it to do for a safety reason rather than a taste one. + CodeNotReleasable Code = "not_releasable" // CodeNotClosable is close policy refusing an unforced close: open // children, or a live blocker. The open-children refusal carries the count // in the `open_children` extension member, read inside the refusing @@ -187,6 +226,7 @@ var codeStatus = map[Code]int{ CodeAlreadyClaimed: http.StatusConflict, CodeNotClaimable: http.StatusConflict, CodeNotClosable: http.StatusConflict, + CodeNotReleasable: http.StatusConflict, CodeDependencyCycle: http.StatusConflict, CodeDependencyExists: http.StatusConflict, CodeAlreadyExists: http.StatusConflict, @@ -271,6 +311,21 @@ const ( OpListIssues = "listIssues" OpGetIssue = "getIssue" OpClaimIssue = "claimIssue" + // OpReleaseIssue gives a claim back — the claim's inverse, and what + // `bd unclaim` spells. It is a named lifecycle action rather than a status + // patch for OpCloseIssue's reason: an update spells the release three + // fields at a time, which puts the transition's definition in the caller, + // and the lease it drops is the part a patch cannot express at all. + // + // It is the one write on this surface that is NOT idempotent, and the + // asymmetry with the claim is a fact about the two post-states rather than + // a preference: a claim's post-state names the claimant, so a re-claim is + // recognizable and can answer 200. A release leaves an anonymous row, so + // "I released this twice", "a reaper beat me to it" and "nothing ever + // claimed it" are one row — and one 200 for three situations that want + // different things from a caller. It answers 409 instead and lets the + // caller decide which of them it can live with. + OpReleaseIssue = "releaseIssue" // OpCloseIssue is the second half of the agent loop this surface exists to // serve: claim, work, close. It is a named lifecycle action rather than a // status patch because Close carries semantics a patch has nowhere to put — @@ -484,6 +539,24 @@ var operationCodes = map[string][]Code{ CodeInvalidArgument, CodeNotFound, CodeAlreadyClaimed, CodeNotClaimable, CodeBusy, CodeDBUnavailable, CodeInternal, }, + // THREE conflict codes, and only one of them is new. `already_claimed` is + // the ownership fence, inherited from updateIssue's assignee arm: the same + // situation — a live foreign owner refusing a write — with the same two + // bypasses, spelled `force` and `expected_assignee` here. `precondition_failed` + // is the `expected_assignee` guard, inherited from the same operation and + // carrying the same members for the same reason: the request's expectation, + // never an observation. + // + // `not_releasable` is the mint, and its own doc carries the analysis. + // + // The 404 is the path id's, on the terms updateIssue states. There is no + // `not_claimable` here even though the claim's status refusal is the nearest + // neighbour — see CodeNotReleasable for why that reuse was refused. + OpReleaseIssue: { + CodeInvalidArgument, CodeNotFound, + CodeAlreadyClaimed, CodeNotReleasable, CodePreconditionFailed, + CodeBusy, CodeDBUnavailable, CodeInternal, + }, // The 409 is close POLICY, and it is the only conflict this operation has: // an unforced close refused for open children or for a live blocker. There // is no already_claimed here — closing work somebody else holds is not a diff --git a/internal/httpapi/release.go b/internal/httpapi/release.go new file mode 100644 index 000000000..a36944cfd --- /dev/null +++ b/internal/httpapi/release.go @@ -0,0 +1,268 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + + "github.com/steveyegge/beads/internal/httpapi/apigen" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/issueops" +) + +const ( + // releaseExpectedAssigneeMember is the compare-and-set guard on the holder. + // It is named the way updateIssue names its own guard, because it is the + // same guard — but it does NOT admit the empty string, which is the one + // place the two disagree. See its schema. + releaseExpectedAssigneeMember = "expected_assignee" + // releaseForceMember is the ownership-fence bypass. + releaseForceMember = "force" +) + +// releaseRequestMembers is the document's member list for ReleaseIssueRequest. +// The schema is additionalProperties: false, so anything else is refused BY +// NAME, the posture every body on this surface takes. +var releaseRequestMembers = []string{claimActorMember, releaseExpectedAssigneeMember, releaseForceMember} + +// handleRelease gives back the claim on one issue: the claim's inverse, and the +// verb `bd unclaim` spells. +// +// It carries the claim's posture verbatim. The actor is caller-ASSERTED +// provenance and not authenticated identity; hooks do not fire and the +// per-command auto-commit machinery does not run. The only durable effect is +// the single storage commit the role makes inside its own transaction. +// +// THE ACTOR IS ALSO THE OWNERSHIP FENCE'S SUBJECT here, which it is on no other +// operation: a release carrying neither guard nor force succeeds only while the +// actor is the holder. That is not authorization — this surface has none — it +// is the anti-yank guard the claim gets from refusing a foreign holder, pointed +// the other way, and it is the role's rather than this handler's. +// +// PLANES, as for close and reopen and unlike the claim: the id resolves across +// both. A wisp can hold a claim, so an operation that refused to release one +// would strand an ephemeral row owned by an agent that is gone. +func (s *Server) handleRelease(w http.ResponseWriter, r *http.Request) { + // The custom-method dispatcher split the id off the segment and bounded it + // before this handler was chosen at all; see customMethodTarget. + id := r.PathValue(customMethodIDValue) + if !s.requireNoQuery(w, r) { + return + } + if !s.requireJSONContent(w, r) { + return + } + request, ok := s.releaseRequest(w, r, id) + if !ok { + return + } + + releaser, err := s.releaser(r) + if err != nil { + s.failRelease(w, r, request, err) + return + } + result, err := releaser.Release(r.Context(), request) + if err != nil { + s.failRelease(w, r, request, err) + return + } + // `changed` is the role's own, and it is true on every answer that reaches + // here: the role refuses every shape that would not write. It is published + // because claimIssue and updateIssue publish the same fact, and it is the + // negative space that answers "where is the already_released member" — + // there is none, and the document says why. + // + // `revision` is the row's post-write concurrency token, read off the same + // snapshot rather than computed. A release REMINTS it, so this member is + // the only way a caller composing a following `expected_version` stays in + // step; types.Issue.RowVersion is `json:"-"`, so the issue body cannot + // carry it. + writeJSON(w, apigen.ReleaseIssueResponse{ + Issue: *result.Issue, + Changed: result.Changed, + Revision: result.Issue.RowVersion, + }) +} + +// releaseRequest decodes and validates the body, and reports whether the +// request may proceed. Every refusal here happens BEFORE any database work. +// +// The two guard members are validated AGAINST EACH OTHER at the edge, not only +// individually, because the role refuses the pair and the caller deserves to +// learn that from a 400 naming a member rather than from a generic refusal that +// cost two round trips. +func (s *Server) releaseRequest(w http.ResponseWriter, r *http.Request, id string) (issueops.ReleaseRequest, bool) { + members, res := decodeJSONObjectBody(w, r) + if res != nil { + s.fail(w, r, *res) + return issueops.ReleaseRequest{}, false + } + if offender, unknown := unknownMember(members, releaseRequestMembers); unknown { + s.failUnknownMember(w, r, offender, releaseRequestMembers) + return issueops.ReleaseRequest{}, false + } + + actor, ok := s.bodyActor(w, r, members) + if !ok { + return issueops.ReleaseRequest{}, false + } + expected, ok := s.releaseExpectedAssignee(w, r, members) + if !ok { + return issueops.ReleaseRequest{}, false + } + force, ok := s.booleanMember(w, r, members, releaseForceMember) + if !ok { + return issueops.ReleaseRequest{}, false + } + // The pair the role refuses, refused here by name. They are answers to the + // same question and they disagree — the guard says "only if X still holds + // it" and force says "whoever holds it" — so honoring either would be this + // server picking which half of the request the caller meant. + // + // It names `force`, the member that is redundant given the guard, so a + // caller that added a belt-and-braces flag learns which one to drop. + if force && expected != nil { + s.fail(w, r, InvalidArgument(releaseForceMember, ReasonInvalidValue, + "`"+releaseForceMember+"` and `"+releaseExpectedAssigneeMember+"` disagree about which claim to release; send one")) + return issueops.ReleaseRequest{}, false + } + + return issueops.ReleaseRequest{ + Actor: actor, + IssueID: id, + ExpectedAssignee: expected, + Force: force, + }, true +} + +// releaseExpectedAssignee reads the optional compare-and-set guard. +// +// ABSENT AND ONLY ABSENT selects the unconditional path, so this answers a +// POINTER: the role models "do not check" as nil and this member has no other +// spelling for it. Explicit `null` is a 400 rather than a second spelling of +// absent, the rule every optional member on this surface follows. +// +// THE EMPTY STRING IS A 400 — the one place this member disagrees with +// updateIssue's `expected_assignee`, where an empty string is a real guard +// meaning "expected unassigned". "Release a row nobody holds" describes no +// release, so the role refuses it and this refuses it at the edge, where the +// 400 can name the member. Emptiness is judged AFTER trimming, matching the +// role, and the value is passed on UNTRIMMED, also matching the role: a padded +// expectation must lose every time rather than intermittently. +// +// It is not length- or pattern-checked the way an actor is. This value is +// COMPARED and never stored, so a value no assignee column could hold simply +// cannot match, and refusing it here would be a refusal the role does not have. +func (s *Server) releaseExpectedAssignee(w http.ResponseWriter, r *http.Request, members map[string]json.RawMessage) (*string, bool) { + raw, present := members[releaseExpectedAssigneeMember] + if !present { + return nil, true + } + refuse := func(detail string) (*string, bool) { + s.fail(w, r, InvalidArgument(releaseExpectedAssigneeMember, ReasonInvalidValue, detail)) + return nil, false + } + var value *string + if err := json.Unmarshal(raw, &value); err != nil || value == nil { + return refuse("`" + releaseExpectedAssigneeMember + "` must be a string") + } + if strings.TrimSpace(*value) == "" { + return refuse("`" + releaseExpectedAssigneeMember + "` is empty after trimming; omit it to release whatever claim is there, " + + "or read the row if you meant to assert that nobody holds it") + } + return value, true +} + +// failRelease answers a failed release, mapping the role's TYPED refusals onto +// the frozen codes. +// +// EVERY 409 BRANCH IS MATCHED BEFORE THE ErrValidation AND ErrNotFound ARMS, +// and that order is the whole correctness of this function — failUpdate's +// hazard, in a sharper form. None of the four refusals below is wrapped in +// ErrValidation by any leg: ReleaseIssueInTx returns its two classifications +// bare and passes the raw seam's two through unchanged, and all three database +// legs reach that one function. Below a generic arm they would fall into +// failErr and be answered 500 — on every leg, for four conditions this document +// names by code. +// +// NO BRANCH QUOTES THE ROLE'S MESSAGE. Every one of these refusals formats its +// observation into prose — the holder it found, the status it saw — and this +// surface publishes typed members or nothing. Three of the four have nothing +// typed to publish, so they publish nothing; see the codes' own docs. The real +// error goes to the log with the request id. +func (s *Server) failRelease(w http.ResponseWriter, r *http.Request, request issueops.ReleaseRequest, err error) { + // The 4xx path does not log by default, so the refusals whose real reason + // the response replaces with the server's own words are recorded here. + refused := func() { + s.event("request_refused", "request_id", requestInfo(r.Context()).id, "error", err.Error()) + } + + switch { + // THE GUARD, and it is matched first because it is the only refusal here + // with a member to carry. `expected_assignee` is the REQUEST's value and + // there is no `actual_assignee` beside it: the refusal rolled its + // transaction back, and the role carries the holder it observed in prose + // only — no ClaimConflictError equivalent exists for this sentinel. That is + // updateIssue's rule for the same guard, unchanged. + case errors.Is(err, issueops.ErrAssigneeMismatch): + res := PreconditionFailed() + res.Problem.Param = releaseGuardParam() + if request.ExpectedAssignee != nil { + res = res.WithExpectedAssignee(*request.ExpectedAssignee) + } + s.fail(w, r, res) + + // THE OWNERSHIP FENCE, answered with the code updateIssue already gives the + // same situation: a live foreign owner refusing a write, with a force + // bypass and a name-the-holder bypass. No `assignee` member, for the reason + // that operation states — the fence refuses without naming the holder, so + // absence means "re-read the row" and never "nobody holds it". + case errors.Is(err, issueops.ErrNotOwner): + s.fail(w, r, newResult(CodeAlreadyClaimed, + "this issue is held by another actor; send `"+releaseForceMember+"`, or name the holder in `"+ + releaseExpectedAssigneeMember+"`")) + + // THE ROW REFUSING TO PRODUCE A RELEASE AT ALL, under one code and with no + // member telling the two conditions apart. Neither sentinel carries a typed + // observation, and this surface does not scrape prose to invent one; the + // code's own doc carries the analysis, including why splitting later is the + // direction that stays open. + // + // The detail names both conditions rather than guessing between them, so a + // human reading a `bd unclaim` failure is not told a closed issue is + // unclaimed or the reverse. + case errors.Is(err, issueops.ErrNotClaimed), errors.Is(err, issueops.ErrNotReleasable): + refused() + s.fail(w, r, newResult(CodeNotReleasable, + "this issue holds no claim, or its status is neither `open` nor `in_progress`; nothing was written. "+ + "Read the row rather than assuming the claim is gone: a status this workspace configured can refuse a "+ + "release while the row is still assigned")) + + case errors.Is(err, storage.ErrNotFound): + s.fail(w, r, NotFound()) + + case !errors.Is(err, storage.ErrValidation): + s.failErr(w, r, err) + + // DEFENSIVE. Every request-validation refusal the role has is refused at the + // edge above — an empty actor, a blank guard, force beside the guard — and + // the dispatcher guarantees a non-empty id, so nothing should reach this. + // It stays because the alternative if that ever stops being true is a 500 + // for a request the caller could have fixed. + default: + refused() + s.fail(w, r, InvalidArgument("", ReasonInvalidValue, + "the request was refused by this workspace's own validation; nothing was written")) + } +} + +// releaseGuardParam names the guard member on a `precondition_failed`, so a +// client reads one member to find the offending input whichever way the request +// was refused. It is a function for updateGuardParam's reason: `param` is a +// pointer on the envelope and a package-level address would be shared state. +func releaseGuardParam() *string { + member := releaseExpectedAssigneeMember + return &member +} diff --git a/internal/httpapi/release_test.go b/internal/httpapi/release_test.go new file mode 100644 index 000000000..d9eb30250 --- /dev/null +++ b/internal/httpapi/release_test.go @@ -0,0 +1,480 @@ +package httpapi + +import ( + "errors" + "fmt" + "net/http" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// These are pure: the release path runs end to end over a real listener against +// a fake ROLE, so the wire edge — the path split, the media type, the body +// vocabulary, the guard pair, the response shape and every problem document — +// is covered on every pull request by the unconditional Go test job. +// +// What a fake cannot prove is that a REFUSED release left the claim standing, +// and that is the property the whole non-idempotence argument rests on. That +// lives in cmd/bd's proxied-server integration test against real Dolt +// (TestProxiedServerServeRelease). The role-level transition — what the row +// looks like afterwards, the lease, the event — is owned against a real store +// by internal/storage/uow/releaser_contract_test.go, which this slice cites +// rather than duplicates. + +const releasePath = "/v0/beads/issues/bd-1:release" + +func (ts *testServer) releaseIssue(t *testing.T, path, body string) *http.Response { + t.Helper() + return ts.postBody(t, path, "application/json", body) +} + +// newReleaseServer wires a server over the store-shaped source with a releaser +// the case controls. Every other role is a placeholder: Listen refuses a +// partial source, and a release reaches none of them. +func newReleaseServer(t *testing.T, releaser *roleReleaser) *testServer { + t.Helper() + return newTestServer(t, rolesConfig(Config{Releaser: releaser})) +} + +// releasedIssue is the ANONYMOUS post-state: assignee cleared, status open. It +// is the same row no matter who emptied it, which is the whole reason this +// operation refuses rather than answering an idempotent 200. +func releasedIssue(id string, revision int64) *types.Issue { + issue := seededIssue(id, "", types.StatusOpen) + issue.RowVersion = revision + return issue +} + +// TestReleaseWritesOnceAndAnswersWithTheRowItWrote is the happy path and the +// three things a client depends on: the role receives exactly what the body +// asked for, the response carries the row as it stands after the release, and +// `revision` carries the REMINTED token off that same row. +func TestReleaseWritesOnceAndAnswersWithTheRowItWrote(t *testing.T) { + releaser := &roleReleaser{result: issueops.ReleaseResult{Issue: releasedIssue("bd-1", 77), Changed: true}} + ts := newReleaseServer(t, releaser) + + resp := ts.releaseIssue(t, releasePath, `{"actor":"alice"}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + + got := releaser.releaseRequests() + if len(got) != 1 { + t.Fatalf("the role received %+v, want exactly one request", got) + } + // The unconditional path: nil selects it, and nothing else does. + if got[0].Actor != "alice" || got[0].IssueID != "bd-1" || got[0].ExpectedAssignee != nil || got[0].Force { + t.Fatalf("the role received %+v, want an unconditional release of bd-1 by alice", got[0]) + } + + body := decodeBody(t, resp) + if body["changed"] != true { + t.Errorf("changed = %v, want true — the role reports it true on every answer it returns without an error", body["changed"]) + } + if body["revision"] != float64(77) { + t.Errorf("revision = %v, want the post-release token off the row the role answered with", body["revision"]) + } + issue, ok := body["issue"].(map[string]any) + if !ok { + t.Fatalf("issue = %#v, want an object", body["issue"]) + } + // The ANONYMOUS post-state, as the wire spells it: status open, and no + // `assignee` at all — types.Issue omits the member when it is empty, so a + // client reads the release's outcome from the member's ABSENCE. + if issue["status"] != string(types.StatusOpen) { + t.Errorf("status = %v, want %s: %v", issue["status"], types.StatusOpen, issue) + } + if assignee, present := issue["assignee"]; present && assignee != "" { + t.Errorf("assignee = %v; a released row holds no claim", assignee) + } +} + +// TestReleaseHasNoIdempotentAnswer is the operation's defining property, tested +// from the wire rather than assumed from the role: an unheld row is a REFUSAL, +// and it must not arrive as a 200 carrying `changed: false`. +// +// The distinction is not stylistic. A 200 here would report one answer for "I +// released this twice", "a reaper beat me to it" and "nothing ever claimed it", +// because the post-state is identical in all three and there is nothing left on +// the row to tell them apart. It would also be a value no role produces: +// ReleaseResult.Changed is true on every non-error answer. +func TestReleaseHasNoIdempotentAnswer(t *testing.T) { + releaser := &roleReleaser{err: fmt.Errorf("%w: bd-1 has no assignee to release", issueops.ErrNotClaimed)} + ts := newReleaseServer(t, releaser) + + resp := ts.releaseIssue(t, releasePath, `{"actor":"alice"}`) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(CodeNotReleasable) { + t.Fatalf("code = %v, want %s", body["code"], CodeNotReleasable) + } + // No member distinguishes the two conditions this code covers, and a client + // must not learn to dispatch on one appearing. + for _, member := range []string{"assignee", "issue_status", "expected_assignee", "actual_assignee"} { + if _, present := body[member]; present { + t.Errorf("not_releasable carries %q; the code documents no discriminating member", member) + } + } +} + +// TestReleaseAnswersTheRefusalsTheRoleRaises walks the whole 409 vocabulary and +// the 404, each from the sentinel the role actually returns. +// +// EVERY ARM IS MATCHED BEFORE ErrValidation AND ErrNotFound in failRelease, and +// that is what this table exists to pin: none of these sentinels is wrapped in +// ErrValidation by any leg, so an arm placed below a generic one would be a 500 +// on every leg for a condition the document names by code. Deleting any single +// case from failRelease must fail a row here. +func TestReleaseAnswersTheRefusalsTheRoleRaises(t *testing.T) { + for _, tc := range []struct { + name string + body string + err error + status int + code Code + param string + members map[string]any + }{ + { + name: "a status that does not accept a release", + body: `{"actor":"alice"}`, + err: fmt.Errorf("%w: bd-1 has status %q, which is neither %q nor %q", issueops.ErrNotReleasable, "closed", "open", "in_progress"), + status: http.StatusConflict, + code: CodeNotReleasable, + }, + { + name: "a row that holds no claim", + body: `{"actor":"alice"}`, + err: fmt.Errorf("%w: bd-1 has no assignee to release", issueops.ErrNotClaimed), + status: http.StatusConflict, + code: CodeNotReleasable, + }, + { + // The fence, answered with updateIssue's code for the identical + // situation. No `assignee` member: the fence refuses without naming + // the holder, so absence means "re-read the row". + name: "an unforced release by an actor that is not the holder", + body: `{"actor":"mallory"}`, + err: fmt.Errorf("%w: bd-1 is held by alice", issueops.ErrNotOwner), + status: http.StatusConflict, + code: CodeAlreadyClaimed, + }, + { + // The guard, carrying the REQUEST's expectation and no observation. + name: "a guard that missed", + body: `{"actor":"supervisor","expected_assignee":"alice"}`, + err: fmt.Errorf("%w: bd-1 is held by %q, expected %q", issueops.ErrAssigneeMismatch, "bob", "alice"), + status: http.StatusConflict, + code: CodePreconditionFailed, + param: releaseExpectedAssigneeMember, + members: map[string]any{"expected_assignee": "alice"}, + }, + { + name: "an id naming no row on either plane", + body: `{"actor":"alice"}`, + err: fmt.Errorf("get bd-1: %w", issueops.ErrNotFound), + status: http.StatusNotFound, + code: CodeNotFound, + }, + { + // Defensive: every validation refusal the role has is refused at the + // edge. It must still be a 400 rather than a 500 if that stops + // being true. + name: "the role's own validation, which the edge should have caught", + body: `{"actor":"alice"}`, + err: fmt.Errorf("%w: release requires an actor", issueops.ErrValidation), + status: http.StatusBadRequest, + code: CodeInvalidArgument, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ts := newReleaseServer(t, &roleReleaser{err: tc.err}) + + resp := ts.releaseIssue(t, releasePath, tc.body) + if resp.StatusCode != tc.status { + t.Fatalf("status = %d, want %d: %s", resp.StatusCode, tc.status, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(tc.code) { + t.Fatalf("code = %v, want %s", body["code"], tc.code) + } + if tc.param != "" && body["param"] != tc.param { + t.Errorf("param = %v, want %q", body["param"], tc.param) + } + for member, want := range tc.members { + if body[member] != want { + t.Errorf("%s = %v, want %v", member, body[member], want) + } + } + // The refusals replace the role's prose with the server's own + // words, so the role's message must not travel on the wire: it + // names holders and statuses this surface publishes typed or not + // at all. + if detail, _ := body["detail"].(string); detail != "" && tc.err != nil { + if detail == tc.err.Error() { + t.Errorf("detail quotes the role's message verbatim: %q", detail) + } + } + // `actual_assignee` is declared on the envelope for an operation + // whose role can report what it found. This one cannot. + if _, present := body["actual_assignee"]; present { + t.Errorf("the refusal carries actual_assignee, which no release refusal can honestly fill") + } + }) + } +} + +// TestReleaseRefusesTheGuardPair pins the one refusal this handler owns rather +// than forwards. `force` and `expected_assignee` are answers to the same +// question and they disagree, so honoring either would be the server picking +// which half of the request the caller meant. +// +// It is refused at the EDGE, before any database work, which is what lets the +// 400 name a member. +func TestReleaseRefusesTheGuardPair(t *testing.T) { + releaser := &roleReleaser{result: issueops.ReleaseResult{Issue: releasedIssue("bd-1", 1), Changed: true}} + ts := newReleaseServer(t, releaser) + + resp := ts.releaseIssue(t, releasePath, `{"actor":"alice","expected_assignee":"bob","force":true}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(CodeInvalidArgument) || body["param"] != releaseForceMember { + t.Errorf("code/param = %v/%v, want %s on `%s`", body["code"], body["param"], CodeInvalidArgument, releaseForceMember) + } + if got := releaser.releaseRequests(); len(got) != 0 { + t.Errorf("the pair reached the role: %+v", got) + } +} + +// TestReleaseExpectedAssigneeDistinguishesAbsentFromEmpty is the member's whole +// contract, and the one place it disagrees with updateIssue's same-named guard. +// +// Absent selects the unconditional path. The empty string — and anything blank +// after trimming — is a 400 rather than a guard meaning "expected unassigned", +// because "release a row nobody holds" describes no release at all. A caller +// asking whether a row is unheld is asking a READER a question. +func TestReleaseExpectedAssigneeDistinguishesAbsentFromEmpty(t *testing.T) { + for _, tc := range []struct { + name string + body string + status int + expected *string + }{ + {name: "absent selects the unconditional path", body: `{"actor":"alice"}`, status: http.StatusOK}, + {name: "the empty string is refused", body: `{"actor":"alice","expected_assignee":""}`, status: http.StatusBadRequest}, + {name: "blank after trimming is refused", body: `{"actor":"alice","expected_assignee":" "}`, status: http.StatusBadRequest}, + {name: "explicit null is refused", body: `{"actor":"alice","expected_assignee":null}`, status: http.StatusBadRequest}, + {name: "a non-string is refused", body: `{"actor":"alice","expected_assignee":7}`, status: http.StatusBadRequest}, + { + name: "a real holder guards the release", + body: `{"actor":"supervisor","expected_assignee":"alice"}`, + status: http.StatusOK, + expected: strPtr("alice"), + }, + { + // The value travels UNTRIMMED, matching the role: a padded + // expectation must lose every time rather than intermittently. + name: "a padded holder reaches the role padded", + body: `{"actor":"supervisor","expected_assignee":" alice"}`, + status: http.StatusOK, + expected: strPtr(" alice"), + }, + } { + t.Run(tc.name, func(t *testing.T) { + releaser := &roleReleaser{result: issueops.ReleaseResult{Issue: releasedIssue("bd-1", 1), Changed: true}} + ts := newReleaseServer(t, releaser) + + resp := ts.releaseIssue(t, releasePath, tc.body) + if resp.StatusCode != tc.status { + t.Fatalf("status = %d, want %d: %s", resp.StatusCode, tc.status, readAll(t, resp)) + } + if tc.status != http.StatusOK { + if body := decodeBody(t, resp); body["param"] != releaseExpectedAssigneeMember { + t.Errorf("param = %v, want %q", body["param"], releaseExpectedAssigneeMember) + } + if got := releaser.releaseRequests(); len(got) != 0 { + t.Errorf("a refused guard reached the role: %+v", got) + } + return + } + got := releaser.releaseRequests() + if len(got) != 1 { + t.Fatalf("the role received %+v, want exactly one request", got) + } + switch { + case tc.expected == nil && got[0].ExpectedAssignee != nil: + t.Errorf("ExpectedAssignee = %q, want nil — only absence selects the unconditional path", *got[0].ExpectedAssignee) + case tc.expected != nil && got[0].ExpectedAssignee == nil: + t.Errorf("ExpectedAssignee = nil, want %q", *tc.expected) + case tc.expected != nil && *got[0].ExpectedAssignee != *tc.expected: + t.Errorf("ExpectedAssignee = %q, want %q", *got[0].ExpectedAssignee, *tc.expected) + } + }) + } +} + +// TestReleaseForwardsForce: the fence is the ROLE's, so the handler's whole job +// is to pass the bypass through unexamined. +func TestReleaseForwardsForce(t *testing.T) { + releaser := &roleReleaser{result: issueops.ReleaseResult{Issue: releasedIssue("bd-1", 2), Changed: true}} + ts := newReleaseServer(t, releaser) + + resp := ts.releaseIssue(t, releasePath, `{"actor":"supervisor","force":true}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + got := releaser.releaseRequests() + if len(got) != 1 || !got[0].Force { + t.Fatalf("the role received %+v, want one forced release", got) + } +} + +// TestReleaseRefusesUnknownAndMalformedBodies is the body vocabulary, refused BY +// NAME. The schema is additionalProperties: false, and a client that has stopped +// parsing prose can only enforce that if the server names the offender. +func TestReleaseRefusesUnknownAndMalformedBodies(t *testing.T) { + for _, tc := range []struct { + name string + body string + param string + }{ + {name: "an unknown member", body: `{"actor":"alice","expected_version":3}`, param: "expected_version"}, + {name: "a missing actor", body: `{"force":true}`, param: claimActorMember}, + {name: "an actor that is blank after trimming", body: `{"actor":" "}`, param: claimActorMember}, + {name: "an actor carrying a newline", body: `{"actor":"alice\nbd: released by mallory"}`, param: claimActorMember}, + {name: "a non-boolean force", body: `{"actor":"alice","force":"yes"}`, param: releaseForceMember}, + {name: "an explicitly null force", body: `{"actor":"alice","force":null}`, param: releaseForceMember}, + } { + t.Run(tc.name, func(t *testing.T) { + releaser := &roleReleaser{} + ts := newReleaseServer(t, releaser) + + resp := ts.releaseIssue(t, releasePath, tc.body) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(CodeInvalidArgument) { + t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument) + } + if body["param"] != tc.param { + t.Errorf("param = %v, want %q", body["param"], tc.param) + } + if got := releaser.releaseRequests(); len(got) != 0 { + t.Errorf("a refused body reached the role: %+v", got) + } + }) + } +} + +// TestReleaseRefusesAReleaserThatAnswersWithNothing pins checkedReleaser. The +// handler dereferences the result's issue and reads its RowVersion, so a +// caller-supplied role reporting success without a row is a nil dereference on +// a live server — and there is no wire code that honestly describes it. +func TestReleaseRefusesAReleaserThatAnswersWithNothing(t *testing.T) { + ts := newReleaseServer(t, &roleReleaser{result: issueops.ReleaseResult{Changed: true}}) + + resp := ts.releaseIssue(t, releasePath, `{"actor":"alice"}`) + if resp.StatusCode != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["code"] != string(CodeInternal) { + t.Errorf("code = %v, want %s", body["code"], CodeInternal) + } + // THE STATUS ALONE PROVES NOTHING, which is why this asserts the log. The + // server recovers panics into the same 500 with the same code, so a test + // that stopped at the status would pass with the wrapper deleted and the + // handler dereferencing nil on a live server. What the wrapper buys is the + // fault ARRIVING AS AN ERROR NAMING ITSELF, which is exactly what the panic + // it replaces did not produce. + line := findLogLine(t, ts.stderr.String(), "the releaser reported success without an issue") + if !strings.Contains(line, "bd-1") { + t.Errorf("the logged fault does not name the issue it was asked about:\n%s", line) + } +} + +// TestReleasePathReachesItsHandler drives the path the DOCUMENT spells, which +// is the one thing route parity cannot check for a custom-method row: it +// declares its spec path instead of deriving it from the pattern. The parity +// test bounds the shape of that exception; only a request proves the pattern +// serves the documented path — and, on a shared dispatcher, that this verb is +// not answered by whichever row happens to be first. +func TestReleasePathReachesItsHandler(t *testing.T) { + releaser := &roleReleaser{result: issueops.ReleaseResult{Issue: releasedIssue("bd-1", 1), Changed: true}} + ts := newReleaseServer(t, releaser) + + resp := ts.releaseIssue(t, releasePath, `{"actor":"alice"}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("POST the documented release path: status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + line := findLogLine(t, ts.stderr.String(), "path="+releasePath) + if !strings.Contains(line, "op="+OpReleaseIssue) { + t.Errorf("the documented release path is served by another operation:\n%s", line) + } +} + +// TestReleaseIsNotReachableThroughTheClaimsErrorVocabulary guards the reuse +// decision from the direction that would make it wrong. `already_claimed` is +// borrowed for the ownership fence; the claim's OTHER conflict, not_claimable, +// is deliberately absent from this operation, because an open unassigned row is +// the most claimable row a workspace has and answering that about a release +// refusal would send a client somewhere there is nothing to find. +func TestReleaseIsNotReachableThroughTheClaimsErrorVocabulary(t *testing.T) { + for _, code := range operationCodes[OpReleaseIssue] { + if code == CodeNotClaimable { + t.Fatalf("releaseIssue documents %s; see CodeNotReleasable for why that reuse was refused", code) + } + } + // And the borrowed one is really borrowed rather than re-minted. + if !containsCode(operationCodes[OpReleaseIssue], CodeAlreadyClaimed) { + t.Errorf("releaseIssue does not document %s; the ownership fence has no other code", CodeAlreadyClaimed) + } +} + +func containsCode(codes []Code, want Code) bool { + for _, code := range codes { + if code == want { + return true + } + } + return false +} + +func strPtr(s string) *string { return &s } + +// releaseSentinels is the set failRelease must classify, asserted as a set so a +// sentinel added to the role without a wire arm fails here rather than reaching +// a client as a 500. +func TestEveryReleaseSentinelIsClassified(t *testing.T) { + for _, sentinel := range []error{ + issueops.ErrNotClaimed, + issueops.ErrNotReleasable, + issueops.ErrNotOwner, + issueops.ErrAssigneeMismatch, + issueops.ErrNotFound, + } { + t.Run(sentinel.Error(), func(t *testing.T) { + ts := newReleaseServer(t, &roleReleaser{err: fmt.Errorf("release bd-1: %w", sentinel)}) + + resp := ts.releaseIssue(t, releasePath, `{"actor":"alice","expected_assignee":"bob"}`) + if resp.StatusCode >= http.StatusInternalServerError { + t.Fatalf("%v reached the client as a %d; it must be classified in failRelease: %s", + sentinel, resp.StatusCode, readAll(t, resp)) + } + code := Code(decodeBody(t, resp)["code"].(string)) + if !containsCode(operationCodes[OpReleaseIssue], code) { + t.Errorf("%v produced %s, which this operation does not document", sentinel, code) + } + if errors.Is(sentinel, issueops.ErrValidation) { + t.Fatalf("%v is wrapped in ErrValidation; failRelease's ordering assumes it is not", sentinel) + } + }) + } +} diff --git a/internal/httpapi/roles.go b/internal/httpapi/roles.go index 78ef43a98..c732c93d5 100644 --- a/internal/httpapi/roles.go +++ b/internal/httpapi/roles.go @@ -170,3 +170,25 @@ func (c checkedClaimer) Claim(ctx context.Context, req issueops.ClaimRequest) (i } return result, err } + +// checkedReleaser is the releaser the release handler is handed. +// +// It exists for checkedClaimer's reason exactly: handleRelease writes +// *result.Issue and reads its RowVersion, so a role that reported success +// without the row would panic on a live server. +type checkedReleaser struct{ inner issueops.Releaser } + +// Release refuses a result that reports success without the row the response +// body is built from. +// +// The generic 500, for checkedClaimer's reason and one of its own: there is no +// wire code that fits and there must not be. A 409 would say the row refused +// the release when the role said it did not, and a 404 would say the issue does +// not exist when nothing here knows that. It is a broken implementation. +func (c checkedReleaser) Release(ctx context.Context, req issueops.ReleaseRequest) (issueops.ReleaseResult, error) { + result, err := c.inner.Release(ctx, req) + if err == nil && result.Issue == nil { + return issueops.ReleaseResult{}, fmt.Errorf("release %q: the releaser reported success without an issue", req.IssueID) + } + return result, err +} diff --git a/internal/httpapi/roles_test.go b/internal/httpapi/roles_test.go index bf64f1579..a1c1dbcdd 100644 --- a/internal/httpapi/roles_test.go +++ b/internal/httpapi/roles_test.go @@ -449,6 +449,34 @@ func (c *roleClaimer) claimRequests() []issueops.ClaimRequest { return append([]issueops.ClaimRequest(nil), c.claims...) } +// roleReleaser is the store-shaped source's claim-release role. The release +// tests drive it directly, for the reason roleLifecycle exists: the wire edge — +// the body vocabulary, the guard pair, the refusal mapping — is provable +// against a fake, and the transition itself belongs to the role's own contract. +type roleReleaser struct { + result issueops.ReleaseResult + err error + + mu sync.Mutex + releases []issueops.ReleaseRequest +} + +func (c *roleReleaser) Release(_ context.Context, req issueops.ReleaseRequest) (issueops.ReleaseResult, error) { + c.mu.Lock() + c.releases = append(c.releases, req) + c.mu.Unlock() + if c.err != nil { + return issueops.ReleaseResult{}, c.err + } + return c.result, nil +} + +func (c *roleReleaser) releaseRequests() []issueops.ReleaseRequest { + c.mu.Lock() + defer c.mu.Unlock() + return append([]issueops.ReleaseRequest(nil), c.releases...) +} + // roleLifecycle is the store-shaped source's guarded-mutation role. Every case // hands Listen a COMPLETE source, so this exists partly to be a placeholder — // but the close tests drive it directly, which is what the claim precedent @@ -638,6 +666,9 @@ func rolesConfig(cfg Config) Config { if cfg.Claimer == nil { cfg.Claimer = &roleClaimer{} } + if cfg.Releaser == nil { + cfg.Releaser = &roleReleaser{} + } if cfg.Lifecycle == nil { cfg.Lifecycle = &roleLifecycle{} } diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index 1be8c535f..68400f30d 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -359,6 +359,19 @@ var routeTable = []route{ implemented: true, handler: (*Server).handleClaim, }, + { + op: OpReleaseIssue, + method: http.MethodPost, + // The claim's inverse, on the dispatcher the close built. A fifth row on + // this pattern is a row; everything the claim row says about the + // wildcard's width holds here unchanged. + pattern: customMethodPattern, + specPath: "/v0/beads/issues/{id}:release", + customMethod: ":release", + capability: "issues.release", + implemented: true, + handler: (*Server).handleRelease, + }, { op: OpCloseIssue, method: http.MethodPost, diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 12d1ce3d1..ccb9d0adf 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -173,6 +173,13 @@ type Config struct { // server, so a rebuild would buy nothing. Reader issueops.Reader Claimer issueops.Claimer + // Releaser is the claim's inverse, behind + // POST /v0/beads/issues/{id}:release. It is its own field rather than a + // method on Claimer for the reason the role is its own interface: a caller + // entitled to give its own work back is very often not entitled to take + // new work, so a surface carrying both hands out a capability it should not + // be able to reach. + Releaser issueops.Releaser // Lifecycle is the guarded-mutation role behind the issue lifecycle // operations. Required on the same terms as every field here, and the // hook-firing refusal below bites hardest on it: a store's own @@ -284,6 +291,7 @@ type Server struct { // names because a struct cannot carry both. issueReader issueops.Reader issueClaimer issueops.Claimer + issueReleaser issueops.Releaser issueLifecycle issueops.Lifecycle settings issueops.WorkspaceConfig issueStats issueops.StatsReporter @@ -416,6 +424,7 @@ func Listen(cfg Config) (*Server, error) { provider: cfg.Provider, issueReader: cfg.Reader, issueClaimer: cfg.Claimer, + issueReleaser: cfg.Releaser, issueLifecycle: cfg.Lifecycle, settings: cfg.Settings, issueStats: cfg.Stats, @@ -536,12 +545,12 @@ func Listen(cfg Config) (*Server, error) { // "all or nothing" would turn an honest condition into a special case inside // three functions. It is checked once, on its own, below. func sourceRoles(cfg Config) []any { - return []any{cfg.Reader, cfg.Claimer, cfg.Lifecycle, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS} + return []any{cfg.Reader, cfg.Claimer, cfg.Releaser, cfg.Lifecycle, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS} } // roleSourceNames spells sourceRoles for the refusal message, in the same // order, so a caller reading the error learns the whole set it must pass. -const roleSourceNames = "Reader, Claimer, Lifecycle, Settings, Stats, CycleDetector, EdgeReader, BlockingAnnotator, TreeWalker, ReadyCounter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS" +const roleSourceNames = "Reader, Claimer, Releaser, Lifecycle, Settings, Stats, CycleDetector, EdgeReader, BlockingAnnotator, TreeWalker, ReadyCounter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS" func anyRoleSet(cfg Config) bool { return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil }) @@ -733,6 +742,26 @@ func (s *Server) claimer(r *http.Request) (issueops.Claimer, error) { return checkedClaimer{inner: cl}, nil } +// releaser returns the claim-release surface for one request. +// +// Built the same two ways as claimer above and for the same reasons: the +// configured role on the roles source, and on the provider source one built per +// request so its units of work are timed into THIS request's log line, held by +// INTERFACE so uow.ReleaserSource is load-bearing rather than decorative — and, +// from either source, wrapped in checkedReleaser, because the handler +// dereferences the pointer the result carries. +func (s *Server) releaser(r *http.Request) (issueops.Releaser, error) { + if s.provider == nil { + return checkedReleaser{inner: s.issueReleaser}, nil + } + var src uow.ReleaserSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())} + rel, err := src.Releaser() + if err != nil { + return nil, err + } + return checkedReleaser{inner: rel}, nil +} + // lifecycle returns the guarded issue-mutation surface for one request. // // Built the same two ways as claimer above and for the same reasons: the diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 6196783d0..832207d36 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -599,7 +599,7 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) { "dependencies.tree", "events.list", "events.watch", "issues.batchApply", "issues.batchCreate", "issues.casMetadata", "issues.claim", "issues.close", "issues.create", "issues.delete", "issues.get", "issues.list", - "issues.query", "issues.reopen", "issues.sweep", "issues.update", + "issues.query", "issues.release", "issues.reopen", "issues.sweep", "issues.update", "memories.forget", "memories.get", "memories.list", "memories.remember", "ready.count", "ready.list", "stats.get", diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index 20f8f0ee9..ae1a9229f 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -65,6 +65,7 @@ info: Operations with no parameters at all (`GET /healthz`, `GET /v0/beads/context`, `GET /v0/beads/dependencies/cycles`, `POST /v0/beads/issues/{id}:claim`, + `POST /v0/beads/issues/{id}:release`, `POST /v0/beads/issues/{id}:close`, `POST /v0/beads/issues/{id}:reopen`, `POST /v0/beads/issues/{id}:casMetadata`, `POST /v0/beads/issues:sweep`, @@ -1739,6 +1740,240 @@ paths: '503': $ref: '#/components/responses/Unavailable' + /v0/beads/issues/{id}:release: + post: + operationId: releaseIssue + summary: Give back the claim on an issue + description: >- + The claim's inverse, and what `bd unclaim` spells. It ends the + OWNERSHIP and leaves the work open for the next taker: assignee + cleared, status the literal `open`, `started_at` cleared, the lease + dropped, and `revision` reminted so a concurrent reclaim or close + conflicts rather than silently merging. + + + It is a named lifecycle action rather than a `patch`, for + `POST /v0/beads/issues/{id}:close`'s reason: an update spells a release + as three fields at a time, which puts the transition's definition in + the CALLER, and the lease it drops is the part a patch cannot express + at all. + + + The caller always names the actor, for + `POST /v0/beads/issues/{id}:claim`'s reason. HERE IT IS ALSO THE + OWNERSHIP FENCE'S SUBJECT: a release carrying neither + `expected_assignee` nor `force` succeeds only while `actor` is the + current holder. That is not authentication — this surface has none, and + `actor` is caller-asserted provenance exactly as it is on the claim — + it is the same anti-yank guard the claim gets from refusing a foreign + holder, pointed the other way. + + + ## NOT IDEMPOTENT, which is the one thing to read before adopting it + + + A release over a row that holds NO claim is `409` / `not_releasable`, + never a 200. There is no `already_released` member here and there must + not be one, because the post-state is ANONYMOUS: "I released this + twice", "a reaper beat me to it" and "nothing ever claimed it" leave + the identical row — assignee cleared, status open, `started_at` gone — + so one 200 would report one answer for three situations that want + different things from a caller. `claimIssue` can afford + `already_claimed: true` because a claim's post-state NAMES the + claimant, and this operation has nothing left on the row to name. + + + ON `not_releasable`, READ THE ROW. Do NOT treat the code as "already + released", however ordinary that case is for you — it is the one + shortcut this operation's taxonomy makes unsafe, and it is unsafe in + the direction that strands work. + + + The code covers TWO conditions and publishes no member telling them + apart (see the `409` below). One of them is "nothing holds this". The + other is "the status will not accept a release", which is true of a row + that is CLOSED and equally true of a row parked in a status this + workspace configured — and such a row can still be ASSIGNED. A reaper + that read this code as success would book a claim as dropped while it + is still held, by an agent that is already gone, with nothing left to + free it. That is exactly the stranding this operation resolves ids + across both planes to prevent, reintroduced through the refusal + vocabulary instead of through the id. + + + So the recovery is a read: the row tells you which of the two you got — + an assignee, or none. That is one extra request on an uncommon path, + and it is the honest price of one code rather than two. A caller that + wants the distinction without the read should say so, and it arrives as + an ADDITION, which the `Problem.code` rules already tell clients to + tolerate. + + + ## The two ways to release a claim you do not hold + + + `expected_assignee` is a compare-and-set on the holder and REPLACES the + ownership fence: a caller that can name the current holder has + demonstrated the view the fence exists to protect, so `actor` need not + be that holder. It cannot release a claim that has since moved, which + is what makes it the safer of the two for a supervisor reaping one + named agent's abandoned work. + + + `force` ignores the holder entirely, and ignores NOTHING ELSE. It does + not make an unheld row releasable, it does not make a closed one + releasable, and it may not accompany `expected_assignee` — the two are + answers to the same question and they disagree, so sending both is a + 400. + + + ## Planes + + + The id resolves across BOTH planes, unlike + `POST /v0/beads/issues/{id}:claim` and like + `POST /v0/beads/issues/{id}:close`. The asymmetry is about which + direction strands work: a wisp can hold a claim, so an operation that + refused to release one would leave an ephemeral row owned by an agent + that is gone with no verb able to free it. A release whose target is a + wisp records no durable history entry. + + + ## Hooks and auto-commit + + + Hooks do not fire and the per-command auto-commit machinery does not + run, exactly as for `POST /v0/beads/issues/{id}:claim`. The only + durable effect is the single storage commit the role makes inside its + own transaction, which is what a proxied CLI write does today. + parameters: + - $ref: '#/components/parameters/IssueID' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ReleaseIssueRequest' + responses: + '200': + description: >- + The claim is released. The issue is open and unassigned, and the + body carries the row the release produced. + + + THE SET THIS SUCCEEDS OVER IS WIDER THAN `in_progress`, and a + client porting a guard needs to know it before it ports one. The + transition is defined over `open` AND `in_progress` alike, so a row + already in `open` that STILL HOLDS AN ASSIGNEE — the state a + partial write or an out-of-band status edit leaves behind — is + released here. A caller whose own release-if-current guarded on + `in_progress` did nothing for that row and reported no error; this + operation writes it. That is a genuine widening rather than a + restatement, and a client mapping "no error" to "I released it" + will now be right about rows it was previously never right about — + which is the point, and which is also why the mapping below is + written in terms of the CODES rather than in terms of success. + + + THE CODE-TO-OUTCOME MAPPING a release-if-current client wants, + stated here so it is written against a documented fact rather than + against a reading of the refusals. Four answers mean "no release + happened, and that is not an error": `not_releasable`, + `precondition_failed`, `already_claimed`, and `404`. A client + spelling that as a `(released, err)` pair returns + `(false, nil)` for all four. + + + `(false, nil)` MEANS "NO RELEASE HAPPENED". It does not mean the + claim is gone, and nothing here licenses that reading — see the + `not_releasable` paragraph in the operation description, which is + the one place the two readings come apart and the place a reaper + gets it wrong. A client that needs "is this row still held" asks a + READER; this operation answers whether IT released anything. + content: + application/json: + schema: + $ref: '#/components/schemas/ReleaseIssueResponse' + '400': + description: >- + Invalid request: an unknown query parameter, an unparseable or + oversized body, an unknown body member, an `actor` refused by the + rules `ClaimRequest.actor` states, an `expected_assignee` that is + empty after trimming, or `force` sent beside `expected_assignee`. + x-bd-codes: [invalid_argument] + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + '404': + $ref: '#/components/responses/NotFound' + '409': + description: >- + THE ORDER THESE ARE DECIDED IN IS PART OF THE ANSWER, because one + request can fail several ways at once. Request validation runs + before anything is read; then existence (the 404); then the row's + STATUS, because a closed issue is not a claim question at all; then + whether a claim exists; then the precondition or the fence, + whichever the request selected. So a CLOSED row guarded on a stale + `expected_assignee` is `not_releasable`, not + `precondition_failed` — do not read one refusal as evidence about + the checks that never ran. + + + `not_releasable` is the row refusing to produce a release at all, + and it covers two conditions: it holds no claim, or its status is + neither `open` nor `in_progress` — a closed issue, or one parked in + a status this workspace configured, which plainly can still hold a + claim. Neither has a bypass: `force` answers "may I release someone + else's claim" and has no opinion about whether there is a claim + here to release. + + + IT CARRIES NO MEMBER DISTINGUISHING THOSE TWO, and a client must + not look for one. The OBSERVATIONS the two refusals made — the + status one saw, the emptiness of the assignee the other saw — travel + in their messages, and this surface does not scrape its own prose to + manufacture a typed member. If the distinction ever earns one, it + arrives as an ADDITION (a new member, or a second code), which the + `Problem.code` rules already tell clients to tolerate; going the + other way, merging two codes back into one, is the change that + could not be made. + + + SO THE RECOVERY IS A READ, and it is a correctness rule rather than + a convenience: one of these two conditions leaves the row STILL + ASSIGNED, so a client that read this code as "already released" + books a claim as dropped while it stands. The operation description + says why that direction strands work. Read the row. + + + `already_claimed` is the ownership fence: an unforced, unguarded + release by an actor that is not the holder. It is `updateIssue`'s + assignee-fence code unchanged — the same situation, and the same + two bypasses, spelled `force` and `expected_assignee` here instead + of `force_assignee_transfer` and `expected_assignee` there. As + there, the `assignee` extension member is NOT attached: the fence + refuses without naming the holder, so a client re-reads the row. + + + `precondition_failed` is `expected_assignee` missing, INCLUDING + against a row that holds no claim — that is a mismatch rather than + `not_releasable`, because the caller asked about a specific holder + and the answer is that it is not the holder. It carries + `expected_assignee` (the value the REQUEST sent) and `param`, and + NO `actual_assignee`: the refusal rolled its transaction back, and + the role carries the holder it observed in prose only. That is + `updateIssue`'s rule for the same guard, unchanged. + x-bd-codes: [already_claimed, not_releasable, precondition_failed] + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + '500': + $ref: '#/components/responses/InternalError' + '503': + $ref: '#/components/responses/Unavailable' + /v0/beads/issues/{id}:close: post: operationId: closeIssue @@ -4896,7 +5131,7 @@ components: The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.create`, - `issues.claim`, + `issues.claim`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, @@ -6861,6 +7096,127 @@ components: nothing — the idempotent re-claim. A claim held by a DIFFERENT actor is a 409, not a 200 with this flag. + ReleaseIssueRequest: + type: object + additionalProperties: false + required: [actor] + properties: + actor: + type: string + minLength: 1 + maxLength: 256 + pattern: '^[^\u0000-\u001F\u007F-\u009F\u2028\u2029]+$' + description: >- + Who is releasing the claim. `ClaimRequest.actor`'s rules exactly: + the server trims it, then refuses an empty result, anything longer + than 256 BYTES (the `maxLength` above counts characters — the byte + limit is the binding one), and any control character including + newline. The value reaches the event the release records and the + storage commit message, so an unvalidated newline would forge + audit-trail lines. + + + It is REQUIRED, and for one reason beyond the audit trail: a + release is the moment work stops being owned, and the one question + asked of its history entry afterwards is who let it go. On the + unconditional path it is ALSO the ownership fence's subject — see + the operation description. + expected_assignee: + type: string + description: >- + Compare-and-set on the holder: the release proceeds only while the + issue is still assigned to this actor, and otherwise refuses with + `409` / `precondition_failed` naming this value, having written + nothing. + + + A MATCH REPLACES THE OWNERSHIP FENCE, so `actor` need not be the + holder. Sending it beside `force` is a 400: the two are answers to + the same question and they disagree. + + + THE COMPARISON IS SEPARATOR-INSENSITIVE AND NOTHING ELSE. + A run of `.`, `_` or `-` matches any other such run, so `agent-a`, + `agent_a` and `agent.a` are one holder — that is deliberate, so a + caller naming the holder under a different layer's spelling is a + match rather than a mismatch. NOTHING ELSE IS FORGIVEN: the value + is not trimmed and not case-folded, so `" agent-a"` and `Agent-a` + are both refusals. The server trims only far enough to tell a blank + expectation from a real one and never sends the trimmed form on, so + a caller that pads its expectation loses EVERY time rather than + intermittently. Compose it from a holder a read gave you. + + + THE EMPTY STRING IS A 400, and this is the one place this member + disagrees with `UpdateIssueRequest.expected_assignee`, where an + empty string is a real guard meaning "expected unassigned". Here + "release a row nobody holds" describes no release at all; a caller + that wants to assert a row is unheld is asking a READER a question, + not asking this operation to do nothing. Absent, and only absent, + selects the unconditional path. + + + IT IS NOT LENGTH- OR PATTERN-BOUNDED the way `actor` is, and the + asymmetry is deliberate: this value is COMPARED and never stored, + so a value no assignee column could hold simply cannot match, and + refusing it at the edge would be a refusal the role does not have. + force: + type: boolean + default: false + description: >- + Bypass the ownership fence, so an actor that is not the holder may + release the claim. It is the escape hatch `bd unclaim --force` + spells, for an abandoned claim whose holder crashed. + + + IT BYPASSES THE FENCE AND NOTHING ELSE. It does not make an unheld + row releasable, it does not make a closed one releasable, and it + never bypasses a precondition — sending it beside + `expected_assignee` is a 400 rather than a silent win for either. + + ReleaseIssueResponse: + type: object + required: [issue, changed, revision] + properties: + issue: + $ref: '#/components/schemas/Issue' + changed: + type: boolean + description: >- + Whether the release WROTE the row. It is TRUE on every 200 this + operation returns, because every shape that would not write is + refused above it — an unheld row is a 409, not an idempotent no-op. + DO NOT WRITE A `changed: false` BRANCH: no request reaches one. + + + It is published rather than omitted because `claimIssue` and + `updateIssue` publish the same fact, and a caller holding all three + should not have to read them two ways. It is also the negative + space that answers "where is the `already_released` member" — + there is none, and the operation description says why. + revision: + type: integer + format: int64 + description: >- + The row's optimistic-concurrency token AFTER the release, spelled + the way `UpdateIssueResponse.revision` spells it and carrying the + same promise: a read-modify-write loop composes its next + `expected_version` from THIS value, never from a number it + incremented itself. + + + A release REMINTS the token by design, so a caller that guarded a + following write on a version it read BEFORE the release will miss. + That is the point — a concurrent reclaim or close conflicts rather + than silently merging — and this member is how the caller stays in + step. + + + DECODE IT AS A 64-BIT INTEGER, for the reason + `UpdateIssueRequest.expected_version` spells out: an IEEE-754-double + parser corrupts it silently, and the corruption only shows up as a + `precondition_failed` on the NEXT request. + CloseIssueRequest: type: object additionalProperties: false @@ -7627,6 +7983,7 @@ components: emitted by the Host-header middleware on any route), `invalid_cursor` (400), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), + `not_releasable` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), diff --git a/internal/httpapi/spec_parity_test.go b/internal/httpapi/spec_parity_test.go index 27dde87a3..ec881c375 100644 --- a/internal/httpapi/spec_parity_test.go +++ b/internal/httpapi/spec_parity_test.go @@ -756,6 +756,37 @@ func TestCloseRequestMembersMatchTheHandler(t *testing.T) { } } +// TestReleaseRequestMembersMatchTheHandler is the close's gate for the release +// body, and it exists for the same reason. It matters a little more here than +// there because two of the three members are GUARDS: a documented guard the +// server refuses as unknown, or an undocumented one it honors, both change who +// is allowed to release whose claim. +func TestReleaseRequestMembersMatchTheHandler(t *testing.T) { + accepted := map[string]bool{} + for _, name := range releaseRequestMembers { + accepted[name] = true + } + + goFields := jsonTagNames(t, reflect.TypeOf(apigen.ReleaseIssueRequest{})) + if extra := diff(goFields, accepted); len(extra) > 0 { + t.Errorf("generated ReleaseIssueRequest declares members the release handler refuses as unknown: %v\n"+ + "teach releaseRequest to honor them, or the document promises a member the server turns down", extra) + } + if missing := diff(accepted, goFields); len(missing) > 0 { + t.Errorf("the release handler accepts members ReleaseIssueRequest does not declare: %v", missing) + } + + doc := loadSpec(t) + schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "ReleaseIssueRequest") + specProps := schemaProperties(t, doc, schema) + if extra := diff(specProps, accepted); len(extra) > 0 { + t.Errorf("the ReleaseIssueRequest schema documents members the release handler refuses: %v", extra) + } + if missing := diff(accepted, specProps); len(missing) > 0 { + t.Errorf("the release handler accepts members the ReleaseIssueRequest schema does not document: %v", missing) + } +} + // TestUpdateRequestMembersMatchTheHandler is the claim's and the close's gate // for the update body, at BOTH of its levels. //