beads/internal/httpapi/close_test.go
Julian Knutsen b858a29e4a
fix(contracts): JSON contract fixes before 1.3.0 freezes them — string revision tokens, --set-metadata scalar typing, create --json nano timestamps (#6053)
* fix(metadata): restore v1.2.2 scalar typing for --set-metadata values

8ebd53e88 moved the CLI's metadata-edit helpers into
internal/storage/metadata.go and, in the move, replaced v1.2.2's
toJSONValue inference with a MetadataEditValue that always json.Marshals
the value as a string. The intent was GH#4146 (a numeric-looking id or a
version like "1e3" came back as a JSON number, breaking map[string]string
Go consumers), but it silently changed the shipped CLI contract:
`bd update --set-metadata k=5` started storing "5" instead of 5. That
regression shipped only in the deprecated/superseded v1.2.1, never in
v1.2.2, and 1.3.0 would freeze it.

Restore v1.2.2's inference body-for-body inside MetadataEditValue, so the
parity claim stays checkable against `git show v1.2.2:cmd/bd/update.go`:
"null" is JSON null, "true"/"false" are booleans, a spelling that scans
as a float AND is valid JSON on its own is emitted as that literal
(5 -> 5, 1e3 -> 1e3, 0.50 -> 0.50, while 05, +5 and NaN stay strings),
and everything else is a string. Every --set-metadata caller funnels
through this one function: embedded (cmd/bd/update.go ->
storage.ApplyMetadataEdits), proxied (parseSetMetadataFlags) and the
update executor's []string path.

GH#4146's concern is served by the explicitly typed routes, which are
untouched: --metadata / --metadata-json on the CLI (MergeMetadataJSON)
and the typed set map on the HTTP/Go path (applyTypedMetadataEdits).

No data migration: a "5" written by an in-window build is
indistinguishable from a string a user set intentionally through the
typed paths, so normalizing stored metadata would corrupt intended data.
Re-running the same --set-metadata k=5 retypes any given key.

Tests: new table in internal/storage/metadata_edit_value_test.go pinning
the v1.2.2 matrix plus an ApplyMetadataEdits end-to-end; the tests that
pinned the string-always behavior are flipped (domain/db mergeops suite,
update_lifecycle patch mapping, cmd/bd toJSONValue table) and the
embedded + proxied CLI suites now assert a stored JSON number. The
contract corpus is regenerated: its update/list/ready goldens run
`--set-metadata phase=2`, so `"phase": "2"` becomes `"phase": 2` and
nothing else moves.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(create): echo full-precision timestamps from bd create, not the DATETIME(0) re-read

b92442d1a routed `bd create` through issueops.Lifecycle, whose executors
build their result by re-reading the row they just wrote
(HydrateIssueOperationResult -> GetIssueInTx). created_at/updated_at are
DATETIME(0) columns, so that snapshot comes back at whole-second
precision and cmd/bd/create.go echoes it. v1.2.2 returned the caller's
own in-memory struct, which PrepareIssueForInsert stamps with
time.Now().UTC() including nanoseconds, so `bd create --json` used to
print e.g. 2026-08-28T12:34:56.789012345Z. Agents that create several
issues in a burst order them by exactly that fraction; rounded to the
second they all tie.

Restore the echo with OverlayCreateTimestamps: after hydration, put back
the created_at/updated_at (and closed_at, when the write set one) the
INSERT actually sent. Everything else on the snapshot stays DB-truth,
which is the facade's contract — only create, and only these fields.

Applied at every create body, not just the two the CLI reaches:
issueops.ExecuteCreate and ExecuteCreateBatch behind the dolt and
embedded-dolt stores, and the unit-of-work provider's own Create,
CreateBatch and batch-apply create item, which is what the proxied server
and POST /v0/beads/issues run on. Fixing only the shared executors would
have left the two bodies disagreeing about the same promise.

What is NOT changed, because it is not a regression: `bd show --json` and
`bd list --json` answered whole seconds in v1.2.2 too — they read the
column — and update/close/reopen re-read after writing there as well.
Widening the columns to DATETIME(6) would give reads sub-second times
too, but that is a schema migration on user Dolt DBs and touches paths
that deliberately compare at second precision; it is a 1.4 change.

The accepted skew, which predates this and stays: the engine ROUNDS to
the column rather than truncating, so a later read of the same row can
sit up to half a second either side of the create echo.

Tests: two new conformance cases, run on all three backends —
RunLifecycleCreateEchoesSubSecondTimestamps (a caller-supplied
nanosecond stamp must survive to the result exactly; the auto-stamped arm
stays a bounded smoke check, since requiring a non-zero fraction off the
clock is flaky by a billionth) and RunBatchCreatorEchoesSubSecondTimestamps
(per item, since both bodies build the result one snapshot at a time).
Plus a cmd/bd embedded test asserting `bd create --json` prints a
fractional part, and one httpapi assertion that the wire does not round
the role's snapshot on the way out. All four fail on the pre-fix tree.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(httpapi,types)!: revision / expected_version tokens are opaque JSON strings

The optimistic-concurrency token is minted by freshRowLock over the FULL
int64 range (crypto-random, non-zero) and published on the wire as a JSON
number: `revision` on responses, `expected_version` on guarded requests.
A JSON number does not survive a consumer that decodes into an IEEE-754
double — JavaScript's JSON.parse, Go's `any`, Python's `float`, jq. Live
tokens run past 5e17, where a double's ulp is already 64, so such a
client reads back a value NEAR the token, echoes that as its guard, and
earns a 409 against a row nobody else touched. The spec already carried
"DECODE IT AS A 64-BIT INTEGER" paragraphs telling clients to work around
this; that is a workaround for a wire type that should not have been a
number.

Emit and accept the token as a decimal STRING instead. It is documented
as opaque and EQUALITY-ONLY — compare it, never order or interpret it —
and a string round-trips exactly in every JSON consumer. It also leaves a
future backend free to mint a token that is not an int64 at all.

Internals are untouched: freshRowLock, the row_lock BIGINT column, its
migration, types.Issue.RowVersion and the ExpectedVersion *int64 guards
on the issueops requests all stay int64. Only the wire projection moves,
through the one spelling of the encoding — types.RevisionToken and
types.ParseRevisionToken.

STRICT STRING ONLY, with no transitional number-or-string acceptance.
This API already refuses unknown members by name and keeps one spelling
of the guard, and a number is precisely the shape a double-based client
has already rounded before it left the client — accepting it would
preserve the defect. A numeric guard is a 400 naming the member.

Chosen over clamping freshRowLock to 53 bits: a clamp does not fix rows
already minted with full-range tokens by in-window builds, so a JS
consumer reading one still rounds past 2^53 — repairing that would need a
row_lock normalization sweep over issues and wisps, a migration days
before a tag.

Surface: types.IssueDetails.Revision (what `bd show --json` prints and
GET /v0/beads/issues/{id} returns), the five hand-assigned httpapi
response fields, applyVersionGuardMember (now the reader for the batch
update item too, ahead of its typed decode, so a mistyped token still
earns a 400 naming the member), Problem.expected_version, and 14 OpenAPI
members regenerated through `make api-gen`. actual_version goes with them
— it is documented as "the `revision` the row was found holding", so
leaving it an integer would make the expected/actual pair disagree about
its own type; it is declared but never populated, so nothing changes
behaviorally.

Nothing shipped in a tagged release ever carried this member: v1.2.2 has
no internal/httpapi at all and no `revision` anywhere on the wire, so the
whole surface is in-window and can still be changed compatibly. Legacy
migration-0054 rows read as the string "0" with the same CAS semantics.

Corpus goldens are UNCHANGED: the canonicalizer already replaced any
`revision` value with the string "<REVISION>" whatever its JSON type.

Tests: types-level pins that the marshaled member matches `"revision":
"-?\d+"` and that RevisionToken/ParseRevisionToken round-trip MinInt64,
MaxInt64 and 2^53+1, plus a JS-realistic decode of 2^53+1 with a float64
control proving the token really is one a number would corrupt; httpapi
refusal tests for a numeric guard on update, close, reopen, delete and
both batch item kinds; a 409 echo asserted as the string; and the proxied
serve integration tests now splice the response's own token back in
verbatim rather than re-rendering a parsed one.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 05:20:27 +00:00

769 lines
33 KiB
Go

package httpapi
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// These are pure: the close path runs end to end over a real listener against a
// fake ROLE, so the wire edge — path split, media type, body rules, actor and
// text rules, response and problem shapes — is covered on every pull request by
// the PR workflow's unconditional Go test job. What a fake cannot prove is the
// transaction: first-close-wins read back through a second close, and a forced
// close over real open children, live in cmd/bd's proxied-server integration
// test against real Dolt (TestProxiedServerServeClose). The role-level
// transition is owned against a real store by
// internal/storage/uow/lifecycle_close_reopen_contract_test.go, which this
// slice cites rather than duplicates.
const closePath = "/v0/beads/issues/bd-1:close"
func (ts *testServer) closeIssue(t *testing.T, path, body string) *http.Response {
t.Helper()
return ts.postBody(t, path, "application/json", body)
}
// newCloseServer wires a server over the store-shaped source with a lifecycle
// role the case controls. Every other role is a placeholder: Listen refuses a
// partial source, and a close reaches none of them.
func newCloseServer(t *testing.T, lifecycle *roleLifecycle) *testServer {
t.Helper()
return newTestServer(t, rolesConfig(Config{Lifecycle: lifecycle}))
}
func closedIssue(id string) *types.Issue {
issue := seededIssue(id, "alice", types.StatusClosed)
issue.CloseReason = "shipped"
issue.ClosedBySession = "session-7"
return issue
}
// TestCloseWritesOnceAndAnswersWithTheRowItWrote is the happy path and the two
// things a client depends on: the role receives exactly what the body asked
// for, and the response carries the issue as it stands after the close.
func TestCloseWritesOnceAndAnswersWithTheRowItWrote(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1"), Changed: true}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice","reason":"shipped","session":"session-7"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
want := issueops.CloseRequest{Actor: "alice", IssueID: "bd-1", Reason: "shipped", Session: "session-7"}
if got := lifecycle.closeRequests(); len(got) != 1 || got[0] != want {
t.Fatalf("the role received %+v, want exactly one %+v", got, want)
}
body := decodeBody(t, resp)
if body["already_closed"] != false {
t.Errorf("already_closed = %v, want false on a close that changed the row", body["already_closed"])
}
// An unforced close that got this far had no open children, and the
// document promises the member is present rather than omitted.
if body["open_children"] != float64(0) {
t.Errorf("open_children = %v, want 0", body["open_children"])
}
issue, ok := body["issue"].(map[string]any)
if !ok {
t.Fatalf("issue = %#v, want an object", body["issue"])
}
if issue["status"] != string(types.StatusClosed) || issue["close_reason"] != "shipped" {
t.Errorf("the response does not carry the closed row: %v", issue)
}
}
// TestCloseIsIdempotentForAnAlreadyClosedIssue pins the wire's name for the
// role's unchanged result. It is the re-claim's answer to the same question: an
// agent replaying its own recovery should not have to classify an error to
// learn it already ran.
func TestCloseIsIdempotentForAnAlreadyClosedIssue(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1"), Changed: false}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice","reason":"a second opinion"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["already_closed"] != true {
t.Errorf("already_closed = %v, want true for a re-close", body["already_closed"])
}
// The response still carries the row, and the row still carries what the
// FIRST close wrote — the second reason never reached a column.
issue, ok := body["issue"].(map[string]any)
if !ok {
t.Fatalf("issue = %#v, want an object", body["issue"])
}
if issue["close_reason"] != "shipped" {
t.Errorf("close_reason = %v; a re-close must not rewrite the record of why the work ended", issue["close_reason"])
}
}
// TestCloseForwardsForceAndReportsWhatItBypassed: `force` is the ROLE's bypass,
// so the handler's whole job is to pass it through — and to publish the count
// the role reports, which is exactly what a caller who forced past the guard
// wants to know.
func TestCloseForwardsForceAndReportsWhatItBypassed(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{
Issue: closedIssue("bd-1"), Changed: true, OpenChildren: 3,
}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice","force":true}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if got := lifecycle.closeRequests(); len(got) != 1 || !got[0].Force {
t.Fatalf("the role received %+v, want Force set", got)
}
if body := decodeBody(t, resp); body["open_children"] != float64(3) {
t.Errorf("open_children = %v, want the 3 the role reported", body["open_children"])
}
}
// TestCloseOpenChildrenIsATypedConflict is the whole reason not_closable exists
// as a code and open_children as a member: a client classifies the refusal and
// reads the count without substring-matching "3 open child issue(s)".
func TestCloseOpenChildrenIsATypedConflict(t *testing.T) {
lifecycle := &roleLifecycle{closeErr: fmt.Errorf("close bd-1: %w",
&issueops.CloseOpenChildrenError{IssueID: "bd-1", OpenChildren: 3})}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"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(CodeNotClosable) {
t.Errorf("code = %v, want %s", body["code"], CodeNotClosable)
}
if body["open_children"] != float64(3) {
t.Errorf("open_children = %v, want the count the refusing transaction observed", body["open_children"])
}
}
// TestCloseBlockedIsTheSameCodeWithoutTheCount is the other half of the
// discriminator the document promises. Both refusals are `not_closable` and
// both are bypassed by `force`; only one can say how many children it saw, and
// MEMBER PRESENCE is how a client tells them apart.
func TestCloseBlockedIsTheSameCodeWithoutTheCount(t *testing.T) {
lifecycle := &roleLifecycle{closeErr: fmt.Errorf("close bd-1: %w", issueops.ErrCloseBlocked)}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"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(CodeNotClosable) {
t.Errorf("code = %v, want %s", body["code"], CodeNotClosable)
}
if _, present := body["open_children"]; present {
t.Errorf("the blocker refusal reported open_children, which is the other refusal's discriminator: %v", body)
}
}
// TestCloseUnknownIDIs404 keeps the miss on the shape the document already
// describes rather than inventing one for this operation.
func TestCloseUnknownIDIs404(t *testing.T) {
lifecycle := &roleLifecycle{closeErr: fmt.Errorf("close bd-9: %w", issueops.ErrNotFound)}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, "/v0/beads/issues/bd-9:close", `{"actor":"alice"}`)
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["code"] != string(CodeNotFound) {
t.Errorf("code = %v, want %s", body["code"], CodeNotFound)
}
}
// TestCloseRejectsTheShapesTheDocumentRefuses is the body vocabulary, refused
// at the wire edge. Every case asserts that NOTHING reached the role: a 400
// this handler can answer is a 400 no transaction should be opened for.
func TestCloseRejectsTheShapesTheDocumentRefuses(t *testing.T) {
for _, tc := range []struct {
name string
body string
param string
}{
{"no actor", `{"reason":"x"}`, "actor"},
{"blank actor", `{"actor":" "}`, "actor"},
{"actor with a newline", "{\"actor\":\"alice\\nbd: close bd-1 by mallory\"}", "actor"},
{"actor with a C1 control character", `{"actor":"alice\u0085bd: close"}`, "actor"},
{"null actor", `{"actor":null}`, "actor"},
{"actor is not a string", `{"actor":7}`, "actor"},
{"oversize actor", `{"actor":"` + strings.Repeat("x", 300) + `"}`, "actor"},
{"unknown member", `{"actor":"alice","cascade":true}`, "cascade"},
{"reason is not a string", `{"actor":"alice","reason":7}`, "reason"},
// `null` is refused rather than read as a clear: absence already means
// "not supplied", so a null would publish a third state with no meaning.
{"null reason", `{"actor":"alice","reason":null}`, "reason"},
{"oversize reason", `{"actor":"alice","reason":"` + strings.Repeat("x", 300) + `"}`, "reason"},
{"reason with a control character", "{\"actor\":\"alice\",\"reason\":\"done\\nbd: forged\"}", "reason"},
{"session is not a string", `{"actor":"alice","session":[]}`, "session"},
{"null session", `{"actor":"alice","session":null}`, "session"},
{"session with a control character", "{\"actor\":\"alice\",\"session\":\"s\\u0000\"}", "session"},
{"force is not a boolean", `{"actor":"alice","force":"yes"}`, "force"},
{"null force", `{"actor":"alice","force":null}`, "force"},
} {
t.Run(tc.name, func(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1")}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, 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 := lifecycle.closeRequests(); len(got) != 0 {
t.Errorf("a refused body reached the role: %+v", got)
}
})
}
}
// TestCloseRefusesABodyItCannotRead covers the refusals with no nameable
// member, where `param` is documented absent.
func TestCloseRefusesABodyItCannotRead(t *testing.T) {
for _, tc := range []struct{ name, body string }{
{"not an object", `["actor"]`},
{"a bare null", `null`},
{"trailing garbage", `{"actor":"alice"} {"actor":"mallory"}`},
{"unparseable", `{`},
} {
t.Run(tc.name, func(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, 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 _, present := body["param"]; present {
t.Errorf("a body with no nameable part reported a param: %v", body)
}
if got := lifecycle.closeRequests(); len(got) != 0 {
t.Errorf("a refused body reached the role: %+v", got)
}
})
}
}
// TestCloseRefusesAForeignMediaType: the CSRF control, on the surface's newest
// write. A JSON content type is not CORS-simple, so a cross-origin close always
// triggers a preflight this server never approves.
func TestCloseRefusesAForeignMediaType(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newTestServer(t, rolesConfig(Config{Lifecycle: lifecycle}))
resp := ts.postBody(t, closePath, "text/plain", `{"actor":"alice"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["param"] != "Content-Type" {
t.Errorf("param = %v, want Content-Type", body["param"])
}
if got := lifecycle.closeRequests(); len(got) != 0 {
t.Errorf("a foreign media type reached the role: %+v", got)
}
}
// TestCloseRefusesAQueryParameter: this operation publishes none, so every key
// is the document-level unknown-parameter refusal.
func TestCloseRefusesAQueryParameter(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath+"?force=true", `{"actor":"alice"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["reason"] != string(ReasonUnknownParameter) {
t.Errorf("reason = %v, want %s", body["reason"], ReasonUnknownParameter)
}
if got := lifecycle.closeRequests(); len(got) != 0 {
t.Errorf("a query string reached the role: %+v", got)
}
}
// TestCloseRefusesALifecycleThatAnswersWithNothing is checkedLifecycle's
// reason for existing: handleClose dereferences the issue the role returned, so
// a role reporting success without one is a nil pointer panic on a live server
// unless it is folded into the generic 500 first.
func TestCloseRefusesALifecycleThatAnswersWithNothing(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Changed: true}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"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 fault is in the log, which is the only place a 5xx detail may say
// what happened.
if !strings.Contains(ts.stderr.String(), "request_error") {
t.Errorf("a broken role produced no request_error line:\n%s", ts.stderr.String())
}
}
// TestClosePathReachesItsHandler 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 shared pattern
// actually serves the documented path — and serves it as THIS operation rather
// than as the claim that registered the pattern first.
func TestClosePathReachesItsHandler(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1"), Changed: true}}
ts := newCloseServer(t, lifecycle)
if resp := ts.closeIssue(t, closePath, `{"actor":"alice"}`); resp.StatusCode != http.StatusOK {
t.Fatalf("POST the documented close path: status = %d, want 200", resp.StatusCode)
}
line := findLogLine(t, ts.stderr.String(), "path="+closePath)
if !strings.Contains(line, "op="+OpCloseIssue) {
t.Errorf("the documented close path is served by another operation:\n%s", line)
}
}
// TestCloseTakesADatabaseSlot: the newest write is not exempt from the
// in-flight limit. An exempt write would keep opening connections while every
// reader is already queued — the saturation case the semaphore exists for.
func TestCloseTakesADatabaseSlot(t *testing.T) {
for _, rt := range routeTable {
if rt.op != OpCloseIssue {
continue
}
if rt.bypassSemaphore {
t.Error("the close route bypasses the database semaphore; only handlers that touch no database may")
}
if !rt.implemented {
t.Error("the close route is still marked unimplemented, so capabilities will not advertise it")
}
return
}
t.Fatalf("no %s row in the route table", OpCloseIssue)
}
// TestCloseMapsARetryableRoleFailureOntoTheDocumentedRetry keeps the shared
// error mapping load-bearing for this operation: an exhausted retry budget is
// a 503 the client comes back from, never the generic 500.
func TestCloseMapsARetryableRoleFailureOntoTheDocumentedRetry(t *testing.T) {
lifecycle := &roleLifecycle{closeErr: ErrBusy}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice"}`)
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["code"] != string(CodeBusy) {
t.Errorf("code = %v, want %s", body["code"], CodeBusy)
}
if got := resp.Header.Get("Retry-After"); got == "" {
t.Error("a retryable refusal carries no Retry-After")
}
}
// TestCloseTrimsTheActor pins that the value the role is handed is the trimmed
// one, not the caller's whitespace — the same rule the claim applies, applied
// by the same shared function.
func TestCloseTrimsTheActor(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1"), Changed: true}}
ts := newCloseServer(t, lifecycle)
if resp := ts.closeIssue(t, closePath, `{"actor":" alice "}`); resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if got := lifecycle.closeRequests(); len(got) != 1 || got[0].Actor != "alice" {
t.Errorf("the role received actor %q, want the trimmed value", got[0].Actor)
}
}
// TestCloseErrorsMapThroughTheSharedClassification pins the two close-policy
// sentinels onto one code at the mapping rather than at the handler, so any
// other operation that ever reaches them answers the same way.
func TestCloseErrorsMapThroughTheSharedClassification(t *testing.T) {
for _, tc := range []struct {
name string
err error
}{
{"open children", &issueops.CloseOpenChildrenError{IssueID: "bd-1", OpenChildren: 2}},
{"the bare open-children sentinel", issueops.ErrCloseOpenChildren},
{"a live blocker", issueops.ErrCloseBlocked},
} {
t.Run(tc.name, func(t *testing.T) {
res := ClassifyError(fmt.Errorf("wrapped: %w", tc.err))
if res.Problem.Status != http.StatusConflict || res.Problem.Code != string(CodeNotClosable) {
t.Errorf("ClassifyError = %d/%s, want 409/%s", res.Problem.Status, res.Problem.Code, CodeNotClosable)
}
// The mapping never attaches the member — failClose does, from the
// typed error's field — so a code-only classification stays silent.
if res.Problem.OpenChildren != nil {
t.Errorf("the shared mapping attached open_children: %v", *res.Problem.OpenChildren)
}
})
}
}
// TestCloseIsNotReachableByOtherMethods: the dispatcher is registered for POST
// alone, so the documented path under any other method is an unrouted path.
//
// PATCH is excluded and has its own test below. `PATCH /v0/beads/issues/{id}`
// is a documented operation on a single-segment wildcard, so it MATCHES this
// path — as an update of an issue whose id happens to be "bd-1:close". That is
// the detail path's long-standing behavior (GET has always answered the same
// way), and what matters is that it never executes as a close.
func TestCloseIsNotReachableByOtherMethods(t *testing.T) {
ts := newCloseServer(t, &roleLifecycle{})
for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete} {
req, err := http.NewRequest(method, ts.base+closePath, strings.NewReader(`{"actor":"alice"}`))
if err != nil {
t.Fatalf("new %s request: %v", method, err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := ts.client.Do(req)
if err != nil {
t.Fatalf("%s %s: %v", method, closePath, err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("%s %s: status = %d, want 404", method, closePath, resp.StatusCode)
}
}
}
// TestCloseRefusesUnrowableIDsBeforeAnyDatabaseWork: the id bound is the
// dispatcher's and it is shared, so it holds for this operation without this
// handler carrying a copy of it. The answer is the SAME 404 a real miss gets —
// a distinct refusal would let a caller map the server's notion of a
// well-formed id.
func TestCloseRefusesUnrowableIDsBeforeAnyDatabaseWork(t *testing.T) {
for _, tc := range []struct{ name, id string }{
{"longer than the column", strings.Repeat("b", types.MaxFieldLen+1)},
{"carrying a control character", "bd-1%00"},
{"carrying a C1 introducer", "bd-1%C2%9B"},
} {
t.Run(tc.name, func(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, "/v0/beads/issues/"+tc.id+":close", `{"actor":"alice"}`)
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp))
}
if got := lifecycle.closeRequests(); len(got) != 0 {
t.Errorf("an unrowable id reached the role: %+v", got)
}
})
}
}
// TestCloseBodyCapIsEnforcedWhileReading pins that the megabyte cap refuses
// before the whole body is buffered, which is what makes it a bound rather than
// a check.
func TestCloseBodyCapIsEnforcedWhileReading(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newCloseServer(t, lifecycle)
oversize := `{"actor":"alice","reason":"` + strings.Repeat("x", maxJSONBodyBytes+1) + `"}`
resp := ts.closeIssue(t, closePath, oversize)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if got := lifecycle.closeRequests(); len(got) != 0 {
t.Errorf("an oversize body reached the role: %+v", got)
}
}
// TestFailCloseNeverParsesTheRefusalsProse is the rule the whole 409 exists to
// enforce, asserted at the seam: the member comes from the typed error's field,
// so an error whose MESSAGE mentions open children but whose type is not the
// typed one carries no member.
func TestFailCloseNeverParsesTheRefusalsProse(t *testing.T) {
lifecycle := &roleLifecycle{closeErr: fmt.Errorf(
"cannot close bd-1: 4 open child issue(s); close children first: %w", issueops.ErrCloseBlocked)}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice"}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["open_children"] != nil {
t.Errorf("open_children = %v; it was read out of the message rather than the typed field", body["open_children"])
}
}
// TestCloseResolvesAcrossBothPlanes is the divergence from the claim, pinned:
// the claim addresses the issues table only, and this operation does not copy
// that. Nothing here decides the plane — the ROLE does — so what this asserts
// is that the handler publishes no IssuePlaneOnly-style narrowing of its own.
func TestCloseResolvesAcrossBothPlanes(t *testing.T) {
wisp := seededIssue("bd-w1", "alice", types.StatusClosed)
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: wisp, Changed: true}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, "/v0/beads/issues/bd-w1:close", `{"actor":"alice"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("closing a wisp id: status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if got := lifecycle.closeRequests(); len(got) != 1 || got[0].IssueID != "bd-w1" {
t.Fatalf("the role received %+v, want the wisp id unchanged", got)
}
}
// guardToken is the fixture row version every guarded case in this package
// uses, and its SIZE is the point: it is past 2^53, where an IEEE-754 double's
// ulp is already 2, so a response member read through `map[string]any` comes
// back as a value NEAR the token and is not it.
//
// Live row_lock tokens run in this range, which is how the update slice's first
// integration case failed — the guard it composed from a float64-decoded
// revision was refused against a row nothing else had touched. Pinning it here
// means a member decoded the wrong way fails in milliseconds instead of against
// real Dolt.
const guardToken int64 = 9007199254740993
// guard spells a row-version expectation the way a request carries one: through
// a pointer, so that nil ("do not check") stays distinct from a guard on the
// never-written version 0.
func guard(v int64) *int64 { return &v }
// revisionOf reads `revision` as the decimal STRING the document declares and
// parses it back to the int64 the row holds. That is the whole reason it exists
// beside decodeBody: that helper decodes into `any`, which would take the string
// but hand back its text, and would silently have taken a float64 back when the
// member was a number — which is the corruption the string exists to prevent.
// Decoding into *string is what makes a number-typed member fail here.
//
// NEVER ORDER IT AND NEVER COMPUTE ONE. The token is opaque and compared for
// equality alone, so "the previous revision" is not `revision - 1`; it is the
// value an earlier write answered with.
func revisionOf(t *testing.T, resp *http.Response) int64 {
t.Helper()
raw := readAll(t, resp)
var body struct {
Revision *string `json:"revision"`
}
if err := json.Unmarshal([]byte(raw), &body); err != nil {
t.Fatalf("decode revision from %q: %v", raw, err)
}
if body.Revision == nil {
t.Fatalf("the response carries no `revision`: %s", raw)
}
token, err := types.ParseRevisionToken(*body.Revision)
if err != nil {
t.Fatalf("`revision` %q is not a decimal token: %v", *body.Revision, err)
}
return token
}
// TestCloseForwardsTheVersionGuard: the member reaches the role as the POINTER
// it models, and an absent member stays nil.
//
// The nil half is not decoration. issueops.CloseRequest.ExpectedVersion is a
// pointer precisely so that "do not check" is distinguishable from a caller
// guarding on the never-written version 0, so a handler that collapsed absence
// into &0 would refuse every close of a row that has ever been written.
func TestCloseForwardsTheVersionGuard(t *testing.T) {
for _, tc := range []struct {
name string
body string
want *int64
}{
{"a guard is forwarded", `{"actor":"alice","expected_version":"9007199254740993"}`, guard(guardToken)},
{"the never-written version is a real guard", `{"actor":"alice","expected_version":"0"}`, guard(0)},
{"an absent guard stays nil", `{"actor":"alice"}`, nil},
} {
t.Run(tc.name, func(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1"), Changed: true}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, tc.body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
got := lifecycle.closeRequests()
if len(got) != 1 {
t.Fatalf("%d closes, want 1", len(got))
}
switch {
case tc.want == nil && got[0].ExpectedVersion != nil:
t.Errorf("ExpectedVersion = %d, want nil: an absent member must not become a guard", *got[0].ExpectedVersion)
case tc.want != nil && got[0].ExpectedVersion == nil:
t.Errorf("ExpectedVersion = nil, want %d", *tc.want)
case tc.want != nil && *got[0].ExpectedVersion != *tc.want:
t.Errorf("ExpectedVersion = %d, want %d", *got[0].ExpectedVersion, *tc.want)
}
})
}
}
// TestCloseAnswersWithTheRowsRevision is the other half of the guard: the token
// a caller's NEXT request needs comes back on this one.
//
// It asserts the value against the row the ROLE answered with rather than
// against whatever the handler put there, which is the difference between this
// case and one that cannot fail. The update slice measured that exactly: its
// first version echoed the handler's own number and stayed green against a
// `revision: 0`.
//
// The idempotent re-close carries one too. A caller that guarded a replay needs
// the token whether or not the replay wrote, and `already_closed: true` with no
// revision beside it would leave a chain unable to continue.
func TestCloseAnswersWithTheRowsRevision(t *testing.T) {
for _, tc := range []struct {
name string
changed bool
}{
{"a close that wrote", true},
{"an idempotent re-close", false},
} {
t.Run(tc.name, func(t *testing.T) {
issue := closedIssue("bd-1")
issue.RowVersion = guardToken
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: issue, Changed: tc.changed}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if got := revisionOf(t, resp); got != guardToken {
t.Errorf("revision = %d, want the row's %d", got, guardToken)
}
})
}
}
// TestCloseRefusesAStaleGuard is the 409, and it is the case whose GREEN is
// bought by the arm's placement in failClose.
//
// ClassifyError has no row for ErrVersionMismatch and neither leg wraps it, so
// the arm's absence is not a worse status — it is a 500 for a refusal this
// document names by code. Mutation-checked: deleting the arm makes this case
// fail with 500.
//
// `actual_version` stays ABSENT. The refusal rolled its transaction back, so a
// read afterwards would describe a row it never saw; PreconditionFailed says so
// and this pins it.
func TestCloseRefusesAStaleGuard(t *testing.T) {
lifecycle := &roleLifecycle{closeErr: fmt.Errorf("close bd-1: %w", issueops.ErrVersionMismatch)}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice","expected_version":"9007199254740993"}`)
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(CodePreconditionFailed) {
t.Errorf("code = %v, want %s", body["code"], CodePreconditionFailed)
}
if body["param"] != expectedVersionMember {
t.Errorf("param = %v, want %s", body["param"], expectedVersionMember)
}
if _, present := body["expected_version"]; !present {
t.Errorf("the refusal does not echo the guard the request sent: %v", body)
}
if _, present := body["actual_version"]; present {
t.Errorf("actual_version = %v; the refusing transaction rolled back, so there is no observed value to report",
body["actual_version"])
}
// It is not the close-policy refusal wearing a different code.
if _, present := body["open_children"]; present {
t.Errorf("open_children = %v on a precondition refusal; that member is not_closable's discriminator", body["open_children"])
}
}
// TestCloseGuardOutranksClosePolicy pins the ORDER the role documents, over the
// wire: ExpectedVersion is checked first, so a request that is both stale and
// policy-refused reports the stale guard.
//
// A caller told "close the children first" when its whole view of the row has
// moved would be acting on information that has already changed.
func TestCloseGuardOutranksClosePolicy(t *testing.T) {
lifecycle := &roleLifecycle{closeErr: fmt.Errorf("close bd-1: %w", issueops.ErrVersionMismatch)}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, `{"actor":"alice","expected_version":"41","force":false}`)
body := decodeBody(t, resp)
if body["code"] != string(CodePreconditionFailed) {
t.Errorf("code = %v, want %s: the role checks the version before policy and the wire must not reorder it",
body["code"], CodePreconditionFailed)
}
}
// TestCloseForceDoesNotBypassTheGuard pins the two members as INDEPENDENT.
// `force` says "close it even though the graph objects"; the guard says "only
// if this is still the row I read". A handler that dropped the guard when force
// arrived would let the one member that cannot be undone travel unchecked.
func TestCloseForceDoesNotBypassTheGuard(t *testing.T) {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1"), Changed: true}}
ts := newCloseServer(t, lifecycle)
if resp := ts.closeIssue(t, closePath, `{"actor":"alice","force":true,"expected_version":"41"}`); resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
got := lifecycle.closeRequests()
if len(got) != 1 {
t.Fatalf("%d closes, want 1", len(got))
}
if !got[0].Force || got[0].ExpectedVersion == nil || *got[0].ExpectedVersion != 41 {
t.Errorf("request = %+v, want both Force and the guard forwarded", got[0])
}
}
// TestCloseRefusesAMalformedGuard: the token is a decimal STRING and nothing
// else, refused at the edge before any database work.
//
// The bare number is the case that matters. It is what the member used to be, so
// accepting it would be the transitional spelling this contract deliberately
// does not have — and a JSON number is exactly the shape that arrives already
// rounded from a double-based client.
func TestCloseRefusesAMalformedGuard(t *testing.T) {
for _, body := range []string{
`{"actor":"alice","expected_version":41}`,
`{"actor":"alice","expected_version":9007199254740993}`,
`{"actor":"alice","expected_version":"41.5"}`,
`{"actor":"alice","expected_version":"not-a-token"}`,
`{"actor":"alice","expected_version":""}`,
`{"actor":"alice","expected_version":1.5}`,
`{"actor":"alice","expected_version":null}`,
`{"actor":"alice","expected_version":true}`,
} {
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{Issue: closedIssue("bd-1")}}
ts := newCloseServer(t, lifecycle)
resp := ts.closeIssue(t, closePath, body)
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("body %s: status = %d, want 400: %s", body, resp.StatusCode, readAll(t, resp))
continue
}
if problem := decodeBody(t, resp); problem["param"] != expectedVersionMember {
t.Errorf("body %s: param = %v, want %s", body, problem["param"], expectedVersionMember)
}
if calls := lifecycle.closeRequests(); len(calls) != 0 {
t.Errorf("body %s: %d closes reached the role; a malformed guard is refused before any database work", body, len(calls))
}
}
}