Compare commits

...
Sign in to create a new pull request.

10 commits

Author SHA1 Message Date
Eddie the Engineer
75b6ed9a72 fix(httpapi): pin the S4 sweep members at the wire edge, gate golden sides
The `sides` map this change adds to golden.json predates schemas main gained
since (#7248's BatchGetIssue*, BatchGetIssuesRequest* and
BatchGetIssuesResult*, plus IssueDetails.gated_by[]), so the rebase left it 9
schemas short of what gendigest writes, and goldenDrift never compared Sides,
so nothing noticed. Regenerated (+9 sides lines, no entry changes), and
goldenDrift now fails with the regenerate instruction when the golden's sides
disagree with a fresh digest; TestGoldenDrift drives that arm three ways.

The SweepSkips description still called the first two buckets protections
and the last four defenses, which filed the new live_dependent protection
under the defenses. It now names pinned, referenced and live_dependent as the
protections (apigen regenerated: the two comment copies only), and
handleSweep's comment counts eight members.

internal/httpapi's sweep pins stopped at the original six members: nothing
there sent protect_live_dependents or limit, refused a mistyped one, or read
live_dependent or remaining back. The forward, refuse and publish tests now
cover all four, and TestSweepResponseCarriesEveryRoleField, named by
sweepResponse's comment but never written, counts both projection levels and
requires every wire field populated from a fully set role result.

The httpclient Sweep defer comment described ProtectLiveDependents/Limit
refusal paths this change replaced with capability gates; it now says why
the pass-through defer stays.

Validation: go test ./internal/httpapi/... ./internal/httpclient/... (CGO,
gms_pure_go), the served sweeper tier with BEADS_TEST_EMBEDDED_DOLT=1 (19/19
pass, none skipped), make api-check, go vet, git diff --check, and bazel test
--config=ci on httpapi_test, wireshape/..., httpclient_test, encode_test and
types_gen_drift_test. Mutants, each restored: disabling the sides arm reds
three TestGoldenDrift arms; the pre-fix golden reds TestWireShapeDigest
naming the 9 schemas; dropping the live_dependent or remaining projection,
the protect_live_dependents decode, or the limit assignment each reds its
new pin.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 14:48:41 +00:00
Eddie the Engineer
c5f64c8a45 fix(httpclient): give encode_test the httpclient tests its pin check reads
Maintainer fixup for the pre-review CI of #7251. Bazel / test and
Bazel / integration (PR run 37781419956) each fail one target,
//internal/httpclient/encode:encode_test, which also fails CI Gate / Required.
TestLedgerRowsAreWellFormed reports that rows W-SweepRequest.ProtectLiveDependents
and W-SweepRequest.Limit are pinned by
TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem, which is "neither a test
in this package nor a TODO(<bead>)".

The pin is right. The test lives in internal/httpclient/bulk_roles_test.go.
testFunctionsInThisPackage collects test names from ".", ".." and
../../../cmd/bd, but the data of encode_test declares only its own sources,
//cmd/bd:go_srcs, the ledger doc and the OpenAPI spec. Under Bazel, ".."
exists in the runfiles but holds no _test.go files, so the walk silently finds
nothing there. go test reads the real directory and passes. This PR changes
neither the walk nor the BUILD file. Every pin on main resolves from this
package or cmd/bd, which is why main is green. These two rows are the only ones
pinned to a test that exists only in internal/httpclient. The red stayed hidden
until now because the PR sat on a stacked base. PR CI, including the Bazel
lanes, runs only for PRs against main, release/** and hotfix/**.

Declare //internal/httpclient:go_srcs as data, so Bazel sees the files that
go test reads. The filegroup already exists with //:__subpackages__ visibility.
The pins stay on the test that actually covers the S4 members.

Validation: bazel test //internal/httpclient/encode:encode_test --config=ci
--nocache_test_results, run two ways. In the local processwrapper sandbox
(--remote_executor= --strategy=TestRunner=processwrapper-sandbox) the same
command fails both rows without this change and passes with it. It also passes
on the remote executor. Plus tools/bazel/go_srcs.py --check, gazelle
-mode=diff on the package (no change), git diff --check, and
go test ./internal/httpclient/encode/.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:45:13 +00:00
Julian Knutsen
4aa334ef58 docs(httpclient): regenerate the divergence ledger on main after #7247 merged
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:57:02 +00:00
Eddie the Engineer
a3be7b6d47 fix(httpapi,httpclient): name the invalid_value refusal; add tests to Bazel
Maintainer fixup for the review of #7251 (iteration 1). There are no blocker or
major findings. This applies the three optional findings that both reviewers
reported.

- Eight comment and description sites added by this PR say that an older
  server refuses an unpublished `tier` (or S4) member with `unknown_value`.
  No such reason exists. The server refuses with ReasonInvalidValue =
  "invalid_value" (internal/httpapi/problem.go), and sweep.go uses it for a
  bad tier. The sites are in openapi.v0.yaml, apigen/types.gen.go (regenerated
  by `make api-gen`), routes.go, sweeper.go and wire/handshake.go. The base has
  none of them, so this only corrects the PR's own text. A client author now
  matches the token the server actually sends.
- wire/handshake.go said the tier member carries no ledger row because it
  "narrows" an existing enum. Adding a value widens the accepted set, so the
  word is now "widens".
- internal/httpclient/BUILD.bazel: add expected_revision_contract_test.go and
  served_dualwrite_history_test.go to the httpclient_test srcs. Both files are
  new in this PR. Without the entries, `go test` runs them but no Bazel lane
  compiles them. The srcs list now matches the package's files, and the
  existing deps already cover their imports.

Provenance: this is the residue of the stranded fixup cad1cf02a2 from the
previous adoption of this PR, replayed onto the current head. Its patch-id
(b62e7d6d5562) is identical to that reviewed residue. That fixup's
widensAdditively guard and SKIP-message nit are not repeated here. The author
already landed both in b3f1516e55 (d41f317e0a after the rebase).

Validation: git diff --check; make api-gen (no-op) and make api-check;
go build, go vet and gofmt on internal/httpapi/... and internal/httpclient/...;
go test for internal/httpclient/wire, internal/httpclient/encode and
test/docsync; the httpclient Sweep* and TestExpectedRevisionContract tests; the
served dual-write tests with BEADS_TEST_EMBEDDED_DOLT=1; and
tools/bazel/go_srcs.py --check.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:55:09 +00:00
Julian Knutsen
49aaf8b681 test(httpclient): Sweep Limit now refuses on the missing issues.sweep.limit capability
#7247's review round pinned Sweep{Limit} as an encoder refusal. With S4 the
wire carries limit behind issues.sweep.limit, so against a server without
the token the refusal is a pre-dial capability refusal: still
*storage.ErrUnsupported for this backend, now naming the capability.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:55:09 +00:00
Julian Knutsen
daf0f1234f docs(httpclient): regenerate the divergence ledger after rebasing onto #7247's review fixes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:55:09 +00:00
Julian Knutsen
45f6cde4e7 fixup(wireshape): guard widensAdditively against "no enum before"
bee-ghosttrack / CHANGES_REQUESTED on #7251: widensAdditively required
len(new.Enum) > len(old.Enum), which holds vacuously when the old side
has no enum at all (a free `type: string`). That let a request-only
member go from unconstrained to a fixed enum at the same wire_revision
-- the opposite of widening, since the server now 400s a value an old
client could send yesterday.

Add the guard `len(old.Enum) == 0 || len(new.Enum) <= len(old.Enum) ->
false` so the no-enum-before case falls through to the ordinary
non-additive Changed path, same as a strict narrowing. Add a pinning
case to TestEnumWideningAdditivity and extend the doc comment.

Also reword the ExpectedRevision contract file comment from "runs ZERO
assertions" to "SKIPS", per the reviewer's note that the Run* helpers
t.Skip when CompareAndSetVersion is nil -- it's a skip, not an
assertion-free run.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-08 12:55:09 +00:00
Julian Knutsen
abf98bfe18 fix(types): make ParseRevisionToken the exact inverse of FormatInt
ParseRevisionToken's doc comment already promised it accepts exactly
what RevisionToken emits, but strconv.ParseInt alone is looser than
that: besides a leading "+" that FormatInt never produces, it also
accepts a leading zero on a digit string longer than one character
("007") and the literal "-0" — none of which FormatInt ever emits
(FormatInt(0, 10) is always "0", never "-0", and it never pads a
digit run). A caller is only ever supposed to echo a token a response
carried, so any of these is a client that invented a value rather
than a server this client should follow; reject them explicitly
instead of accepting them silently.

Pins the string<->int64 boundary with
TestParseRevisionTokenRejectsMalformedTokens, covering empty strings,
fractional/exponent spellings, leading "+", surrounding whitespace,
non-decimal bases, one-past-int64-boundary values, non-ASCII digits,
and now "007", "-007" and "-0".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-08 12:55:09 +00:00
Julian Knutsen
8c2d801f61 fix(storage): ratchet the http leg's role-contract ceiling to zero
Classify all 42 previously-ceilinged http-leg entrypoints and clear
the ceiling:

- ExpectedRevision + Refusal (10): wire a Phase-0 all-nil fixture,
  matching every other backend's current (unbuilt-CAS-feature) state.
  Said honestly: these ten entrypoints are counted here, the hook is
  unbuilt on every leg (not just this one), and every case runs zero
  assertions until a CompareAndSetVersion wire operation exists for
  this client to bind.
- Lifecycle ExpectedVersion concurrency (4): wire the two races that
  land on Priority/Notes and on Close for real over the served HTTP
  harness (precondition_failed decodes to storage.ErrVersionMismatch
  via errors.Is, same as the local legs). The other two, which race
  IssuePatch.SpecID/.AwaitID/.Owner edits against updateIssue, stay
  waived, but PENDING rather than permanent: IssuePatchBody refuses
  those three fields outright (W-IssuePatch.SpecID/.AwaitID/.Owner,
  D8 refuse-not-drop) rather than ever sending them, so the race never
  reaches the wire today. Closing the gap means publishing those
  fields on the wire, tracked as a follow-up slice, S4b: publish
  owner/spec_id/await_id on the wire.
- DualWrite (6): wired for real instead of waived. Mutate and
  MutateAsNoOp drive the client's Lifecycle role (Create/Update)
  against an in-process served harness with its own reference store,
  so VersionedHistoryConfigurer can be toggled per fixture;
  CurrentRevision, VersionRowCount and LatestVersionAttribution read
  the reference store's raw columns the same way every other served
  fixture's postcondition hooks do. All six FR-1/FR-2/FR-3/FR-5/FR-7
  cases (one version row per accepted mutation, no-op skip, atomic
  attribution, current_revision parity, and flag-off producing no
  rows) now run and pass.
- VersionReconciler + InitVerifier (13), and the raw
  IssueOperationsUpdate seam (3): waived — unservable over a typed
  HTTP role boundary, not a wiring gap.

adoptionCeiling: 42 -> 0 for the http leg; the "adopting" field is
removed (a zero ceiling with a reason is a registry error) since every
remaining gap is now a named waiver, PENDING or permanent as stated
above, instead of a budgeted unnamed one. Also deletes the scratch
zzz_dump_missing_test.go used to enumerate the ceiling during triage.

Re-review fix: the shared conformance attribution case only asserts
change_actor is non-empty (it runs across every leg, each with a
different literal Mutate actor). The http fixture's own Mutate always
sends Actor: "writer", so this leg's AttributionIsRecordedWithTheMutation
subtest now also mutates a second, independent issue and asserts the
recorded actor equals exactly "writer", in addition to the shared
non-empty check.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-08 12:55:09 +00:00
Julian Knutsen
d02e7b3d43 feat(httpclient): wire the S4 Sweeper extension (wisps-plane, live-dependent protection, limit)
Publish SweepRequest.ProtectLiveDependents and .Limit (plus a
wisps-plane tier and SweepResult.Remaining/.LiveDependent) on the v0
wire behind three new behavior-capability tokens
(issues.sweep.wispsPlane, issues.sweep.liveDependents,
issues.sweep.limit), and wire the client to send them once the
handshake advertises the tokens (refuseUnservedSweep otherwise).
Retire the two W-SweepRequest ledger rows that previously refused
these fields for lack of a wire member.

CurrentWireRevision stays at 2. A new wisps-plane SweepRequest.Tier
value is a request-only enum widening: it cannot cause an older
client to misdecode a response, and it is already gated by its own
capability token, so it is additive rather than a wire break. Teach
wireshape's drift gate that distinction directly: a Digest.Sides side
channel records whether each schema member is request-only,
response-only or both, and widensAdditively now treats a request-only
enum's new value as additive while still treating any response-side
widening as breaking, with tests pinning both directions and a
regenerated golden.json. min_client_wire_revision stays 0.
internal/httpapi/apigen/types.gen.go and openapi.v0.yaml's comments are
regenerated/updated to match (make api-gen).

Six served Sweeper contracts that were parked now run for real against
the in-process HTTP server; TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem
pins the capability-gated encode.

Re-review fix: walk()'s side classification short-circuited on a
name-only visited set, so a node already walked from one side never
had its CHILDREN walked again when a later path promoted the parent
to "both" — children stayed classified under whichever side reached
them first, order-dependent on Go's map iteration. Side recursion is
now guarded per (schema, side) pair (sideWalked, keyed on
name+"\x00"+side) instead of per schema name alone, so a child
reachable from both sides is always walked, and therefore recorded,
from both. Added TestSidePropagatesToNestedChildren (a named grandchild
and an inline nested child both reachable from a request body and,
via a wrapper, a response, assert "both" on every level and that
widening either enum breaks instead of being classed additive),
TestEnumWideningOnSharedNestedChildIsNotAdditive, and
TestComputeFromSideAssignmentIsDeterministic (200 runs, asserts
identical Sides/Entries every time). golden.json is confirmed
unchanged by the fix (regenerated and diffed byte-for-byte). Also
removes a bd-enterprise mention introduced in this slice's own
write_ledger_test.go comment (not a provenance header) in favor of
neutral wording.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-08 12:54:05 +00:00
28 changed files with 1714 additions and 175 deletions

View file

@ -47,7 +47,7 @@ the behavior.
## Summary
264 rows: 209 refuse, 33 degrade, 22 retired.
264 rows: 207 refuse, 33 degrade, 24 retired.
## Whole-behavior divergences (D9 ledger)
@ -138,8 +138,8 @@ Role-request fields on the served writes that the v0 wire publishes no member fo
| W-DepAddItem.ThreadID | refuse | `DepAddItem.ThreadID` | associating an edge ITEM with a discussion thread refuses | ApplyDepAddItem publishes no thread member, and no operation on this surface does: W-CreateDependency.ThreadID refuses the same column on both create edges. Dropping it would store the edge with no thread, so a replies-to edge would lose the conversation it was written for. It is a row of its own rather than a citation of that one for W-CreateItem.Issue's reason: the operation is different | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-IssuePatch.Labels | retired | `IssuePatch.Labels` | RETIRED — the whole ordered label edit crosses: `labels` replaces, `add_labels` adds, `remove_labels` removes | upstream #5510 published add_labels and remove_labels on IssuePatchBody and client wave ga-jpywb emits both, which is the retirement path this row named. The three travel as FLAT siblings where applyBatch nests them under one object, and the server assembles all three into ONE issueops.LabelPatch — so the algebra the role states (replace, then add, then remove; removal wins) is applied server-side and is never this client's to arrange. WHAT THE REFUSAL WAS PROTECTING is worth keeping after the refusal is gone: degrading an incremental edit onto the replace-only member would have meant reading the set, adding to it and writing it back, which silently drops any label another writer added in between. `bd label add` and every agent that tags work concurrently are exactly that caller, so the refusal was right for as long as the members did not exist — and it is the members that retire it, not a change of mind about the read-modify-write | D8 refuse-not-drop, open questions (tracked-refusal roadmap) | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CloseBatchRequest.ClaimNext | refuse | `CloseBatchRequest.ClaimNext` | folding an atomic claim-after-close onto a batch close refuses | batchCloseIssues publishes actor, force, items and session only — no claim_next member exists for this client to encode a ReadyRequest into, and none exists on the response for a claimed issue to decode back out of. Dropping the field silently would answer a caller's claim-after-close with a close that quietly never claimed anything; see W-CreateBatchRequest.Provenance for the same refuse-not-drop reasoning applied to an absent wire member. Deferred: S13 schedules ReadyLister (and with it, the ready-side plumbing a composed claim would need); no slice currently schedules claim_next itself | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-SweepRequest.ProtectLiveDependents | refuse | `SweepRequest.ProtectLiveDependents` | protecting live structural dependents during a sweep refuses | sweepIssues publishes dry_run, tier, closed_before, pattern, protect_referenced and actor only; no protect_live_dependents member exists for this client to send, and the server has no stored-edge lookup to run on this client's behalf. `bd purge` from a local workspace still gets the protection; over http it must ask without it or not at all | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-SweepRequest.Limit | refuse | `SweepRequest.Limit` | bounding one sweep call and draining a backlog over several refuses | sweepIssues publishes no limit member and SweepResult publishes no remaining member for a bounded caller to loop on; a non-zero Limit refuses before the dial rather than running the unbounded sweep silently. issueops.SweepResult.Remaining is therefore always zero from this client — not a dropped count, since nothing bounded the call that would have left one | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-SweepRequest.ProtectLiveDependents | retired | `SweepRequest.ProtectLiveDependents` | protecting live structural dependents during a sweep used to refuse | RETIRED by the S4 wire extension that sends it. The gap was always the DOCUMENT's rather than a decision: the local Sweeper role carries a structural-dependent protection alongside the referenced-citation one, and apigen.SweepRequest had no protect_live_dependents member for this client to narrow onto, so sending `true` and silently dropping it would have run an UNPROTECTED sweep while the caller believed the structural guard was active. The spec now publishes `protect_live_dependents` (and SweepSkips.live_dependent on the response) behind its own behavior-capability token, issues.sweep.liveDependents, because it is a parameter added to an operation that already shipped. The client sends it only once the handshake advertises the token and refuses locally, before the dial, when it does not — see refuseUnservedSweep (sweeper.go) and W-SweepRequest.Limit for the sibling member closed the same way | D8 refuse-not-drop | TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem |
| W-SweepRequest.Limit | retired | `SweepRequest.Limit` | bounding one sweep call and draining a backlog over several used to refuse | RETIRED by the S4 wire extension that sends it (with W-SweepRequest.ProtectLiveDependents). The local Sweeper role bounds one sweep call and reports the remainder back; apigen.SweepRequest and SweepResult carried neither a limit member to send nor a remaining member to read one back from, so a dropped Limit would have run the UNBOUNDED sweep the caller asked to cap, in one transaction. The spec now publishes `limit` on the request and `remaining` on the response behind issues.sweep.limit. The client sends Limit only once the handshake advertises that token and refuses locally otherwise; issueops.SweepResult.Remaining now carries the server's count rather than always reading zero | D8 refuse-not-drop | TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem |
## Command and flag refusals (D7)

View file

@ -81,8 +81,9 @@ func (e HealthStatus) Valid() bool {
// Defines values for SweepRequestTier.
const (
Durable SweepRequestTier = "durable"
Ephemeral SweepRequestTier = "ephemeral"
Durable SweepRequestTier = "durable"
Ephemeral SweepRequestTier = "ephemeral"
WispsPlane SweepRequestTier = "wisps-plane"
)
// Valid indicates whether the value is a known member of the SweepRequestTier enum.
@ -92,6 +93,8 @@ func (e SweepRequestTier) Valid() bool {
return true
case Ephemeral:
return true
case WispsPlane:
return true
default:
return false
}
@ -1034,7 +1037,7 @@ type ContextResponse struct {
// OPTIONAL, and absent means only that this server does not disclose its filesystem layout — never that it has no workspace. A client MUST NOT require it, MUST NOT treat absence as an error, and has no use for the value beyond display: it is a path on the SERVER's filesystem, which the client cannot open. Identify the workspace by `project_id` and `database`, which are required.
BeadsDir *string `json:"beads_dir,omitempty"`
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, and `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — 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"`
@ -1074,7 +1077,25 @@ type ContextResponse struct {
// had moved underneath it. That silent gap is the whole reason
// this field exists.
// * `2` — the first release whose `ContextResponse` carries
// `wire_revision` and `min_client_wire_revision` at all (this one).
// `wire_revision` and `min_client_wire_revision` at all. Still
// current: S4 widened `SweepRequest.tier`'s enum to add
// `wisps-plane` and added `protect_live_dependents` and `limit`
// alongside it, and none of the three bumped this counter.
// `SweepRequest` is a REQUEST-body-only schema — no response ever
// carries it — so nothing decodes it out of a server reply; the
// new enum member and the two new fields are each something only
// an UPDATED CLIENT chooses to send, behind their own behavior
// tokens (`issues.sweep.wispsPlane`, `issues.sweep.liveDependents`,
// `issues.sweep.limit`). An old client that never sends any of the
// three has nothing to misdecode, which is exactly the additive
// case this field exists to NOT gate. The wireshape drift gate
// (`internal/httpapi/wireshape`) tracks, per member, whether it is
// reachable from a request body, a response, or both, and treats
// an enum WIDENING as additive only on a request-only member —
// the identical widening on a response-side (or request+response)
// member still counts as changed and still demands a bump, since
// an existing client decoding a response must keep recognizing
// every value the server might send it.
//
//
// PRESENCE, not just value: a generated client whose JSON decoder zero-values a missing integer field cannot tell, by looking at a decoded `0` alone, whether the server SENT `0` or sent nothing. This is never actually ambiguous in practice, because `0` and `1` are PERMANENTLY RETIRED values — they describe servers that predate this field or carried the brief interim string shape, and no server that implements this field (`CurrentWireRevision` starts at `2` and only increases) will ever legitimately send a literal `0` or `1`. A decoded `0` can therefore only mean "this server omitted the field," and a client inferring from `bd_version` per the paragraph below is doing exactly the right thing in that case, never guessing at a value the field could have meant on its own. A client that wants presence as a first-class fact rather than an inference anyway should decode `wire_revision` into a nullable type, or check for the JSON key's presence directly, instead of relying on this retirement guarantee.
@ -1937,9 +1958,15 @@ type SweepRequest struct {
// DryRun Report what the sweep WOULD do and delete nothing. The counts, the skips and the refusals are the same ones the real sweep would produce, computed against the same snapshot — and nothing is recorded in history either.
DryRun *bool `json:"dry_run,omitempty"`
// Limit Cap how many beads this sweep deletes, OLDEST-CLOSED-FIRST. Absent or zero means unbounded. A negative value is a `400` invalid_argument, the same as the role's own ErrValidation. Behind the `issues.sweep.limit` behavior token: an older server answers `unknown_parameter` for this name.
Limit *int64 `json:"limit,omitempty"`
// Pattern Keep only beads whose id matches this shell glob (`*`, `?`, `[...]`, `\` escapes; `*` also crosses `-` and `.`, since an id is not a path). Absent matches every bead in the tier. A MALFORMED glob is a `400`, never a pattern that matches nothing.
Pattern *string `json:"pattern,omitempty"`
// ProtectLiveDependents Skip a closed candidate that a LIVE (not-done) bead depends on through a parent/child, tracks, or blocks edge, so closing a dependent's dependency does not erase the row a live bead still points at. Protection is TRANSITIVE and crosses the ephemeral/durable plane boundary. Behind the `issues.sweep.liveDependents` behavior token: an older server answers `unknown_parameter` for this name.
ProtectLiveDependents *bool `json:"protect_live_dependents,omitempty"`
// ProtectReferenced Skip candidates whose id is CITED — as a literal, at word boundaries — in the description, notes or comments of any bead that is not done, so a decision trail a live bead still points at is not deleted out from under it.
//
// It DEFAULTS ON here, unlike the library default, and that is deliberate. This is the only destructive operation on the surface, and the bearer a deployment may configure is not a per-caller right: one shared token admits a client to everything published here, so being authenticated says nothing about whether this particular deletion was meant. A caller that omits the member must therefore not get weaker protection than the operator typing `bd prune`, which protects unless `--ignore-references`. The inverse — opt OUT locally, opt IN remotely — is the shape that lets a stray request delete a decision trail nothing brings back.
@ -1948,10 +1975,14 @@ type SweepRequest struct {
ProtectReferenced *bool `json:"protect_referenced,omitempty"`
// Tier Which plane to clear. `ephemeral` is the wisp tier (`bd purge`) and `durable` is the issue tier (`bd prune`). The two are DISJOINT: a sweep of one can never touch a bead of the other. Required, with no default — a caller handed the wrong tier has nothing to notice until the beads are gone.
//
// `wisps-plane` is a THIRD, wider tier: it clears the whole wisps table (ephemeral beads) AND any durable bead with no history row, in one pass. Behind the `issues.sweep.wispsPlane` behavior token: an older server answers `invalid_value` for this member, since it predates the token and knows only the first two values.
Tier SweepRequestTier `json:"tier"`
}
// SweepRequestTier Which plane to clear. `ephemeral` is the wisp tier (`bd purge`) and `durable` is the issue tier (`bd prune`). The two are DISJOINT: a sweep of one can never touch a bead of the other. Required, with no default — a caller handed the wrong tier has nothing to notice until the beads are gone.
//
// `wisps-plane` is a THIRD, wider tier: it clears the whole wisps table (ephemeral beads) AND any durable bead with no history row, in one pass. Behind the `issues.sweep.wispsPlane` behavior token: an older server answers `invalid_value` for this member, since it predates the token and knows only the first two values.
type SweepRequestTier string
// SweepResult What one sweep did. Every number describes the SAME snapshot, because the selection and the deletion ran in one transaction.
@ -1973,18 +2004,24 @@ type SweepResult struct {
// ReferencedIds A BOUNDED SAMPLE of the ids `skipped.referenced` counts — at most 100, in the order the candidate query returned them. It is a sample, not the set: compare its length against 100 to tell a truncated one from a complete one. Absent when nothing was protected.
ReferencedIds *[]string `json:"referenced_ids,omitempty"`
// Skipped The candidates a sweep declined to delete, bucketed by WHY. They are separate counters rather than one number because they mean different things: the first two are PROTECTIONS, and the last four are the sweep declining to trust its own input.
// Remaining How many beads this sweep's own selection left unswept because `limit` cut it off, oldest-closed-first. Always 0 when `limit` was absent, zero, or at least as large as the matching set — never a dropped count, a 0 here means nothing was left over. Present only behind the `issues.sweep.limit` behavior token.
Remaining *int64 `json:"remaining,omitempty"`
// Skipped The candidates a sweep declined to delete, bucketed by WHY. They are separate counters rather than one number because they mean different things: `pinned`, `referenced` and `live_dependent` are PROTECTIONS, and the other four are the sweep declining to trust its own input.
Skipped SweepSkips `json:"skipped"`
// Swept How many beads were deleted, or under `dry_run` would be.
Swept int `json:"swept"`
}
// SweepSkips The candidates a sweep declined to delete, bucketed by WHY. They are separate counters rather than one number because they mean different things: the first two are PROTECTIONS, and the last four are the sweep declining to trust its own input.
// SweepSkips The candidates a sweep declined to delete, bucketed by WHY. They are separate counters rather than one number because they mean different things: `pinned`, `referenced` and `live_dependent` are PROTECTIONS, and the other four are the sweep declining to trust its own input.
type SweepSkips struct {
// ClosedAtOrAfterCutoff Candidates whose close timestamp did not satisfy `closed_before`. See `not_closed`.
ClosedAtOrAfterCutoff int `json:"closed_at_or_after_cutoff"`
// LiveDependent Candidates protected by `protect_live_dependents`. Always 0 when that member is false or absent. Present only behind the `issues.sweep.liveDependents` behavior token.
LiveDependent *int `json:"live_dependent,omitempty"`
// NotClosed Candidates the tier query returned that the recheck found were not closed. A NON-ZERO VALUE HERE IS A DEFENSE FIRING, not a normal outcome: the query asked for exactly the beads this excludes.
NotClosed int `json:"not_closed"`

View file

@ -119,6 +119,36 @@ const CapIssuesListSort = "issues.list.sort"
// count.
const CapIssuesCountScope = "issues.count.scope"
// CapIssuesSweepWispsPlane is the behavior capability that advertises the
// `wisps-plane` value of SweepRequest.tier (sweep.go, spec SweepRequest.tier):
// a third, wider tier that clears the whole wisps table plus any durable bead
// with no history row, in one pass (issueops.SweepWispsPlane). An older
// server predating this token answers the value with a `400
// invalid_argument`/`invalid_value` naming the member, the same per-value
// refusal CapIssuesCountScope's doc describes for a whole parameter. The
// client MUST check this token before sending `tier: "wisps-plane"` to a
// server that may predate it.
const CapIssuesSweepWispsPlane = "issues.sweep.wispsPlane"
// CapIssuesSweepLiveDependents is the behavior capability that advertises
// SweepRequest.protect_live_dependents and the paired SweepSkips.live_dependent
// response member (sweep.go): skip a closed candidate a live bead still
// depends on, transitively, across the ephemeral/durable plane boundary
// (issueops.SweepRequest.ProtectLiveDependents). An older server predating
// this token answers the request member with `400
// invalid_argument`/`unknown_parameter`. The client MUST check this token
// before sending the member to a server that may predate it.
const CapIssuesSweepLiveDependents = "issues.sweep.liveDependents"
// CapIssuesSweepLimit is the behavior capability that advertises
// SweepRequest.limit and the paired SweepResult.remaining response member
// (sweep.go): cap how many beads one sweep deletes, oldest-closed-first
// (issueops.SweepRequest.Limit / SweepResult.Remaining). An older server
// predating this token answers the request member with `400
// invalid_argument`/`unknown_parameter`. The client MUST check this token
// before sending the member to a server that may predate it.
const CapIssuesSweepLimit = "issues.sweep.limit"
// customMethodTarget splits the custom method off the segment the router
// matched, and reports the row that claims it.
//
@ -866,7 +896,10 @@ func (r route) specPathOf() string {
// route. project.enforce announces per-request Bd-Project-Id enforcement
// (checkProjectStamp): a stamped client reads it to know the refusal is available
// rather than silently dropped by an older server.
var behaviorCapabilities = []string{CapProjectEnforce, CapBatchApplyLarge, CapIssuesListSort, CapIssuesCountScope}
var behaviorCapabilities = []string{
CapProjectEnforce, CapBatchApplyLarge, CapIssuesListSort, CapIssuesCountScope,
CapIssuesSweepWispsPlane, CapIssuesSweepLiveDependents, CapIssuesSweepLimit,
}
// Capabilities lists what this build advertises in ContextResponse.capabilities:
// the operations it actually implements, gated on `implemented` so a stub can

View file

@ -635,7 +635,8 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
// them; project.enforce and issues.batchApplyLarge are advertised in the
// same list. Both are spelled literally here to keep this an independent
// oracle rather than a second call to the code under test.
want = append(want, "project.enforce", "issues.batchApplyLarge", "issues.list.sort", "issues.count.scope")
want = append(want, "project.enforce", "issues.batchApplyLarge", "issues.list.sort", "issues.count.scope",
"issues.sweep.wispsPlane", "issues.sweep.liveDependents", "issues.sweep.limit")
slices.Sort(want)
if !slices.Equal(got, want) {
t.Errorf("capabilities = %v, want %v", got, want)

View file

@ -7962,7 +7962,16 @@ components:
`issues.count.scope`, which announces that
`GET /v0/beads/issues:count` accepts `parent`, `no_parent`,
`exclude_type`, and `exclude_status` (see those parameters) rather
than silently answering `unknown_parameter` for all four. The
than silently answering `unknown_parameter` for all four,
`issues.sweep.wispsPlane`, which announces that
`POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of
`tier` rather than silently answering `invalid_value`,
`issues.sweep.liveDependents`, which announces that the same
operation accepts `protect_live_dependents` and answers
`skipped.live_dependent` rather than silently answering
`unknown_parameter`, and `issues.sweep.limit`, which announces
that it accepts `limit` and answers `remaining` rather than
silently answering `unknown_parameter`. The
list grows additively, and an operation never appears here unless
it is fully implemented. This is how a client checks for an
operation or a behavior — never the version string.
@ -8011,7 +8020,25 @@ components:
had moved underneath it. That silent gap is the whole reason
this field exists.
* `2` — the first release whose `ContextResponse` carries
`wire_revision` and `min_client_wire_revision` at all (this one).
`wire_revision` and `min_client_wire_revision` at all. Still
current: S4 widened `SweepRequest.tier`'s enum to add
`wisps-plane` and added `protect_live_dependents` and `limit`
alongside it, and none of the three bumped this counter.
`SweepRequest` is a REQUEST-body-only schema — no response ever
carries it — so nothing decodes it out of a server reply; the
new enum member and the two new fields are each something only
an UPDATED CLIENT chooses to send, behind their own behavior
tokens (`issues.sweep.wispsPlane`, `issues.sweep.liveDependents`,
`issues.sweep.limit`). An old client that never sends any of the
three has nothing to misdecode, which is exactly the additive
case this field exists to NOT gate. The wireshape drift gate
(`internal/httpapi/wireshape`) tracks, per member, whether it is
reachable from a request body, a response, or both, and treats
an enum WIDENING as additive only on a request-only member —
the identical widening on a response-side (or request+response)
member still counts as changed and still demands a bump, since
an existing client decoding a response must keep recognizing
every value the server might send it.
PRESENCE, not just value: a generated client whose JSON decoder
@ -8506,13 +8533,20 @@ components:
properties:
tier:
type: string
enum: [ephemeral, durable]
enum: [ephemeral, durable, wisps-plane]
description: >-
Which plane to clear. `ephemeral` is the wisp tier (`bd purge`) and
`durable` is the issue tier (`bd prune`). The two are DISJOINT: a
sweep of one can never touch a bead of the other. Required, with no
default — a caller handed the wrong tier has nothing to notice
until the beads are gone.
`wisps-plane` is a THIRD, wider tier: it clears the whole wisps
table (ephemeral beads) AND any durable bead with no history row,
in one pass. Behind the `issues.sweep.wispsPlane` behavior token:
an older server answers `invalid_value` for this member, since it
predates the token and knows only the first two values.
actor:
type: string
minLength: 1
@ -8574,6 +8608,25 @@ components:
skips and the refusals are the same ones the real sweep would
produce, computed against the same snapshot — and nothing is
recorded in history either.
protect_live_dependents:
type: boolean
default: false
description: >-
Skip a closed candidate that a LIVE (not-done) bead depends on
through a parent/child, tracks, or blocks edge, so closing a
dependent's dependency does not erase the row a live bead still
points at. Protection is TRANSITIVE and crosses the ephemeral/durable
plane boundary. Behind the `issues.sweep.liveDependents` behavior
token: an older server answers `unknown_parameter` for this name.
limit:
type: integer
format: int64
description: >-
Cap how many beads this sweep deletes, OLDEST-CLOSED-FIRST. Absent
or zero means unbounded. A negative value is a `400`
invalid_argument, the same as the role's own ErrValidation. Behind
the `issues.sweep.limit` behavior token: an older server answers
`unknown_parameter` for this name.
SweepResult:
type: object
@ -8620,6 +8673,15 @@ components:
protected.
items:
type: string
remaining:
type: integer
format: int64
description: >-
How many beads this sweep's own selection left unswept because
`limit` cut it off, oldest-closed-first. Always 0 when `limit` was
absent, zero, or at least as large as the matching set — never a
dropped count, a 0 here means nothing was left over. Present only
behind the `issues.sweep.limit` behavior token.
SweepSkips:
type: object
@ -8633,8 +8695,8 @@ components:
description: >-
The candidates a sweep declined to delete, bucketed by WHY. They are
separate counters rather than one number because they mean different
things: the first two are PROTECTIONS, and the last four are the sweep
declining to trust its own input.
things: `pinned`, `referenced` and `live_dependent` are PROTECTIONS,
and the other four are the sweep declining to trust its own input.
properties:
pinned:
type: integer
@ -8667,6 +8729,12 @@ components:
description: >-
Rows the tier query returned as nothing at all. A defense of the
same kind, on a shape rather than a value.
live_dependent:
type: integer
description: >-
Candidates protected by `protect_live_dependents`. Always 0 when
that member is false or absent. Present only behind the
`issues.sweep.liveDependents` behavior token.
ReadyPage:
type: object

View file

@ -18,12 +18,14 @@ import (
// sharper reason: a narrowing term the server silently ignored would widen
// what is erased.
const (
sweepTierMember = "tier"
sweepActorMember = "actor"
sweepClosedBeforeMember = "closed_before"
sweepPatternMember = "pattern"
sweepProtectReferencedMember = "protect_referenced"
sweepDryRunMember = "dry_run"
sweepTierMember = "tier"
sweepActorMember = "actor"
sweepClosedBeforeMember = "closed_before"
sweepPatternMember = "pattern"
sweepProtectReferencedMember = "protect_referenced"
sweepDryRunMember = "dry_run"
sweepProtectLiveDependentsMember = "protect_live_dependents"
sweepLimitMember = "limit"
)
// sweepMembers is the whole vocabulary, in one place, so the unknown-member
@ -36,6 +38,8 @@ var sweepMembers = []string{
sweepPatternMember,
sweepProtectReferencedMember,
sweepDryRunMember,
sweepProtectLiveDependentsMember,
sweepLimitMember,
}
// handleSweep answers POST /v0/beads/issues:sweep — one of the two DESTRUCTIVE
@ -51,7 +55,7 @@ var sweepMembers = []string{
// would be one handler away from an unguarded mass delete.
//
// Everything above the role here is argument validation: the media type, the
// body shape, and the six members the document publishes.
// body shape, and the eight members the document publishes.
//
// NO ACTOR IS INFERRED, for the reason the claim gives: the server's own
// identity is meaningless to a remote caller. Unlike the claim, the actor is
@ -148,7 +152,7 @@ func (s *Server) sweepRequest(w http.ResponseWriter, r *http.Request) (issueops.
// name the member.
if !apigen.SweepRequestTier(*tier).Valid() {
s.fail(w, r, InvalidArgument(sweepTierMember, ReasonInvalidValue,
"`"+sweepTierMember+"` must be \"ephemeral\" or \"durable\""))
"`"+sweepTierMember+"` must be \"ephemeral\", \"durable\", or \"wisps-plane\""))
return issueops.SweepRequest{}, false
}
request.Tier = issueops.SweepTier(*tier)
@ -200,6 +204,7 @@ func (s *Server) sweepRequest(w http.ResponseWriter, r *http.Request) (issueops.
}{
{sweepProtectReferencedMember, &request.ProtectReferenced},
{sweepDryRunMember, &request.DryRun},
{sweepProtectLiveDependentsMember, &request.ProtectLiveDependents},
} {
raw, ok := members[flag.member]
if !ok {
@ -214,6 +219,20 @@ func (s *Server) sweepRequest(w http.ResponseWriter, r *http.Request) (issueops.
*flag.dest = *value
}
if raw, ok := members[sweepLimitMember]; ok {
var value *int64
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
s.fail(w, r, InvalidArgument(sweepLimitMember, ReasonInvalidValue,
"`"+sweepLimitMember+"` must be an integer"))
return issueops.SweepRequest{}, false
}
// A negative value is NOT refused here. The role refuses it
// (issueops.ErrValidation), and routing it through the role is what
// keeps one definition of what a valid limit is, the same way a
// malformed pattern is left to the role above.
request.Limit = int(*value)
}
return request, true
}
@ -267,8 +286,11 @@ func sweepResponse(result issueops.SweepResult) apigen.SweepResult {
UnknownClosedAt: result.Skipped.UnknownClosedAt,
ClosedAtOrAfterCutoff: result.Skipped.ClosedAtOrAfterCutoff,
Unreadable: result.Skipped.Unreadable,
LiveDependent: &result.Skipped.LiveDependent,
},
}
remaining := int64(result.Remaining)
body.Remaining = &remaining
if len(result.ReferencedIDs) > 0 {
ids := append([]string(nil), result.ReferencedIDs...)
body.ReferencedIds = &ids

View file

@ -11,7 +11,7 @@ import (
)
// The pins for POST /v0/beads/issues:sweep. What is asserted here is the WIRE
// EDGE — that the handler decodes the document's six members into the role's
// EDGE — that the handler decodes the document's eight members into the role's
// request faithfully, refuses what the document refuses, and does not
// re-implement anything the role owns.
@ -42,7 +42,7 @@ func TestSweepPathReachesItsHandler(t *testing.T) {
}
// TestSweepForwardsEveryDocumentedMember is the operation's central pin: each
// of the six body members reaches the role's request unchanged.
// of the eight body members reaches the role's request unchanged.
//
// It is asserted on the REQUEST the role received rather than on the response:
// a body carrying the right numbers says nothing about which set was swept, and
@ -57,7 +57,9 @@ func TestSweepForwardsEveryDocumentedMember(t *testing.T) {
"closed_before": "2026-03-01T12:00:00Z",
"pattern": "bd-old-*",
"protect_referenced": true,
"dry_run": true
"dry_run": true,
"protect_live_dependents": true,
"limit": 25
}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
@ -72,10 +74,12 @@ func TestSweepForwardsEveryDocumentedMember(t *testing.T) {
Tier: issueops.SweepDurable,
// TRIMMED, by the same rule and the same function the claim's actor
// goes through: it reaches the same commit-message interpolation.
Actor: "alice",
IDPattern: "bd-old-*",
ProtectReferenced: true,
DryRun: true,
Actor: "alice",
IDPattern: "bd-old-*",
ProtectReferenced: true,
DryRun: true,
ProtectLiveDependents: true,
Limit: 25,
}
cutoff := time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
want.ClosedBefore = &cutoff
@ -149,7 +153,9 @@ func TestSweepPublishesTheWholeResult(t *testing.T) {
Skipped: issueops.SweepSkips{
Pinned: 1, Referenced: 2, NotClosed: 3,
UnknownClosedAt: 4, ClosedAtOrAfterCutoff: 5, Unreadable: 6,
LiveDependent: 8,
},
Remaining: 13,
ReferencedIDs: []string{"bd-1", "bd-2"},
}}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
@ -169,6 +175,7 @@ func TestSweepPublishesTheWholeResult(t *testing.T) {
{"dependencies", float64(3)},
{"labels", float64(2)},
{"events", float64(11)},
{"remaining", float64(13)},
} {
if body[want.key] != want.val {
t.Errorf("%s = %v, want %v", want.key, body[want.key], want.val)
@ -182,6 +189,7 @@ func TestSweepPublishesTheWholeResult(t *testing.T) {
for key, want := range map[string]float64{
"pinned": 1, "referenced": 2, "not_closed": 3,
"unknown_closed_at": 4, "closed_at_or_after_cutoff": 5, "unreadable": 6,
"live_dependent": 8,
} {
if skipped[key] != want {
t.Errorf("skipped.%s = %v, want %v", key, skipped[key], want)
@ -194,6 +202,56 @@ func TestSweepPublishesTheWholeResult(t *testing.T) {
}
}
// TestSweepResponseCarriesEveryRoleField is the guard sweepResponse's comment
// names, the sweep twin of TestDeleteResponseCarriesEveryRoleField. It counts
// fields at both levels the projection copies — the result and its skip
// buckets — and then projects a result with every role field set, so a wire
// field the projection leaves zero or nil fails as well as a field added to
// one side and not the other.
func TestSweepResponseCarriesEveryRoleField(t *testing.T) {
full := issueops.SweepResult{
DryRun: true, Swept: 1, Dependencies: 2, Labels: 3, Events: 4,
Skipped: issueops.SweepSkips{
Pinned: 5, Referenced: 6, LiveDependent: 7, NotClosed: 8,
UnknownClosedAt: 9, ClosedAtOrAfterCutoff: 10, Unreadable: 11,
},
Remaining: 12,
ReferencedIDs: []string{"bd-1"},
}
body := sweepResponse(full)
for _, level := range []struct{ role, wire any }{
{full, body},
{full.Skipped, body.Skipped},
} {
role, wire := reflect.TypeOf(level.role), reflect.TypeOf(level.wire)
if role.NumField() != wire.NumField() {
t.Errorf("%v has %d fields and %v has %d: a field was added to one and not projected onto the "+
"other (see sweepResponse)", role, role.NumField(), wire, wire.NumField())
}
}
requireEveryFieldSet(t, reflect.ValueOf(body), "SweepResult")
}
// requireEveryFieldSet fails for each field of the struct v, followed through
// pointers and into nested structs, that still holds its zero value.
func requireEveryFieldSet(t *testing.T, v reflect.Value, path string) {
t.Helper()
for i := range v.NumField() {
field, name := v.Field(i), path+"."+v.Type().Field(i).Name
if field.Kind() == reflect.Pointer && !field.IsNil() {
field = field.Elem()
}
if field.Kind() == reflect.Struct {
requireEveryFieldSet(t, field, name)
continue
}
if field.IsZero() {
t.Errorf("%s is unset although every role field was set: sweepResponse does not project it", name)
}
}
}
// TestSweepOmitsAnEmptyReferencedSample: the member is documented ABSENT when
// nothing was protected, so a client can tell "nothing cited" from "the
// protection was not asked for" without a second field.
@ -229,6 +287,9 @@ func TestSweepRefusesTheDocumentedBodies(t *testing.T) {
{"pattern is not a string", `{"tier":"ephemeral","pattern":true}`, "pattern"},
{"dry_run is not a boolean", `{"tier":"ephemeral","dry_run":"yes"}`, "dry_run"},
{"protect_referenced is not a boolean", `{"tier":"ephemeral","protect_referenced":1}`, "protect_referenced"},
{"protect_live_dependents is not a boolean", `{"tier":"ephemeral","protect_live_dependents":"yes"}`, "protect_live_dependents"},
{"limit is not an integer", `{"tier":"ephemeral","limit":2.5}`, "limit"},
{"limit is null", `{"tier":"ephemeral","limit":null}`, "limit"},
} {
t.Run(test.name, func(t *testing.T) {
sweeper := &roleSweeper{}

View file

@ -4181,12 +4181,25 @@
"type": "boolean",
"required": false
},
{
"schema": "SweepRequest",
"member": "limit",
"type": "integer",
"format": "int64",
"required": false
},
{
"schema": "SweepRequest",
"member": "pattern",
"type": "string",
"required": false
},
{
"schema": "SweepRequest",
"member": "protect_live_dependents",
"type": "boolean",
"required": false
},
{
"schema": "SweepRequest",
"member": "protect_referenced",
@ -4199,7 +4212,8 @@
"type": "string",
"enum": [
"durable",
"ephemeral"
"ephemeral",
"wisps-plane"
],
"required": true
},
@ -4234,6 +4248,13 @@
"required": false,
"item_type": "string"
},
{
"schema": "SweepResult",
"member": "remaining",
"type": "integer",
"format": "int64",
"required": false
},
{
"schema": "SweepResult",
"member": "skipped",
@ -4252,6 +4273,12 @@
"type": "integer",
"required": true
},
{
"schema": "SweepSkips",
"member": "live_dependent",
"type": "integer",
"required": false
},
{
"schema": "SweepSkips",
"member": "not_closed",
@ -5971,5 +5998,146 @@
"style": "form",
"explode": true
}
]
],
"sides": {
"AddCommentRequest": "request",
"AddDependenciesRequest": "request",
"AddDependenciesResponse": "response",
"AnchorEdgeCount": "response",
"ApplyBatchRequest": "request",
"ApplyBatchResponse": "response",
"ApplyBatchResponse.keys": "response",
"ApplyBatchResponse.keys{}": "response",
"ApplyCloseItem": "request",
"ApplyCreateItem": "request",
"ApplyCreateItem.labels[]": "request",
"ApplyCreateItem.metadata_refs": "request",
"ApplyDepAddItem": "request",
"ApplyItem": "request",
"ApplyItemResult": "response",
"ApplyLabelPatch": "request",
"ApplyLabelPatch.add[]": "request",
"ApplyLabelPatch.remove[]": "request",
"ApplyLabelPatch.replace[]": "request",
"ApplyMetadataPatch": "request",
"ApplyMetadataPatch.set": "request",
"ApplyMetadataPatch.unset[]": "request",
"ApplyPatchBody": "request",
"ApplyUpdateItem": "request",
"BatchCloseItem": "request",
"BatchCloseRequest": "request",
"BatchCloseResponse": "response",
"BatchCreateDependency": "request",
"BatchCreateItem": "request",
"BatchCreateItem.labels[]": "request",
"BatchCreateRequest": "request",
"BatchCreateResponse": "response",
"BatchGetIssue": "response",
"BatchGetIssue.labels[]": "response",
"BatchGetIssue.metadata": "response",
"BatchGetIssue.waiters[]": "response",
"BatchGetIssuesRequest": "request",
"BatchGetIssuesRequest.ids[]": "request",
"BatchGetIssuesResult": "response",
"BatchGetIssuesResult.missing[]": "response",
"Blocker": "response",
"BlockingAnnotations": "response",
"BondRef": "response",
"ClaimNextRequest": "request",
"ClaimNextResponse": "response",
"ClaimRequest": "request",
"ClaimResponse": "response",
"CloseIssueRequest": "request",
"CloseIssueResponse": "response",
"CloseOutcome": "response",
"Comment": "response",
"CompareAndSetMetadataRequest": "request",
"CompareAndSetMetadataResponse": "response",
"ContextResponse": "response",
"ContextResponse.capabilities[]": "response",
"CreateIssueDependency": "request",
"CreateIssueRequest": "request",
"CreateIssueRequest.labels[]": "request",
"CreateIssueWaitsFor": "request",
"Cycle": "response",
"CycleMember": "response",
"CyclesPage": "response",
"DeleteIssuesRequest": "request",
"DeleteIssuesRequest.ids[]": "request",
"DeleteIssuesResult": "response",
"DeleteIssuesResult.orphaned[]": "response",
"Dependency": "response",
"DependencyEdge": "both",
"DependencyEdges": "response",
"DependencyEdges.missing[]": "response",
"DependencyTreePage": "response",
"EdgeCounts": "response",
"EventRecord": "response",
"EventRecord.comment": "response",
"EventRecord.dep": "response",
"EventRecord.issue": "response",
"EventsPage": "response",
"Health": "response",
"Issue": "response",
"Issue.labels[]": "response",
"Issue.metadata": "response",
"Issue.waiters[]": "response",
"IssueBlocking": "response",
"IssueBlocking.blocked_by[]": "response",
"IssueBlocking.blocks[]": "response",
"IssueCount": "response",
"IssueCount.groups": "response",
"IssueCount.groups{}": "response",
"IssueDetails": "response",
"IssueDetails.gated_by[]": "response",
"IssueDetails.labels[]": "response",
"IssueDetails.metadata": "response",
"IssueDetails.waiters[]": "response",
"IssuePatchBody": "request",
"IssuePatchBody.add_labels[]": "request",
"IssuePatchBody.labels[]": "request",
"IssuePatchBody.remove_labels[]": "request",
"IssueWithCounts": "response",
"IssueWithCounts.labels[]": "response",
"IssueWithCounts.metadata": "response",
"IssueWithCounts.waiters[]": "response",
"IssueWithDependencyMetadata": "response",
"IssueWithDependencyMetadata.labels[]": "response",
"IssueWithDependencyMetadata.metadata": "response",
"IssueWithDependencyMetadata.waiters[]": "response",
"IssuesPage": "response",
"MemoriesPage": "response",
"Memory": "response",
"MetadataValue": "request",
"Problem": "response",
"QueryPage": "response",
"ReadyCount": "response",
"ReadyPage": "response",
"Ref": "request",
"RelatedIssues": "response",
"ReleaseIssueRequest": "request",
"ReleaseIssueResponse": "response",
"RememberRequest": "request",
"RememberedMemory": "response",
"RemoveDependencyRequest": "request",
"RemoveDependencyResponse": "response",
"RemovedSetting": "response",
"ReopenIssueRequest": "request",
"ReopenIssueResponse": "response",
"SetSettingRequest": "request",
"Setting": "response",
"SettingsPage": "response",
"Statistics": "response",
"StatsResponse": "response",
"SweepRequest": "request",
"SweepResult": "response",
"SweepResult.referenced_ids[]": "response",
"SweepSkips": "response",
"TreeNode": "response",
"TreeNode.labels[]": "response",
"TreeNode.metadata": "response",
"TreeNode.waiters[]": "response",
"UpdateIssueRequest": "request",
"UpdateIssueResponse": "response"
}
}

View file

@ -98,19 +98,35 @@ func paramKey(operationID, in, name string) (schema, member string) {
}
// Digest is the golden document: the wire revision it was computed against,
// plus every member entry, sorted for a stable diff.
// every member entry (sorted for a stable diff), and Sides — a side-channel
// map from schema name to "request", "response" or "both", recording which
// kind of body (if any) ever reaches that NAMED schema during the walk.
//
// Sides is deliberately NOT a field on Entry itself: Entry is the shape the
// golden pins per member, and giving every member its own copy of the same
// per-SCHEMA fact would turn "we now also track reachability" into a
// spurious Changed diff on every existing entry the day this shipped, which
// is exactly the noise a real, deliberate wire change is supposed to stand
// out from. Keeping it a separate, schema-keyed map makes adding this
// bookkeeping itself a pure addition to the digest.
type Digest struct {
WireRevision int `json:"wire_revision"`
Entries []Entry `json:"entries"`
WireRevision int `json:"wire_revision"`
Entries []Entry `json:"entries"`
Sides map[string]string `json:"sides,omitempty"`
}
// CompareResult is the outcome of diffing two digests by "schema\x00member"
// key: Changed holds keys present in both whose Entry differs, Removed holds
// keys only want has, and Added holds keys only got has.
// key: Changed holds keys present in both whose Entry differs non-additively,
// Removed holds keys only want has, Added holds keys only got has, and
// Widened holds keys present in both whose ONLY difference is a request-only
// enum strictly widening (see widensAdditively) — additive, like Added, but
// kept in its own bucket so a reader can tell "this key is new" apart from
// "this key's enum grew" at a glance.
type CompareResult struct {
Changed []string
Removed []string
Added []string
Widened []string
}
// Compare diffs want (typically the committed golden) against got (typically
@ -135,6 +151,10 @@ func Compare(want, got Digest) CompareResult {
continue
}
if !reflect.DeepEqual(w, g) {
if widensAdditively(w, g, want.Sides[w.Schema], got.Sides[g.Schema]) {
result.Widened = append(result.Widened, key)
continue
}
result.Changed = append(result.Changed, key)
}
}
@ -146,9 +166,51 @@ func Compare(want, got Digest) CompareResult {
sort.Strings(result.Changed)
sort.Strings(result.Removed)
sort.Strings(result.Added)
sort.Strings(result.Widened)
return result
}
// widensAdditively reports whether old -> new differs ONLY in Enum, with
// new's Enum a strict superset of old's, and oldSide/newSide (the entry's
// Schema looked up in each Digest's Sides map) both exactly "request". That
// combination is additive, not a wire break: a request-only member is never
// decoded out of a response, so the CLIENT alone decides whether it sends
// one of the new values — an old client that never sends the new member
// never has anything to misdecode. Any other difference (type, format,
// required, nullable, item/additional-props shape, or an enum NARROWING or
// reordering-with-removal) is excluded here and falls through to the
// ordinary non-additive Changed path, as does the identical widening on a
// "response" or "both" (or unknown/param, "") side, where an existing client
// decoding a response must still recognize every value the server might
// send. An old side with NO enum at all (a free-form string) is the limit
// case of a narrowing — going from unconstrained to any fixed set is a new
// restriction the server did not enforce before, not a widening — so it is
// excluded too: len(old.Enum) == 0 falls through to Changed just like a
// strict narrowing does.
func widensAdditively(old, new Entry, oldSide, newSide string) bool { //nolint:revive // "new" reads clearest paired with "old" here
if oldSide != sideRequest || newSide != sideRequest {
return false
}
oldNoEnum, newNoEnum := old, new
oldNoEnum.Enum, newNoEnum.Enum = nil, nil
if !reflect.DeepEqual(oldNoEnum, newNoEnum) {
return false
}
if len(old.Enum) == 0 || len(new.Enum) <= len(old.Enum) {
return false
}
newSet := make(map[string]bool, len(new.Enum))
for _, v := range new.Enum {
newSet[v] = true
}
for _, v := range old.Enum {
if !newSet[v] {
return false
}
}
return true
}
// SafeToWrite is gendigest's write guard (review MEDIUM: "refuse to write
// changed or removed entries unless CurrentWireRevision is higher than the
// golden's recorded revision. Additive entries are allowed."). A pure
@ -218,7 +280,7 @@ func computeFrom(document []byte, wireRevision int) (Digest, error) {
return Digest{}, fmt.Errorf("parse openapi document: %w", err)
}
c := &collector{doc: doc, visited: map[string]bool{}, byKey: map[string]Entry{}}
c := &collector{doc: doc, sideWalked: map[string]bool{}, byKey: map[string]Entry{}, sideOf: map[string]string{}}
paths, _ := doc["paths"].(map[string]any)
for _, item := range paths {
@ -242,12 +304,12 @@ func computeFrom(document []byte, wireRevision int) (Digest, error) {
continue
}
respMap = c.resolveAny(respMap)
c.walkContent(respMap)
c.walkContent(respMap, sideResponse)
}
if rb, ok := op["requestBody"].(map[string]any); ok {
rb = c.resolveAny(rb)
c.walkContent(rb)
c.walkContent(rb, sideRequest)
}
operationID := asString(op["operationId"])
@ -272,14 +334,30 @@ func computeFrom(document []byte, wireRevision int) (Digest, error) {
}
return entries[i].Member < entries[j].Member
})
return Digest{WireRevision: wireRevision, Entries: entries}, nil
return Digest{WireRevision: wireRevision, Entries: entries, Sides: c.sideOf}, nil
}
// sideRequest and sideResponse are the two values recordSide ever writes
// directly into Digest.Sides (keyed by schema name, not by Entry); an
// unrecorded schema — a parameter's container, or any schema this walk never
// reaches — simply has no key, which Compare's map lookup reads as "" and
// widensAdditively then treats as ineligible, the same as sideResponse.
const (
sideRequest = "request"
sideResponse = "response"
// sideBoth marks a schema reached from both a request and a response
// walk — recordSide promotes to it the moment the two disagree, and it is
// never eligible for the enum-widening carve-out any more than
// sideResponse is.
sideBoth = "both"
)
// walkContent walks every media type's schema under a resolved response or
// requestBody node's `content` map. Shared by Compute's response and request
// body loops: a response object and a resolved requestBody object are both
// shaped `{content: {mediaType: {schema: ...}}}`.
func (c *collector) walkContent(node map[string]any) {
// requestBody node's `content` map, tagging every schema it reaches in
// Digest.Sides (via walk's recordSide calls). Shared by Compute's response
// and request body loops: a response object and a resolved requestBody
// object are both shaped `{content: {mediaType: {schema: ...}}}`.
func (c *collector) walkContent(node map[string]any, side string) {
content, _ := node["content"].(map[string]any)
for _, rawMedia := range content {
media, ok := rawMedia.(map[string]any)
@ -290,7 +368,7 @@ func (c *collector) walkContent(node map[string]any) {
if !ok {
continue
}
c.walk(schemaNode, "")
c.walk(schemaNode, "", side)
}
}
@ -375,9 +453,34 @@ func defaultParamStyle(in string) string {
}
type collector struct {
doc map[string]any
visited map[string]bool
byKey map[string]Entry // "schema\x00member" -> Entry
doc map[string]any
// sideWalked guards recursion into a named (or synthetically labeled)
// node's properties, keyed by "name\x00side" rather than by name alone
// (see walk's doc comment for why: name alone let a node visited first
// from one side block the OTHER side's walk from ever reaching that
// node's children).
sideWalked map[string]bool
byKey map[string]Entry // "schema\x00member" -> Entry
sideOf map[string]string
}
// recordSide notes that schema name was reached via side ("request" or
// "response"), promoting to sideBoth the moment the two disagree. It runs on
// EVERY visit to name, including one walk skips the properties of because
// visited already marked it seen — a schema visited first from a response
// and only later from a request must still end up "both", not stuck at
// whichever context happened to walk its properties.
func (c *collector) recordSide(name, side string) {
if name == "" || side == "" {
return
}
existing, ok := c.sideOf[name]
switch {
case !ok:
c.sideOf[name] = side
case existing != side:
c.sideOf[name] = sideBoth
}
}
// lookup resolves one local $ref to the node it names. It returns nil for
@ -473,12 +576,25 @@ func defaultString(v any) string {
// recorded under it; a $ref always overrides it with the component's own
// name.
//
// Every NAMED schema is walked at most once (the visited guard), which is
// what makes a cycle between named schemas (and there is at least the
// potential for one as this document grows) a no-op rather than a stack
// overflow, and what makes the digest the same whichever operation reaches a
// shared schema first.
func (c *collector) walk(node map[string]any, label string) {
// Recursion into a (name, side) pair's properties happens at most once (the
// sideWalked guard), which is what makes a cycle between named schemas (and
// there is at least the potential for one as this document grows) a no-op
// rather than a stack overflow. The guard is keyed on side, NOT on name
// alone: a schema reached first from a request and later from a response
// (directly, or nested under some other schema the response reaches) must
// still have its PROPERTIES walked a second time with side="response", so
// every descendant that is itself reachable from a response gets recordSide
// called for that side too. Gating on name alone — walked once, ever,
// regardless of which side asks — promotes the node ITSELF to "both" (recordSide
// runs unconditionally before the guard) while leaving every child stuck at
// whichever side first walked down into it: a child nested two levels under a
// schema shared by both a request and a response would silently stay
// request-only or response-only depending on map iteration order, which is
// exactly backwards for a digest whose whole job is deciding whether an enum
// widening is additive by side. TestSidePropagatesToNestedChildren and
// TestComputeFromSideAssignmentIsDeterministic pin both the correctness and
// the order-independence of this.
func (c *collector) walk(node map[string]any, label string, side string) {
name := label
for {
ref, ok := node["$ref"].(string)
@ -507,11 +623,13 @@ func (c *collector) walk(node map[string]any, label string) {
node = merged
}
c.recordSide(name, side)
if name != "" {
if c.visited[name] {
sideKey := name + "\x00" + side
if c.sideWalked[sideKey] {
return
}
c.visited[name] = true
c.sideWalked[sideKey] = true
}
if props, ok := node["properties"].(map[string]any); ok {
@ -565,16 +683,16 @@ func (c *collector) walk(node map[string]any, label string) {
switch entry.Type {
case "object":
c.walk(propMap, name+"."+member)
c.walk(propMap, name+"."+member, side)
if addlPropsNode != nil {
// A map value that is itself a named/object schema gets
// its own members walked too, under a label distinct
// from an array's "[]" so the two can never collide.
c.walk(addlPropsNode, name+"."+member+"{}")
c.walk(addlPropsNode, name+"."+member+"{}", side)
}
case "array":
if itemsNode != nil {
c.walk(itemsNode, name+"."+member+"[]")
c.walk(itemsNode, name+"."+member+"[]", side)
}
}
}
@ -587,7 +705,7 @@ func (c *collector) walk(node map[string]any, label string) {
if itemLabel == "" {
itemLabel = label
}
c.walk(items, itemLabel+"[]")
c.walk(items, itemLabel+"[]", side)
}
}
}

View file

@ -2,6 +2,7 @@ package wireshape
import (
"reflect"
"slices"
"testing"
)
@ -106,6 +107,74 @@ func TestWalkParam(t *testing.T) {
}
}
// sideDoc exercises the three combinations Compute's side-tracking must tell
// apart: a schema reachable ONLY from a request body (reqOnly's ReqOnly), one
// reachable ONLY from a response (respOnly's RespOnly), and one reachable
// from both a request body and a response, on the SAME operation (bothSides'
// Shared) — the case recordSide's "promote to both" path exists for.
const sideDoc = `openapi: 3.0.3
paths:
/req-only:
post:
operationId: reqOnly
requestBody:
content:
application/json:
schema: {$ref: '#/components/schemas/ReqOnly'}
responses:
'200': {description: ok}
/resp-only:
get:
operationId: respOnly
responses:
'200':
description: ok
content:
application/json:
schema: {$ref: '#/components/schemas/RespOnly'}
/both:
put:
operationId: bothSides
requestBody:
content:
application/json:
schema: {$ref: '#/components/schemas/Shared'}
responses:
'200':
description: ok
content:
application/json:
schema: {$ref: '#/components/schemas/Shared'}
components:
schemas:
ReqOnly: {type: object, properties: {tier: {type: string, enum: [a, b]}}}
RespOnly: {type: object, properties: {tier: {type: string, enum: [a, b]}}}
Shared: {type: object, properties: {tier: {type: string, enum: [a, b]}}}
`
// TestSideTracking pins Compute's own Digest.Sides assignment (what
// widensAdditively's oldSide/newSide lookups rely on): a request-only schema
// is "request", a response-only schema is "response", and a schema reached
// from both — even when the already-visited path skips re-walking its
// properties — is promoted to "both", never stuck at whichever side happened
// to walk it first.
func TestSideTracking(t *testing.T) {
d, err := computeFrom([]byte(sideDoc), 2)
if err != nil {
t.Fatalf("computeFrom: %v", err)
}
for schema, wantSide := range map[string]string{
"ReqOnly": "request",
"RespOnly": "response",
"Shared": "both",
} {
if got := d.Sides[schema]; got != wantSide {
t.Errorf("Sides[%q] = %q, want %q", schema, got, wantSide)
}
}
}
// TestEffectiveSerializationIsCompared is the Compute-level falsification for
// recording effective style/explode values: changing how a parameter that
// relied on its defaults is serialized must be a changed entry SafeToWrite
@ -153,3 +222,162 @@ func TestEffectiveSerializationIsCompared(t *testing.T) {
})
}
}
// sharedNestedDoc reproduces the shape the MED1 re-review flagged: Parent is
// a request body (createParent) AND reachable from a response through
// Wrapper.p (getWrapper) — the same "reached from both sides" case sideDoc's
// Shared covers at the top level, but with two further wrinkles sideDoc
// cannot: Child is a NAMED schema nested two levels down (Parent.child,
// $ref'd), and Parent.inl is an ANONYMOUS nested object (no $ref of its own,
// so it is only ever identified by its synthetic "Parent.inl" label) with its
// own enum member. Both sit below the point where the old walk's name-only
// (not name+side) guard stopped recursing on Parent's SECOND visit, so
// recordSide was never called on them for whichever side arrived second —
// and which side that was depended on paths' map iteration order, which is
// why the bug showed up as a flaky 78/100 rather than a deterministic
// failure.
func sharedNestedDoc(kindEnum, modeEnum string) []byte {
return []byte(`openapi: 3.0.3
paths:
/parent:
post:
operationId: createParent
requestBody:
content:
application/json:
schema: {$ref: '#/components/schemas/Parent'}
responses:
'200': {description: ok}
/wrapper:
get:
operationId: getWrapper
responses:
'200':
description: ok
content:
application/json:
schema: {$ref: '#/components/schemas/Wrapper'}
components:
schemas:
Parent:
type: object
properties:
child: {$ref: '#/components/schemas/Child'}
inl:
type: object
properties:
mode: {type: string, enum: [` + modeEnum + `]}
Child:
type: object
properties:
kind: {type: string, enum: [` + kindEnum + `]}
Wrapper:
type: object
properties:
p: {$ref: '#/components/schemas/Parent'}
`)
}
// TestSidePropagatesToNestedChildren pins the MED1 re-review fix directly:
// Parent is reachable from both createParent's request body and, through
// Wrapper.p, getWrapper's response, and "both" must reach all the way down
// to its children — Child (a named, $ref'd grandchild) and Parent.inl (an
// anonymous nested object) alike — not stop at Parent itself. Before the
// fix, whichever side's walk reached Parent SECOND found it already in the
// name-only visited set and returned before ever recursing into Parent's
// properties with that side, so Child and Parent.inl stayed stuck at
// whichever single side walked them first.
func TestSidePropagatesToNestedChildren(t *testing.T) {
d, err := computeFrom(sharedNestedDoc("a, b", "a, b"), 2)
if err != nil {
t.Fatalf("computeFrom: %v", err)
}
want := map[string]string{
"Parent": "both",
"Child": "both",
"Parent.inl": "both",
"Wrapper": "response",
}
for schema, wantSide := range want {
if got := d.Sides[schema]; got != wantSide {
t.Errorf("Sides[%q] = %q, want %q", schema, got, wantSide)
}
}
}
// TestEnumWideningOnSharedNestedChildIsNotAdditive is the end-to-end
// Compare-level falsification the re-review asked for: widening an enum on a
// schema reachable from BOTH sides — whether a named grandchild ($ref'd
// Child.kind) or an anonymous nested one (Parent.inl.mode) — must be
// classified as a breaking Changed entry, never as an additive Widened one.
// An existing client decoding Wrapper out of getWrapper's response has to
// keep recognizing every value the server might send on either member, so
// neither widening is something only an updated client opts into the way a
// request-only widening is.
func TestEnumWideningOnSharedNestedChildIsNotAdditive(t *testing.T) {
for _, tc := range []struct {
name string
beforeKind, afterKind string
beforeMode, afterMode string
wantKey string
}{
{"named grandchild (Child.kind)", "a, b", "a, b, c", "a, b", "a, b", "Child\x00kind"},
{"anonymous nested child (Parent.inl.mode)", "a, b", "a, b", "a, b", "a, b, c", "Parent.inl\x00mode"},
} {
t.Run(tc.name, func(t *testing.T) {
before, err := computeFrom(sharedNestedDoc(tc.beforeKind, tc.beforeMode), 2)
if err != nil {
t.Fatalf("computeFrom(before): %v", err)
}
after, err := computeFrom(sharedNestedDoc(tc.afterKind, tc.afterMode), 2)
if err != nil {
t.Fatalf("computeFrom(after): %v", err)
}
cmp := Compare(before, after)
if !slices.Contains(cmp.Changed, tc.wantKey) {
t.Errorf("Changed = %v, want it to include %q: a both-sides enum widening must break", cmp.Changed, tc.wantKey)
}
if slices.Contains(cmp.Widened, tc.wantKey) {
t.Errorf("Widened = %v, must NOT include %q: both sides are reachable, so this is not additive", cmp.Widened, tc.wantKey)
}
if ok, _ := SafeToWrite(before, after); ok {
t.Errorf("SafeToWrite at the same revision = true, want false: this widening is breaking and needs a wire_revision bump")
}
bumped := Digest{WireRevision: before.WireRevision + 1, Entries: after.Entries, Sides: after.Sides}
if ok, reason := SafeToWrite(before, bumped); !ok {
t.Errorf("SafeToWrite with a bumped revision refused: %s", reason)
}
})
}
}
// TestComputeFromSideAssignmentIsDeterministic is the order-independence pin
// the re-review asked for: the bug this MED1 fix closes was map-order
// dependent (observed failing 78/100 runs), so a single passing run of
// TestSidePropagatesToNestedChildren does not rule out a regression that is
// merely less likely than before. Go randomizes map iteration order per
// range, including paths and properties here, so calling computeFrom many
// times over the SAME document input exercises many different traversal
// orders; every one of them must land on the identical Sides assignment and
// entry set.
func TestComputeFromSideAssignmentIsDeterministic(t *testing.T) {
doc := sharedNestedDoc("a, b", "a, b")
first, err := computeFrom(doc, 2)
if err != nil {
t.Fatalf("computeFrom: %v", err)
}
for i := 0; i < 200; i++ {
got, err := computeFrom(doc, 2)
if err != nil {
t.Fatalf("computeFrom (run %d): %v", i, err)
}
if !reflect.DeepEqual(got.Sides, first.Sides) {
t.Fatalf("run %d: Sides = %v, want %v (non-deterministic across map iteration orders)", i, got.Sides, first.Sides)
}
if !reflect.DeepEqual(got.Entries, first.Entries) {
t.Fatalf("run %d: Entries = %v, want %v (non-deterministic across map iteration orders)", i, got.Entries, first.Entries)
}
}
}

View file

@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
@ -25,8 +26,8 @@ import (
// revision table in openapi.v0.yaml, never before. A wire_revision LOWER than
// the golden's is never fixed by regenerating: that table is append-only, so
// the constant itself is wrong. Any other difference — a bumped
// wire_revision, or entries only added — means this golden is simply stale;
// regenerate it with:
// wire_revision, entries only added, or a `sides` map that no longer matches
// — means this golden is simply stale; regenerate it with:
//
// go run ./internal/httpapi/wireshape/cmd/gendigest
func TestWireShapeDigest(t *testing.T) {
@ -50,8 +51,8 @@ func TestWireShapeDigest(t *testing.T) {
// goldenDrift is TestWireShapeDigest's verdict, factored out so
// TestGoldenDrift can drive every arm with synthetic digests. It returns ""
// only when golden records exactly got — the same entries at the same
// wire_revision. Every other state fails; the arms only choose which
// only when golden records exactly got — the same entries and sides at the
// same wire_revision. Every other state fails; the arms only choose which
// instruction the failure gives.
func goldenDrift(golden, got wireshape.Digest) string {
if got.WireRevision < golden.WireRevision {
@ -62,7 +63,8 @@ func goldenDrift(golden, got wireshape.Digest) string {
}
cmp := wireshape.Compare(golden, got)
changed, removed, added := cmp.Changed, cmp.Removed, cmp.Added
changed, removed, added, widened := cmp.Changed, cmp.Removed, cmp.Added, cmp.Widened
sides := sidesDrift(golden.Sides, got.Sides)
switch {
case len(changed) > 0 || len(removed) > 0:
@ -77,40 +79,72 @@ func goldenDrift(golden, got wireshape.Digest) string {
"removed=%v) and wire_revision moved %d -> %d, but the golden was not regenerated: run "+
"`go run ./internal/httpapi/wireshape/cmd/gendigest` and commit the result",
changed, removed, golden.WireRevision, got.WireRevision)
case len(added) > 0:
case len(added) > 0 || len(widened) > 0:
// Widened (a request-only enum strictly growing) is additive, same as
// Added (a brand-new key): neither needs CurrentWireRevision to move,
// both just need the golden regenerated.
if got.WireRevision == golden.WireRevision {
return fmt.Sprintf("wire shape (response/request-body member or parameter) added (%v) but the "+
"golden was not regenerated: this is additive and needs no wire_revision bump, but still run "+
"`go run ./internal/httpapi/wireshape/cmd/gendigest` and commit the result", added)
return fmt.Sprintf("wire shape (response/request-body member or parameter) added (%v) or had a "+
"request-only enum widen (%v) but the golden was not regenerated: this is additive and needs "+
"no wire_revision bump, but still run `go run ./internal/httpapi/wireshape/cmd/gendigest` "+
"and commit the result", added, widened)
}
// Passing here would leave the golden a revision behind
// CurrentWireRevision, and a later non-additive change at that
// already-moved constant would then be told only to regenerate (which
// SafeToWrite allows) instead of to bump.
return fmt.Sprintf("wire shape (response/request-body member or parameter) added (%v) and "+
"wire_revision moved %d -> %d, but the golden was not regenerated: run "+
"`go run ./internal/httpapi/wireshape/cmd/gendigest` and commit the result",
added, golden.WireRevision, got.WireRevision)
return fmt.Sprintf("wire shape (response/request-body member or parameter) added (%v) or had a "+
"request-only enum widen (%v) and wire_revision moved %d -> %d, but the golden was not "+
"regenerated: run `go run ./internal/httpapi/wireshape/cmd/gendigest` and commit the result",
added, widened, golden.WireRevision, got.WireRevision)
case got.WireRevision != golden.WireRevision:
return fmt.Sprintf("CurrentWireRevision is %d but the golden still says %d, with no shape change to justify "+
"either: regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`",
got.WireRevision, golden.WireRevision)
case len(sides) > 0:
// Compare reads Sides only for the request-only widening carve-out, so
// a stale map changes no member's shape: it misfiles the next enum
// widening on those schemas instead. Nothing to bump, but the golden
// is still not what gendigest writes.
return fmt.Sprintf("the golden's `sides` map disagrees with a fresh digest for %v: this needs no "+
"wire_revision bump, but run `go run ./internal/httpapi/wireshape/cmd/gendigest` and commit the result",
sides)
}
return ""
}
// sidesDrift lists, sorted, every schema whose side differs between want and
// got, including a schema only one of them records.
func sidesDrift(want, got map[string]string) []string {
var drift []string
for schema, side := range want {
if gotSide, ok := got[schema]; !ok || gotSide != side {
drift = append(drift, schema)
}
}
for schema := range got {
if _, ok := want[schema]; !ok {
drift = append(drift, schema)
}
}
slices.Sort(drift)
return drift
}
// TestGoldenDrift is TestWireShapeDigest's own falsification: every way the
// committed golden can disagree with a fresh Compute must fail, each with its
// own instruction. "Added after a bump" is the state review found passing
// silently — no arm fired when entries were only added and wire_revision had
// also moved — and a LOWERED wire_revision was told to regenerate, which
// would have written the golden's revision backwards.
// would have written the golden's revision backwards. A stale `sides` map
// passed the same way until goldenDrift compared it.
func TestGoldenDrift(t *testing.T) {
golden := wireshape.Digest{
WireRevision: 2,
Entries: []wireshape.Entry{
{Schema: "Widget", Member: "name", Type: "string", Required: true},
},
Sides: map[string]string{"Widget": "response"},
}
changed := []wireshape.Entry{{Schema: "Widget", Member: "name", Type: "integer", Required: true}}
added := append(append([]wireshape.Entry{}, golden.Entries...),
@ -141,6 +175,15 @@ func TestGoldenDrift(t *testing.T) {
wireshape.Digest{WireRevision: 1, Entries: changed}, []string{"LOWER than the 2"}},
{"added entry at a lowered revision asks to restore the constant",
wireshape.Digest{WireRevision: 1, Entries: added}, []string{"LOWER than the 2"}},
{"side recorded only by the fresh digest asks for a regenerate",
wireshape.Digest{WireRevision: 2, Entries: golden.Entries,
Sides: map[string]string{"Widget": "response", "Gadget": "request"}},
[]string{"`sides` map disagrees", "[Gadget]", "needs no wire_revision bump"}},
{"side that moved asks for a regenerate",
wireshape.Digest{WireRevision: 2, Entries: golden.Entries, Sides: map[string]string{"Widget": "both"}},
[]string{"`sides` map disagrees", "[Widget]"}},
{"side recorded only by the golden asks for a regenerate",
wireshape.Digest{WireRevision: 2, Entries: golden.Entries}, []string{"`sides` map disagrees", "[Widget]"}},
} {
t.Run(tc.name, func(t *testing.T) {
drift := goldenDrift(golden, tc.got)
@ -258,6 +301,135 @@ func TestSafeToWrite(t *testing.T) {
})
}
// TestEnumWideningAdditivity is the falsification for widensAdditively
// (review MED 1: "the only trigger [for S4's wire_revision bump] is the
// request-only enum widening of SweepRequest.tier ... fix the wireshape gate
// so widening a request-only enum counts as additive, while response-side
// enum widening stays breaking"). Two synthetic digests, identical except for
// their Sides map, prove the carve-out is keyed on Sides alone — Entry itself
// never changes shape.
func TestEnumWideningAdditivity(t *testing.T) {
requestBase := wireshape.Digest{
WireRevision: 2,
Entries: []wireshape.Entry{
{Schema: "SweepRequest", Member: "tier", Type: "string", Required: true,
Enum: []string{"durable", "ephemeral"}},
},
Sides: map[string]string{"SweepRequest": "request"},
}
requestWidened := wireshape.Digest{
WireRevision: 2,
Entries: []wireshape.Entry{
{Schema: "SweepRequest", Member: "tier", Type: "string", Required: true,
Enum: []string{"durable", "ephemeral", "wisps-plane"}},
},
Sides: map[string]string{"SweepRequest": "request"},
}
t.Run("a request-only enum widening is additive at the same revision", func(t *testing.T) {
cmp := wireshape.Compare(requestBase, requestWidened)
if len(cmp.Changed) != 0 {
t.Fatalf("Changed = %v, want none (the widening belongs in Widened)", cmp.Changed)
}
if len(cmp.Widened) != 1 {
t.Fatalf("Widened = %v, want exactly one entry", cmp.Widened)
}
if ok, reason := wireshape.SafeToWrite(requestBase, requestWidened); !ok {
t.Fatalf("request-only enum widening at the same revision refused: %s", reason)
}
drift := goldenDrift(requestBase, requestWidened)
if drift == "" || !strings.Contains(drift, "needs no wire_revision bump") {
t.Fatalf("goldenDrift = %q, want an additive (no-bump) instruction", drift)
}
})
responseBase := wireshape.Digest{
WireRevision: 2,
Entries: []wireshape.Entry{
{Schema: "SweepResult", Member: "tier", Type: "string", Required: true,
Enum: []string{"durable", "ephemeral"}},
},
Sides: map[string]string{"SweepResult": "response"},
}
responseWidened := wireshape.Digest{
WireRevision: 2,
Entries: []wireshape.Entry{
{Schema: "SweepResult", Member: "tier", Type: "string", Required: true,
Enum: []string{"durable", "ephemeral", "wisps-plane"}},
},
Sides: map[string]string{"SweepResult": "response"},
}
t.Run("the identical widening on a response-side entry stays breaking", func(t *testing.T) {
cmp := wireshape.Compare(responseBase, responseWidened)
if len(cmp.Widened) != 0 {
t.Fatalf("Widened = %v, want none (a response-side widening is not additive)", cmp.Widened)
}
if len(cmp.Changed) != 1 {
t.Fatalf("Changed = %v, want exactly one entry", cmp.Changed)
}
if ok, _ := wireshape.SafeToWrite(responseBase, responseWidened); ok {
t.Fatal("response-side enum widening at the same revision was allowed")
}
bumped := wireshape.Digest{WireRevision: 3, Entries: responseWidened.Entries, Sides: responseWidened.Sides}
if ok, reason := wireshape.SafeToWrite(responseBase, bumped); !ok {
t.Fatalf("response-side enum widening with a bumped revision refused: %s", reason)
}
drift := goldenDrift(responseBase, responseWidened)
if drift == "" || !strings.Contains(drift, "changed without a wire_revision bump") {
t.Fatalf("goldenDrift = %q, want the ordinary non-additive instruction", drift)
}
})
t.Run("an enum narrowing on a request-only entry is still breaking", func(t *testing.T) {
narrowed := wireshape.Digest{
WireRevision: 2,
Entries: []wireshape.Entry{
{Schema: "SweepRequest", Member: "tier", Type: "string", Required: true,
Enum: []string{"durable"}},
},
Sides: map[string]string{"SweepRequest": "request"},
}
cmp := wireshape.Compare(requestBase, narrowed)
if len(cmp.Widened) != 0 {
t.Fatalf("Widened = %v, want none (narrowing is not a widening)", cmp.Widened)
}
if len(cmp.Changed) != 1 {
t.Fatalf("Changed = %v, want exactly one entry", cmp.Changed)
}
})
t.Run("going from no enum at all to a fixed enum on a request-only entry is not additive", func(t *testing.T) {
// Pinning case for review finding: widensAdditively required
// len(new.Enum) > len(old.Enum), which holds vacuously when the old
// side has no enum (a free string). That let a request-only member
// go from unconstrained to a fixed set at the same wire_revision —
// the opposite of widening, since the server now 400s a value an
// old client could send yesterday.
noEnumBase := wireshape.Digest{
WireRevision: 2,
Entries: []wireshape.Entry{
{Schema: "SweepRequest", Member: "tier", Type: "string", Required: true},
},
Sides: map[string]string{"SweepRequest": "request"},
}
cmp := wireshape.Compare(noEnumBase, requestWidened)
if len(cmp.Widened) != 0 {
t.Fatalf("Widened = %v, want none (no enum before is a new restriction, not a widening)", cmp.Widened)
}
if len(cmp.Changed) != 1 {
t.Fatalf("Changed = %v, want exactly one entry", cmp.Changed)
}
if ok, _ := wireshape.SafeToWrite(noEnumBase, requestWidened); ok {
t.Fatal("no-enum-to-enum tightening at the same revision was allowed")
}
bumped := wireshape.Digest{WireRevision: 3, Entries: requestWidened.Entries, Sides: requestWidened.Sides}
if ok, reason := wireshape.SafeToWrite(noEnumBase, bumped); !ok {
t.Fatalf("no-enum-to-enum tightening with a bumped revision refused: %s", reason)
}
})
}
// TestParameterMutationsAreCaught is the falsification for how Compare and
// SafeToWrite treat the parameter side of the digest (review: "the digest
// doesn't cover operation PARAMETERS ... so a type, enum, required, or

View file

@ -103,6 +103,7 @@ go_test(
"dispatch_test.go",
"divergence_citation_gate_test.go",
"divergence_test.go",
"expected_revision_contract_test.go",
"helpers_test.go",
"lifecycle_create_test.go",
"lifecycle_update_test.go",
@ -125,6 +126,7 @@ go_test(
"served_counter_test.go",
"served_detail_reads_test.go",
"served_dualrun_test.go",
"served_dualwrite_history_test.go",
"served_graph_aux_test.go",
"served_graph_counter_test.go",
"served_harness_test.go",

View file

@ -14,6 +14,8 @@ import (
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
@ -198,28 +200,150 @@ func TestSweepDoesNotWriteThroughTheCallersCutoff(t *testing.T) {
// is hand-written and a member the server grows would otherwise be dropped in
// silence — a result whose numbers are quietly wrong about what was erased.
func TestSweepResultCarriesEveryWireMember(t *testing.T) {
remaining := int64(13)
liveDependent := 14
w := &stubWire{swept: &apigen.SweepResult{
DryRun: true, Swept: 3, Dependencies: 4, Labels: 5, Events: 6,
Skipped: apigen.SweepSkips{
Pinned: 7, Referenced: 8, NotClosed: 9,
UnknownClosedAt: 10, ClosedAtOrAfterCutoff: 11, Unreadable: 12,
LiveDependent: &liveDependent,
},
ReferencedIds: &[]string{"bd-1"},
Remaining: &remaining,
}}
result, err := bulkSweeper(t, w).Sweep(t.Context(), issueops.SweepRequest{Tier: issueops.SweepEphemeral})
if err != nil {
t.Fatalf("Sweep(): %v", err)
}
// Remaining and LiveDependent are skipped: OSS's wire publishes no
// `remaining` or structural-dependent skip member for either to decode out
// of (W-SweepRequest.Limit, W-SweepRequest.ProtectLiveDependents refuse the
// request members that would produce them), so no wire body — fully
// populated or not — can ever make this projection set them.
assertEveryFieldPopulated(t, "SweepResult", reflect.ValueOf(result), "Remaining")
assertEveryFieldPopulated(t, "SweepSkips", reflect.ValueOf(result.Skipped), "LiveDependent")
assertEveryFieldPopulated(t, "SweepResult", reflect.ValueOf(result))
assertEveryFieldPopulated(t, "SweepSkips", reflect.ValueOf(result.Skipped))
if !reflect.DeepEqual(result.ReferencedIDs, []string{"bd-1"}) {
t.Errorf("ReferencedIDs = %v, want [bd-1]", result.ReferencedIDs)
}
if result.Remaining != 13 {
t.Errorf("Remaining = %d, want 13", result.Remaining)
}
if result.Skipped.LiveDependent != 14 {
t.Errorf("Skipped.LiveDependent = %d, want 14", result.Skipped.LiveDependent)
}
}
// TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem is the encoding half of
// the three S4 additions: tier "wisps-plane", protect_live_dependents and limit
// each reach the wire once the handshake advertises the matching token,
// mirroring TestCountScopeFieldsEncodeOntoTheQuery's idiom for a request body
// rather than a query.
func TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem(t *testing.T) {
served := &apigen.ContextResponse{Capabilities: []string{
wire.CapSweepWispsPlane, wire.CapSweepLiveDependents, wire.CapSweepLimit,
}}
t.Run("wisps-plane tier", func(t *testing.T) {
w := &stubWire{}
sweeper, err := New(testTarget(t), w, served).Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
if _, err := sweeper.Sweep(t.Context(), issueops.SweepRequest{Tier: issueops.SweepWispsPlane}); err != nil {
t.Fatalf("Sweep(): %v", err)
}
if w.lastSweep.Tier != apigen.WispsPlane {
t.Errorf("tier = %q, want %q", w.lastSweep.Tier, apigen.WispsPlane)
}
})
t.Run("protect_live_dependents", func(t *testing.T) {
w := &stubWire{}
sweeper, err := New(testTarget(t), w, served).Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
if _, err := sweeper.Sweep(t.Context(), issueops.SweepRequest{
Tier: issueops.SweepWispsPlane, ProtectLiveDependents: true,
}); err != nil {
t.Fatalf("Sweep(): %v", err)
}
if w.lastSweep.ProtectLiveDependents == nil || !*w.lastSweep.ProtectLiveDependents {
t.Errorf("protect_live_dependents = %v, want true", w.lastSweep.ProtectLiveDependents)
}
})
t.Run("limit", func(t *testing.T) {
w := &stubWire{}
sweeper, err := New(testTarget(t), w, served).Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
if _, err := sweeper.Sweep(t.Context(), issueops.SweepRequest{
Tier: issueops.SweepDurable, Limit: 5,
}); err != nil {
t.Fatalf("Sweep(): %v", err)
}
if w.lastSweep.Limit == nil || *w.lastSweep.Limit != 5 {
t.Errorf("limit = %v, want 5", w.lastSweep.Limit)
}
})
}
// TestSweepRefusesTheS4MembersWhenTheServerLacksTheCapability is the skew half:
// each of the three S4 additions refuses BEFORE dialing when the handshake does
// not advertise its token, mirroring
// TestCountScopeRefusesLocallyWhenTheServerLacksTheCapability.
func TestSweepRefusesTheS4MembersWhenTheServerLacksTheCapability(t *testing.T) {
masked := &apigen.ContextResponse{Capabilities: []string{"issues.sweep"}}
for _, tc := range []struct {
name string
req issueops.SweepRequest
cap string
}{
{"wisps-plane tier", issueops.SweepRequest{Tier: issueops.SweepWispsPlane}, wire.CapSweepWispsPlane},
{"protect_live_dependents", issueops.SweepRequest{Tier: issueops.SweepDurable, ProtectLiveDependents: true}, wire.CapSweepLiveDependents},
{"limit", issueops.SweepRequest{Tier: issueops.SweepDurable, Limit: 5}, wire.CapSweepLimit},
} {
t.Run(tc.name, func(t *testing.T) {
w := &stubWire{}
sweeper, err := New(testTarget(t), w, masked).Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
_, err = sweeper.Sweep(t.Context(), tc.req)
if err == nil {
t.Fatal("Sweep returned no error, want a pre-dial capability refusal")
}
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) {
t.Fatalf("errors.As to *storage.ErrUnsupported failed for %v", err)
}
if unsup.Capability != tc.cap {
t.Errorf("Capability = %q, want %q", unsup.Capability, tc.cap)
}
if unsup.Op != "Sweeper.Sweep" {
t.Errorf("Op = %q, want %q", unsup.Op, "Sweeper.Sweep")
}
if len(w.calls) != 0 {
t.Errorf("dialed %v, want none: a pre-dial refusal must never reach the wire", w.calls)
}
})
}
// The converse: a plain ephemeral/durable sweep with neither new boolean
// nor a limit dials normally against the same masked server — the gate
// guards the three additions, not the operation.
t.Run("no S4 member set dials normally", func(t *testing.T) {
w := &stubWire{}
sweeper, err := New(testTarget(t), w, masked).Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
if _, err := sweeper.Sweep(t.Context(), issueops.SweepRequest{Tier: issueops.SweepDurable}); err != nil {
t.Fatalf("Sweep(): %v", err)
}
if len(w.calls) != 1 {
t.Errorf("dialed %d times, want 1", len(w.calls))
}
})
}
// TestDeleteResultCarriesEveryWireMember is the same guard on the delete, whose

View file

@ -34,6 +34,7 @@ go_test(
"//:engdocs/design/http-divergence-ledger.md",
"//cmd/bd:go_srcs",
"//internal/httpapi/spec:openapi.v0.yaml",
"//internal/httpclient:go_srcs",
] + glob(["*.go"]),
embed = [":encode"],
deps = [

View file

@ -981,36 +981,22 @@ func writeSideRows() []Row {
PinnedBy: pinnedByS3Conformance,
},
{
// S3 reconciliation (2026-10): bd-enterprise's
// sweepIssues wire carried a structural-dependent protection
// alongside the referenced-citation one; OSS's apigen.SweepRequest
// publishes protect_referenced only. There is no
// protect_live_dependents member for this field to narrow onto, so
// sending `true` and having the client silently drop it would run
// an UNPROTECTED sweep while the caller believed the structural
// guard was active — the exact widening refuse-not-drop exists to
// stop, on the one operation this surface uses to delete rows.
ID: "W-SweepRequest.ProtectLiveDependents", Kind: KindRefuse,
ID: "W-SweepRequest.ProtectLiveDependents", Kind: KindRetired,
Type: tySweepRequest, Field: "ProtectLiveDependents",
What: "protecting live structural dependents during a sweep refuses",
Why: "sweepIssues publishes dry_run, tier, closed_before, pattern, protect_referenced and actor only; no protect_live_dependents member exists for this client to send, and the server has no stored-edge lookup to run on this client's behalf. `bd purge` from a local workspace still gets the protection; over http it must ask without it or not at all",
What: "protecting live structural dependents during a sweep used to refuse",
Why: "RETIRED by the S4 wire extension that sends it. The gap was always the DOCUMENT's rather than a decision: the local Sweeper role carries a structural-dependent protection alongside the referenced-citation one, and apigen.SweepRequest had no protect_live_dependents member for this client to narrow onto, so sending `true` and silently dropping it would have run an UNPROTECTED sweep while the caller believed the structural guard was active. " +
"The spec now publishes `protect_live_dependents` (and SweepSkips.live_dependent on the response) behind its own behavior-capability token, issues.sweep.liveDependents, because it is a parameter added to an operation that already shipped. The client sends it only once the handshake advertises the token and refuses locally, before the dial, when it does not — see refuseUnservedSweep (sweeper.go) and W-SweepRequest.Limit for the sibling member closed the same way",
SpecRow: "D8 refuse-not-drop",
PinnedBy: pinnedByS3Conformance,
PinnedBy: "TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem",
},
{
// Limit's absence is the same gap on the OTHER half of the request:
// bd-enterprise's wire bounded one sweep call and reported the
// remainder back; OSS's apigen.SweepRequest and SweepResult carry
// neither a limit member to send nor a remaining member to read one
// back from. A dropped Limit would run the UNBOUNDED sweep the
// caller asked to cap, in one transaction, which is the same
// widening the protection row above refuses rather than degrades.
ID: "W-SweepRequest.Limit", Kind: KindRefuse,
ID: "W-SweepRequest.Limit", Kind: KindRetired,
Type: tySweepRequest, Field: "Limit",
What: "bounding one sweep call and draining a backlog over several refuses",
Why: "sweepIssues publishes no limit member and SweepResult publishes no remaining member for a bounded caller to loop on; a non-zero Limit refuses before the dial rather than running the unbounded sweep silently. issueops.SweepResult.Remaining is therefore always zero from this client — not a dropped count, since nothing bounded the call that would have left one",
What: "bounding one sweep call and draining a backlog over several used to refuse",
Why: "RETIRED by the S4 wire extension that sends it (with W-SweepRequest.ProtectLiveDependents). The local Sweeper role bounds one sweep call and reports the remainder back; apigen.SweepRequest and SweepResult carried neither a limit member to send nor a remaining member to read one back from, so a dropped Limit would have run the UNBOUNDED sweep the caller asked to cap, in one transaction. " +
"The spec now publishes `limit` on the request and `remaining` on the response behind issues.sweep.limit. The client sends Limit only once the handshake advertises that token and refuses locally otherwise; issueops.SweepResult.Remaining now carries the server's count rather than always reading zero",
SpecRow: "D8 refuse-not-drop",
PinnedBy: pinnedByS3Conformance,
PinnedBy: "TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem",
},
}
}

View file

@ -0,0 +1,58 @@
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestExpectedRevisionContract wires the http leg into the R16/R17
// expected-revision contract, the same way dolt, embeddeddolt and uow do
// (see internal/storage/dolt/expected_revision_contract_test.go). Phase 0
// leaves every hook nil in every backend's fixture kit (architecture §12 of
// be-hs42e.1), so this client — which implements no whole-of-state
// expectedRevision CAS wire operation, and has none to implement until that
// phase ships one — is in exactly the same all-nil state every other leg
// already is. Said honestly: these ten entrypoints are COUNTED here, the
// hook is UNBUILT ON EVERY LEG (not just this one), and every case below
// SKIPS as a result (each Run* helper calls t.Skip when
// CompareAndSetVersion is nil) — this file exists so
// TestEveryLegWiresEveryRoleContract counts the http leg for these ten
// entrypoints, and so the cases start running for real the moment a
// CompareAndSetVersion wire operation exists for this client to bind here.
func TestExpectedRevisionContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.ExpectedRevisionFixture{IssuePrefix: "herev"}
t.Run("AcceptsAWriteNamingTheCurrentVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingTheCurrentVersion(t, ctx, fixture)
})
t.Run("AcceptsAWriteNamingNoVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingNoVersion(t, ctx, fixture)
})
t.Run("CoversFieldsOutsideAnyWatchedSubset", func(t *testing.T) {
conformance.RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionAddress", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionAddress(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionsChangeAttribution", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionsChangeAttribution(t, ctx, fixture)
})
t.Run("RefusalIsATypedOutcomeNotAGenericError", func(t *testing.T) {
conformance.RunRefusalIsATypedOutcomeNotAGenericError(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromAnAcceptedWrite", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromAnAcceptedWrite(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromNotFound", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromNotFound(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromValidationFailure", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromValidationFailure(t, ctx, fixture)
})
t.Run("RefusalNeverSilentlyPicksAWinner", func(t *testing.T) {
conformance.RunRefusalNeverSilentlyPicksAWinner(t, ctx, fixture)
})
}

View file

@ -304,8 +304,18 @@ func TestWriteRoleRefusalsMatchTheReadShape(t *testing.T) {
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
// Since S4 the wire carries limit, gated by issues.sweep.limit: a
// server that does not advertise it refuses pre-dial with a capability
// refusal, which classifies as *storage.ErrUnsupported naming the token
// (not an encoder refusal, so not *InexpressibleError).
_, err = sweeper.Sweep(ctx, issueops.SweepRequest{Tier: "ephemeral", Limit: 5})
assertUnsupported(t, err, "Sweeper.Sweep")
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) || unsup.Backend != Backend {
t.Fatalf("got %v, want *storage.ErrUnsupported for this backend", err)
}
if unsup.Capability != wire.CapSweepLimit {
t.Errorf("the refusal names capability %q, want %q", unsup.Capability, wire.CapSweepLimit)
}
if len(w.dispatched) != 0 {
t.Errorf("a refused sweep dialed %v", w.dispatched)
}

View file

@ -64,6 +64,17 @@ func newServedSweeperFixture(t *testing.T, prefix string) conformance.SweeperFix
// served store reaches the shape through the embedded database behind
// the server and then exercises the sweep over the wire as usual.
Exec: env.exec,
AddDependencies: func(ctx context.Context, req issueops.AddDependenciesRequest) error {
// Through the DependencyEditor ROLE, which routes each edge to its
// source plane's dependency table itself — the same seam
// dolt/uow/embeddeddolt's own sweeper fixtures use.
editor, err := env.subject.DependencyEditor()
if err != nil {
return err
}
_, err = editor.AddDependencies(ctx, req)
return err
},
}
}
@ -119,6 +130,36 @@ func TestServedSweeperDoesNotMutateTheCallerRequest(t *testing.T) {
conformance.RunSweeperDoesNotMutateTheCallerRequest(t, t.Context(), newServedSweeperFixture(t, "hs10"))
}
// The S4 wire extension: tier: "wisps-plane", ProtectLiveDependents and Limit
// all now have a round trip (internal/httpapi/sweep.go, internal/httpclient/
// sweeper.go), each behind its own capability token the served harness's
// in-process handshake always advertises, so these six run for real rather
// than parking.
func TestServedSweeperWispsPlaneClearsTheWholeWispsTable(t *testing.T) {
conformance.RunSweeperWispsPlaneClearsTheWholeWispsTable(t, t.Context(), newServedSweeperFixture(t, "hs13"))
}
func TestServedSweeperWispsPlaneRequiresAFilter(t *testing.T) {
conformance.RunSweeperWispsPlaneRequiresAFilter(t, t.Context(), newServedSweeperFixture(t, "hs14"))
}
func TestServedSweeperProtectsLiveDependents(t *testing.T) {
conformance.RunSweeperProtectsLiveDependents(t, t.Context(), newServedSweeperFixture(t, "hs15"))
}
func TestServedSweeperProtectsTransitiveLiveDependents(t *testing.T) {
conformance.RunSweeperProtectsTransitiveLiveDependents(t, t.Context(), newServedSweeperFixture(t, "hs16"))
}
func TestServedSweeperProtectsLiveDependentsAcrossPlanes(t *testing.T) {
conformance.RunSweeperProtectsLiveDependentsAcrossPlanes(t, t.Context(), newServedSweeperFixture(t, "hs17"))
}
func TestServedSweeperLimitTakesTheOldestClosedFirst(t *testing.T) {
conformance.RunSweeperLimitTakesTheOldestClosedFirst(t, t.Context(), newServedSweeperFixture(t, "hs18"))
}
// ── Deleter ─────────────────────────────────────────────────────────────────
func newServedDeleterFixture(t *testing.T, prefix string) conformance.DeleterFixture {

View file

@ -431,6 +431,33 @@ func TestServedLifecycleUpdatePreservesTheCreationStamp(t *testing.T) {
conformance.RunLifecycleUpdatePreservesTheCreationStamp(t, t.Context(), newServedUpdateFixture(t, "hlcs"))
}
// Two of the four ExpectedVersion concurrency races, run for real over this
// wire: N goroutines dial N concurrent HTTP requests against the same
// in-process server, racing the same --if-revision token.
// precondition_failed decodes to storage.ErrVersionMismatch
// (internal/httpclient/wire/problem.go), the same sentinel
// storage.ErrVersionMismatch aliases to (internal/storage/storage.go), so
// errors.Is resolves identically whether the loser learned it locally or over
// http.
//
// The other two of the four race IssuePatch.SpecID/.AwaitID/.Owner updates
// against each other (RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency,
// RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency),
// and stay off this leg: those three fields are refused on updateIssue by
// name (W-IssuePatch.SpecID, W-IssuePatch.AwaitID, W-IssuePatch.Owner,
// internal/httpclient/encode/ledger.go), a pre-existing D8 refuse-not-drop
// decision this slice does not reopen, not a race outcome the wire could
// report correctly — see issuePatchFieldsNotOnUpdateWireWaiverReason
// (internal/storage/leg_contract_wiring_test.go).
func TestServedLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t *testing.T) {
conformance.RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t, t.Context(), newServedUpdateFixture(t, "hlvu"))
}
func TestServedLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency(t *testing.T) {
conformance.RunLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency(t, t.Context(), newServedUpdateFixture(t, "hlvc"))
}
// The THREE claim-and-override cases below RUN, and left the park population
// together, with the #7247 review port: `claim`, `force_assignee_transfer` and
// `force_close_policy` are top-level members of updateIssue's body (the first

View file

@ -0,0 +1,147 @@
//go:build cgo
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The DualWriteFixture contracts, run through client → in-process bd serve →
// reference store, the same shape as the other served fixtures in this
// package.
//
// Mutate and MutateAsNoOp are bound to the CLIENT'S Lifecycle role (Create and
// Update over the wire), not to the reference store: the contract is a claim
// about what a client-driven mutation causes the SERVER to record, and a
// fixture that seeded through the reference store would only prove the
// storage engine versions its own direct writes, which the dolt/embeddeddolt/
// uow legs already cover. CurrentRevision, VersionRowCount and
// LatestVersionAttribution read the REFERENCE store's raw columns, the same
// as every other served fixture's postcondition hooks (served_issue_operations_test.go's
// doc comment states the rule this follows: a postcondition reads the row
// directly, never through a role, so a column the read side does not project
// still gets checked).
//
// Each fixture gets its OWN env (newServedEnv), never the shared
// composition: storage.VersionedHistoryConfigurer is a knob on the reference
// store instance the server's roles are bound to, and flipping it on a store
// any other test shares would start minting issue_versions rows underneath
// cases that never asked for them.
func newServedDualWriteFixture(t *testing.T, prefix string, enabled bool) conformance.DualWriteFixture {
t.Helper()
env := newServedEnv(t, prefix)
configurer, ok := any(env.reference).(storage.VersionedHistoryConfigurer)
if !ok {
t.Fatalf("%T does not implement storage.VersionedHistoryConfigurer", env.reference)
}
configurer.SetVersionedHistoryEnabled(enabled)
lifecycle, err := env.subject.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
return conformance.DualWriteFixture{
IssuePrefix: env.prefix,
Mutate: func(ctx context.Context, id string) error {
_, err := lifecycle.Create(ctx, issueops.CreateRequest{
Actor: "writer",
ForceIDPrefix: true,
Issue: &types.Issue{
ID: id, Title: "t-" + id, Status: types.StatusOpen,
Priority: 1, IssueType: types.TypeTask,
},
})
return err
},
// Re-sets Title to the exact value Mutate already gave it, so
// issueops.DiscardNoopIssueUpdates discards it before it ever reaches
// RecordVersionInTx — the same shape the uow leg's own
// newUOWDualWriteFixture uses for the identical reason.
MutateAsNoOp: func(ctx context.Context, id string) error {
_, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "writer",
IssueID: id,
Patch: issueops.IssuePatch{Title: set("t-" + id)},
})
return err
},
CurrentRevision: func(ctx context.Context, id string) (int64, error) {
var revision int64
err := env.queryScalar(ctx, "SELECT current_revision FROM issues WHERE id = ?", []any{id}, &revision)
return revision, err
},
VersionRowCount: func(ctx context.Context, id string) (int, error) {
var count int
err := env.queryScalar(ctx, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", []any{id}, &count)
return count, err
},
LatestVersionAttribution: func(ctx context.Context, id string) (actor, agent, message string, err error) {
err = env.queryScalar(ctx, `
SELECT COALESCE(change_actor, ''), COALESCE(change_agent, ''), COALESCE(change_message, '')
FROM issue_versions
WHERE issue_id = ?
ORDER BY revision DESC
LIMIT 1`, []any{id}, &actor, &agent, &message)
return actor, agent, message, err
},
}
}
func TestServedDualWriteContract(t *testing.T) {
ctx := t.Context()
fixture := newServedDualWriteFixture(t, "hdw", true)
t.Run("MintsOneVersionRowPerAcceptedMutation", func(t *testing.T) {
conformance.RunDualWriteMintsOneVersionRowPerAcceptedMutation(t, ctx, fixture)
})
t.Run("NoOpMutationMintsNoRow", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationMintsNoRow(t, ctx, fixture)
})
t.Run("AttributionIsRecordedWithTheMutation", func(t *testing.T) {
conformance.RunDualWriteAttributionIsRecordedWithTheMutation(t, ctx, fixture)
// The shared contract above only asserts change_actor is non-empty,
// since each leg's Mutate closure supplies a different literal. This
// fixture's Mutate always sends Actor: "writer" (see
// newServedDualWriteFixture below), so the http leg can assert the
// exact value rather than merely "something was recorded".
id := fixture.IssuePrefix + "-attribution-exact"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s: %v", id, err)
}
actor, _, _, err := fixture.LatestVersionAttribution(ctx, id)
if err != nil {
t.Fatalf("reading attribution for %s: %v", id, err)
}
if actor != "writer" {
t.Errorf("change_actor = %q, want exactly %q: this fixture's Mutate always sends Actor: %q", actor, "writer", "writer")
}
})
t.Run("CurrentRevisionMatchesTheNewVersionRow", func(t *testing.T) {
conformance.RunDualWriteCurrentRevisionMatchesTheNewVersionRow(t, ctx, fixture)
})
t.Run("NoOpMutationLeavesThePriorVersionRowUnperturbed", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationLeavesThePriorVersionRowUnperturbed(t, ctx, fixture)
})
}
// TestServedDualWriteContractFlagOff runs FR-7 against an env whose reference
// store has the flag OFF from the start — its own env, not the one above, so
// "flag off" means what FR-7 promises rather than "not yet turned on this
// session".
func TestServedDualWriteContractFlagOff(t *testing.T) {
ctx := t.Context()
fixture := newServedDualWriteFixture(t, "hdwoff", false)
t.Run("FlagOffProducesNoVersionRows", func(t *testing.T) {
conformance.RunDualWriteFlagOffProducesNoVersionRows(t, ctx, fixture)
})
}

View file

@ -4,25 +4,28 @@ package httpclient
import (
"context"
"slices"
"strings"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/issueops"
)
// httpSweeper serves issueops.Sweeper from the sweepIssues custom method
// (design D8 row 12) — the capability behind `bd purge` and `bd prune`.
//
// The mapping is NOT total, unlike bd-enterprise's: OSS's apigen.SweepRequest
// publishes tier, closed_before, pattern, protect_referenced, dry_run and
// actor, with no member for ProtectLiveDependents or Limit, and
// apigen.SweepResult carries no remaining member for SweepResult.Remaining to
// decode out of. Both refuse before the dial (W-SweepRequest.ProtectLiveDependents,
// W-SweepRequest.Limit) rather than silently running an unprotected or
// unbounded sweep, so SweepResult.Remaining is always zero from this client —
// never a dropped count, since a Limit refuses before anything could be left
// over to report.
// S4 closed three gaps this client had against the local Sweeper role: the
// wire now carries `tier: "wisps-plane"`, `protect_live_dependents` and
// `limit` on the
// request, and `skipped.live_dependent`/`remaining` on the response — each
// behind its own behavior-capability token (CapSweepWispsPlane,
// CapSweepLiveDependents, CapSweepLimit), since each is a parameter added to
// an operation that already shipped. refuseUnservedSweep checks all three
// before the dial, exactly as counter.go's refuseUnservedScope does for
// Count's scope fields: a caller asking for something an older server
// predates learns that LOCALLY, never after a round trip that would 400
// anyway, and never by way of a silently unprotected or unbounded sweep.
//
// WHAT IS NOT DECIDED HERE, deliberately: the require-a-filter gate, the glob's
// well-formedness and the tier's own predicate. All three are the ROLE's, they
@ -54,28 +57,30 @@ var _ issueops.Sweeper = (*httpSweeper)(nil)
// is the same failure class refuse-not-drop exists to stop, in the other
// direction.
func (s *httpSweeper) Sweep(ctx context.Context, req issueops.SweepRequest) (result issueops.SweepResult, err error) {
// Decorates ProtectLiveDependents/Limit's bare *encode.RefusedError into the
// same *InexpressibleError shape a read refusal gets, so errors.As(err,
// &unsupported) reaches *storage.ErrUnsupported here too (write-side parity,
// see (*Store).inexpressible's doc). A non-refusal error passes through
// unchanged.
// Write-side parity with reads: decorates a bare *encode.RefusedError into
// *InexpressibleError so errors.As(err, &unsupported) reaches
// *storage.ErrUnsupported, same as inexpressible does for a read role. No
// Sweep path raises one today — refuseUnservedSweep's capability errors
// pass through unchanged — so this is the write-role convention's single
// defer, kept so the next refuse() here is decorated without a new one.
defer func() { err = s.store.inexpressible("Sweeper.Sweep", err) }()
// Refuse-not-drop on the two members this wire has no place for. Both
// checks run before the tier is even validated, for the same reason every
// other raw refusal here precedes the dial: a caller who asked for a
// protection or a bound this client cannot honor must not learn that only
// after an unprotected or unbounded sweep already ran.
if req.ProtectLiveDependents {
return issueops.SweepResult{}, refuse(encode.OpSweepIssues, "W-SweepRequest.ProtectLiveDependents")
}
if req.Limit != 0 {
return issueops.SweepResult{}, refuse(encode.OpSweepIssues, "W-SweepRequest.Limit")
}
tier := apigen.SweepRequestTier(req.Tier)
if !tier.Valid() {
return issueops.SweepResult{}, invalid("sweep tier %q is not %q or %q",
string(req.Tier), apigen.Ephemeral, apigen.Durable)
return issueops.SweepResult{}, invalid("sweep tier %q is not %q, %q, or %q",
string(req.Tier), apigen.Ephemeral, apigen.Durable, apigen.WispsPlane)
}
// refuseUnservedSweep is the pre-dial half of the three Sweep behavior
// tokens (routes.go, beside CapIssuesSweepWispsPlane): a request naming
// the wisps-plane tier, or setting ProtectLiveDependents or Limit, asks
// for something only a server advertising the matching token answers, and
// an older server predating it answers with a guaranteed 400
// invalid_value/unknown_parameter. Checked BEFORE the dial so a caller
// never pays for a round trip that 400s anyway, and never silently gets an
// unprotected or unbounded sweep from a server too old to honor the
// request as asked.
if err := s.refuseUnservedSweep(ctx, tier, req); err != nil {
return issueops.SweepResult{}, err
}
body := apigen.SweepRequest{
@ -101,6 +106,13 @@ func (s *httpSweeper) Sweep(ctx context.Context, req issueops.SweepRequest) (res
cutoff := *req.ClosedBefore
body.ClosedBefore = &cutoff
}
if req.ProtectLiveDependents {
body.ProtectLiveDependents = &req.ProtectLiveDependents
}
if req.Limit != 0 {
limit := int64(req.Limit)
body.Limit = &limit
}
res, err := s.wire.SweepIssues(ctx, body)
if err != nil {
@ -109,6 +121,32 @@ func (s *httpSweeper) Sweep(ctx context.Context, req issueops.SweepRequest) (res
return sweepResult(res), nil
}
// refuseUnservedSweep checks each of the three S4 additions against the
// handshake snapshot, independently — a caller may ask for any subset of
// them, and an older server may serve none, some, or (not yet, but
// structurally possible) only some of the three. A request using none of
// them never consults the snapshot at all, the same short-circuit
// refuseUnservedScope uses for Count.
func (s *httpSweeper) refuseUnservedSweep(ctx context.Context, tier apigen.SweepRequestTier, req issueops.SweepRequest) error {
if tier != apigen.WispsPlane && !req.ProtectLiveDependents && req.Limit == 0 {
return nil
}
snap, err := s.store.snapshot(ctx)
if err != nil {
return err
}
if tier == apigen.WispsPlane && !slices.Contains(snap.Capabilities, wire.CapSweepWispsPlane) {
return s.store.unsupportedCapability("Sweeper.Sweep", wire.CapSweepWispsPlane)
}
if req.ProtectLiveDependents && !slices.Contains(snap.Capabilities, wire.CapSweepLiveDependents) {
return s.store.unsupportedCapability("Sweeper.Sweep", wire.CapSweepLiveDependents)
}
if req.Limit != 0 && !slices.Contains(snap.Capabilities, wire.CapSweepLimit) {
return s.store.unsupportedCapability("Sweeper.Sweep", wire.CapSweepLimit)
}
return nil
}
// sweepResult projects the wire's answer onto the role's.
//
// It is a field list rather than a cast because SweepResult is deliberately not
@ -132,6 +170,12 @@ func sweepResult(res *apigen.SweepResult) issueops.SweepResult {
Unreadable: res.Skipped.Unreadable,
},
}
if res.Skipped.LiveDependent != nil {
out.Skipped.LiveDependent = *res.Skipped.LiveDependent
}
if res.Remaining != nil {
out.Remaining = int(*res.Remaining)
}
if res.ReferencedIds != nil {
out.ReferencedIDs = append([]string(nil), *res.ReferencedIds...)
}

View file

@ -161,6 +161,40 @@ const CapCountScope = "issues.count.scope"
// token gates.
const CapBatchApplyLarge = "issues.batchApplyLarge"
// CapSweepWispsPlane is the behavior capability announcing that sweepIssues
// accepts `tier: "wisps-plane"` — a third tier, wider than ephemeral or
// durable, that clears the whole wisps table plus any durable bead with no
// history row — spelled exactly as httpapi's constant of the same name (held
// to it by TestTheProjectIdentityVocabularyMatchesTheServer). sweeper.go's
// tier mapping checks this token before mapping issueops.SweepWispsPlane onto
// the wire, refusing locally with a typed capability error rather than
// dialing a server that would answer the value with invalid_value. See
// W-SweepRequest.ProtectLiveDependents and W-SweepRequest.Limit (encode/
// ledger.go) for the sibling S4 members retired the same way; the tier value
// itself carries no ledger row because it widens an existing enum rather
// than adding a request member.
const CapSweepWispsPlane = "issues.sweep.wispsPlane"
// CapSweepLiveDependents is the behavior capability announcing that
// sweepIssues honors SweepRequest.protect_live_dependents and answers
// SweepSkips.live_dependent, spelled exactly as httpapi's constant of the
// same name (held to it by TestTheProjectIdentityVocabularyMatchesTheServer).
// sweeper.go reads this token before sending the field, refusing locally with
// a typed capability error rather than silently dropping the protection
// against an older server. encode/ledger.go's W-SweepRequest.ProtectLiveDependents
// row records the S4 closure of what used to be a permanent refusal.
const CapSweepLiveDependents = "issues.sweep.liveDependents"
// CapSweepLimit is the behavior capability announcing that sweepIssues honors
// SweepRequest.limit and answers SweepResult.remaining, spelled exactly as
// httpapi's constant of the same name (held to it by
// TestTheProjectIdentityVocabularyMatchesTheServer). sweeper.go reads this
// token before sending the field, refusing locally with a typed capability
// error rather than silently running an unbounded sweep against an older
// server. encode/ledger.go's W-SweepRequest.Limit row records the S4 closure
// of what used to be a permanent refusal.
const CapSweepLimit = "issues.sweep.limit"
// CapExternalDependencies is the CONDITIONAL behavior capability announcing
// that the ready, claim and close operations of this server apply bd's
// external-dependency policy themselves, spelled exactly as httpapi's constant
@ -193,7 +227,16 @@ const CapExternalDependencies = "policy.external_dependencies"
// (problem.go's WireRevisionUnsupportedError) instead of answering with a
// shape this build was never compiled to read. It doubles as the upper bound
// of the handshake gate below: nothing compiled against revision 2 can
// promise to decode revision 3.
// promise to decode a FUTURE, non-additive revision 3.
//
// S4 added SweepRequest.protect_live_dependents, SweepRequest.limit and a
// wisps-plane SweepRequest.tier value, none of which bumped
// CurrentWireRevision (internal/httpapi/wireshape's drift gate tracks a
// request-only member's enum widening as additive, not a wire break — see
// that package's Sides/widensAdditively), so this constant stays 2 too: a
// revision-2 client (this one, and the S2 client already on main) must keep
// talking to a revision-2 server rather than refusing it over a bump nothing
// here required.
const ClientWireRevision = 2
// ClientMinWireRevision is the oldest SERVER-reported wire_revision this
@ -289,7 +332,10 @@ func (e *WireRevisionSkewError) Unwrap() error { return ErrWireRevisionSkew }
// union(opCapability tokens, this) set-equal with httpapi.Capabilities(), which is
// what makes the server change and this client change land together: the parity
// test goes red the moment one ships without the other.
var behaviorCapabilities = []string{CapProjectEnforce, CapBatchApplyLarge, CapListSort, CapCountScope}
var behaviorCapabilities = []string{
CapProjectEnforce, CapBatchApplyLarge, CapListSort, CapCountScope,
CapSweepWispsPlane, CapSweepLiveDependents, CapSweepLimit,
}
// CapabilityFor reports the capability token gating op, and whether op is on
// this client's map at all. An operation with no token — liveness, the

View file

@ -149,6 +149,15 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
if CapBatchApplyLarge != httpapi.CapBatchApplyLarge {
t.Errorf("CapBatchApplyLarge = %q, server says %q", CapBatchApplyLarge, httpapi.CapBatchApplyLarge)
}
if CapSweepWispsPlane != httpapi.CapIssuesSweepWispsPlane {
t.Errorf("CapSweepWispsPlane = %q, server says %q", CapSweepWispsPlane, httpapi.CapIssuesSweepWispsPlane)
}
if CapSweepLiveDependents != httpapi.CapIssuesSweepLiveDependents {
t.Errorf("CapSweepLiveDependents = %q, server says %q", CapSweepLiveDependents, httpapi.CapIssuesSweepLiveDependents)
}
if CapSweepLimit != httpapi.CapIssuesSweepLimit {
t.Errorf("CapSweepLimit = %q, server says %q", CapSweepLimit, httpapi.CapIssuesSweepLimit)
}
if ReasonProjectMismatch != string(httpapi.ReasonProjectMismatch) {
t.Errorf("ReasonProjectMismatch = %q, server says %q", ReasonProjectMismatch, httpapi.ReasonProjectMismatch)
}
@ -183,8 +192,12 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
// literal is spelled out member by member rather than compared against the
// server's own slice: a mirror checked against the thing it mirrors passes
// however both of them move.
if !slices.Equal(behaviorCapabilities, []string{httpapi.CapProjectEnforce, httpapi.CapBatchApplyLarge, httpapi.CapIssuesListSort, httpapi.CapIssuesCountScope}) {
t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort and issues.count.scope tokens", behaviorCapabilities)
if !slices.Equal(behaviorCapabilities, []string{
httpapi.CapProjectEnforce, httpapi.CapBatchApplyLarge, httpapi.CapIssuesListSort, httpapi.CapIssuesCountScope,
httpapi.CapIssuesSweepWispsPlane, httpapi.CapIssuesSweepLiveDependents, httpapi.CapIssuesSweepLimit,
}) {
t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort, "+
"issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents and issues.sweep.limit tokens", behaviorCapabilities)
}
}

View file

@ -373,21 +373,23 @@ func writeShapes() []writeShape {
},
},
{
// NOT total, unlike bd-enterprise's: OSS's apigen.SweepRequest has
// no member for ProtectLiveDependents or Limit, so both are absent
// from carried below and the source -> wire arm obliges the two
// W-SweepRequest rows (W-SweepRequest.ProtectLiveDependents,
// W-SweepRequest.Limit) rather than a member.
// S4 extended the sweep carriage: apigen.SweepRequest now
// publishes protect_live_dependents and limit too, each carried
// by the role field of the same name (behind
// CapSweepLiveDependents and CapSweepLimit respectively —
// see sweeper.go's refuseUnservedSweep).
name: "sweepIssues",
source: reflect.TypeOf(issueops.SweepRequest{}),
body: reflect.TypeOf(apigen.SweepRequest{}),
carried: map[string]carriage{
"Actor": member("actor"),
"Tier": member("tier"),
"ClosedBefore": member("closed_before"),
"IDPattern": member("pattern"),
"ProtectReferenced": member("protect_referenced"),
"DryRun": member("dry_run"),
"Actor": member("actor"),
"Tier": member("tier"),
"ClosedBefore": member("closed_before"),
"IDPattern": member("pattern"),
"ProtectReferenced": member("protect_referenced"),
"DryRun": member("dry_run"),
"ProtectLiveDependents": member("protect_live_dependents"),
"Limit": member("limit"),
},
},
{

View file

@ -50,25 +50,9 @@ func init() {
registerContractLeg(contractLeg{name: "embeddeddolt", wiringRoot: "internal/storage/embeddeddolt"})
registerContractLeg(contractLeg{name: "uow", wiringRoot: "internal/storage/uow"})
registerContractLeg(contractLeg{
name: "http",
wiringRoot: "internal/httpclient",
adopting: "S3 wires every read role (IssueReader, Counter, ReadyCounter, GraphCounter, EdgeReader, " +
"Relations, BlockingAnnotator, TreeWalker, CycleDetector, Querier, StatsReporter, WorkspaceConfig, " +
"Memories, Journal minus watch) plus MetadataCAS and DependencyEditor in full; the HTTP leg's own " +
"CycleDetector.IncludeTracks gap, the nine Bootstrapper cases " +
"(internal/httpclient/accessors.go names Bootstrapper PERMANENTLY UNSERVABLE — no wire operation " +
"and none coming — see bootstrapperPermanentlyUnservableWaiverReason), the four Importer cases " +
"(uow is Importer's one accessor, same as the other two legs), and the twenty-two " +
"RetentionFixture/EpochFixture/CrossRecordInvariantFixture cases (raw storage bookkeeping with no " +
"publicops role behind them — see retentionEpochNoRoleWaiverReason and " +
"crossRecordInvariantNoRoleWaiverReason) are all named waivers, not part of this ceiling. What is " +
"still counted here is write-role and internal-plumbing work S4 and later slices wire and ratchet " +
"down one tranche at a time: lifecycle writes (IssueOperationsUpdate, LifecycleUpdate), " +
"DualWrite's Phase-2 history mechanism, Sweeper, VersionReconciler, InitVerifier, and " +
"ExpectedRevision/Refusal. VersionReconciler and InitVerifier are named PERMANENTLY UNSERVABLE by " +
"the same accessors.go comment that covers Bootstrapper, but moving them to a named waiver is out " +
"of scope for the change that lowered this ceiling to 42 and is left for their own reviewed change",
adoptionCeiling: 42,
name: "http",
wiringRoot: "internal/httpclient",
adoptionCeiling: 0,
})
}

View file

@ -99,6 +99,27 @@ func init() {
"RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS": crossRecordInvariantNoRoleWaiverReason,
"RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS": crossRecordInvariantNoRoleWaiverReason,
"RunStoreInvariantTransactionScopesExactlyTheSpanningRecords": crossRecordInvariantNoRoleWaiverReason,
"RunVersionReconcilerAdvancesBothMarkersOnAnUpgrade": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerCatchesUpToTheHighWaterMark": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerLeavesTheMarkersStandingWhenItCannotComplete": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerRecordsAWorkspaceWithNoMarkers": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerRecordsNoHistory": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerRefusesADowngradeWithoutAnError": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerRefusesAVersionBelowTheHighWaterMark": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerRefusesAnEmptyVersion": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunVersionReconcilerTreatsTheSameVersionAsANoOp": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunInitVerifierReportsAFailedReadAsAnError": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunInitVerifierReportsAPartialIdentityAsItStands": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunInitVerifierWritesNothing": versionReconcilerInitVerifierPermanentlyUnservableWaiverReason,
"RunIssueOperationsUpdateClosedFieldsMatchClose": issueOperationsUpdateRawSeamWaiverReason,
"RunIssueOperationsUpdateRawMetadataTakesTheFunnelsValueShapes": issueOperationsUpdateRawSeamWaiverReason,
"RunIssueOperationsUpdateStampsStartedAtOnceOnTheFirstInProgress": issueOperationsUpdateRawSeamWaiverReason,
"RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency": issuePatchFieldsNotOnUpdateWireWaiverReason,
"RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency": issuePatchFieldsNotOnUpdateWireWaiverReason,
})
}
@ -230,6 +251,84 @@ const stagingWaiverReason = "the unit-of-work provider commits every unit of wor
"caller-held working set to stage into and no Commit hook to close one; these two cases assert what a " +
"create sweeps into a commit the caller opened"
// versionReconcilerInitVerifierPermanentlyUnservableWaiverReason covers the
// thirteen VersionReconciler and InitVerifier contracts: PERMANENTLY
// unservable over http, not merely unwired yet.
//
// internal/httpclient/accessors.go names VersionReconciler and InitVerifier,
// alongside Bootstrapper, as the three accessors still on the generated
// refusing shell for one reason: "PERMANENTLY UNSERVABLE — no wire operation
// and none coming." Both share Bootstrapper's own fate and (InitVerifier
// shares BootstrapperFixture outright) the same cause: `bd init`'s substrate
// identification and the schema-version reconciliation it drives both run
// entirely client-side, against the on-disk substrate a server-mediated
// caller never touches directly, before or instead of any server existing to
// dial. There is no v0 operation for an http accessor to bind to and none is
// coming. This waiver was left out of the change that added
// bootstrapperPermanentlyUnservableWaiverReason (that change's own comment
// says so) and is added by this one.
const versionReconcilerInitVerifierPermanentlyUnservableWaiverReason = "internal/httpclient/accessors.go names " +
"VersionReconciler and InitVerifier PERMANENTLY UNSERVABLE over http, the same fate as Bootstrapper — no " +
"wire operation and none coming — because both run entirely client-side against the on-disk substrate " +
"(schema-version reconciliation and `bd init`'s own identity read) before or instead of any server existing " +
"to dial"
// issueOperationsUpdateRawSeamWaiverReason covers the three
// IssueOperationsStagingFixture cases whose SUBJECT is the untyped UpdateRaw
// funnel itself, not merely a fixture that seeds through it.
//
// storage.UpdateIssue is on this client's unsupported allowlist by design
// (D8: re-routing a raw front door would put a second spelling of the edit
// beside the role's), so served_issue_operations_test.go binds UpdateRaw only
// to the REFERENCE store's own untyped funnel (env.reference.UpdateIssue),
// never to the client — see that file's own doc comment. That binding is
// sound for every case actually wired there because none of them takes the
// funnel AS ITS SUBJECT; these three do (RunIssueOperationsUpdateClosedFieldsMatchClose
// drives a reopen/reclose through it, RunIssueOperationsUpdateStampsStartedAtOnceOnTheFirstInProgress
// and RunIssueOperationsUpdateRawMetadataTakesTheFunnelsValueShapes assert
// what it writes). Wiring them against the reference store's funnel would
// assert a property of the store the server happens to share a process with,
// never of the client under test — the same kind of empty assertion binding
// UpdateRaw to the client would be in the other direction. There is no
// client-side UpdateRaw to bind instead: that is D8's allowlist decision, not
// a gap.
const issueOperationsUpdateRawSeamWaiverReason = "these three cases take the untyped UpdateRaw funnel itself as " +
"their subject; storage.UpdateIssue is on this client's unsupported allowlist by design (D8), so there is no " +
"client-side UpdateRaw to bind, and binding the reference store's own funnel instead (as this leg's other " +
"IssueOperationsStagingFixture cases do, to SEED preconditions) would assert a property of the store the " +
"server happens to share a process with, never of the client under test"
// issuePatchFieldsNotOnUpdateWireWaiverReason covers the two
// LifecycleUpdateFixture concurrency cases whose racers patch
// IssuePatch.SpecID, .AwaitID, and/or .Owner against updateIssue.
//
// THIS IS PENDING, NOT PERMANENT: it is unbuilt work waiting on a wire
// change, not a boundary this leg can never cross. S4 wired the other two
// ExpectedVersion concurrency races (the plain Update race over
// Priority/Notes, and the Close race) against the real served HTTP harness,
// and both pass: precondition_failed decodes to storage.ErrVersionMismatch
// exactly as the local legs report it. These two cases cannot follow
// because SOME of their racers patch fields updateIssue refuses outright
// rather than ever sending — not a race outcome, a refusal before any
// request leaves the client. internal/httpclient/encode/ledger.go already
// names this gap per field (W-IssuePatch.SpecID, W-IssuePatch.AwaitID,
// W-IssuePatch.Owner, D8 refuse-not-drop): neither IssuePatchBody nor
// ApplyPatchBody publishes spec_id or await_id at all, and Owner is excluded
// from IssuePatchBody specifically (ApplyPatchBody — issues:batchApply's body
// — does carry it, which is a different operation from updateIssue). Closing
// this gap means publishing those fields on IssuePatchBody, a wire change to
// the write role itself, not a client-side wiring exercise — tracked as a
// follow-up slice, S4b: publish owner/spec_id/await_id on the wire. Until
// S4b lands, these two contracts stay off this leg rather than asserting a
// race outcome against a request three of its own racers never send.
const issuePatchFieldsNotOnUpdateWireWaiverReason = "PENDING, not permanent (tracked as S4b: publish " +
"owner/spec_id/await_id on the wire): two of the four ExpectedVersion concurrency contracts race " +
"IssuePatch.SpecID/.AwaitID/.Owner edits against updateIssue, and those three fields are refused outright by " +
"IssuePatchBody (W-IssuePatch.SpecID, W-IssuePatch.AwaitID, W-IssuePatch.Owner in " +
"internal/httpclient/encode/ledger.go, D8 refuse-not-drop) rather than ever reaching the server, so the race " +
"never happens over this wire; closing the gap means publishing those fields on IssuePatchBody, which is a " +
"wire change to the write role (S4b), not something this leg's test wiring can bind around today"
// TestEveryLegWiresEveryRoleContract fails when a backend leg skips a role
// contract the conformance package exports.
//

View file

@ -1360,11 +1360,29 @@ func RevisionToken(v int64) string {
// ParseRevisionToken reads a wire revision token back to the internal int64.
//
// It accepts exactly what RevisionToken emits. A caller must echo the token a
// response carried rather than compose one, so anything else is a client that
// invented a value, and reporting that as a parse failure is more useful than
// guessing at it.
// It accepts exactly what RevisionToken emits — the exact inverse of
// strconv.FormatInt — and nothing strconv.ParseInt alone would additionally
// tolerate: no leading "+" (FormatInt never emits one), no leading zero on
// any digit string longer than one character (FormatInt never pads "7" out
// to "007", positive or negative), and never "-0" (FormatInt(0, 10) is "0",
// never "-0"). A caller must echo the token a response carried rather than
// compose one, so anything else is a client that invented a value, and
// reporting that as a parse failure is more useful than guessing at it.
func ParseRevisionToken(s string) (int64, error) {
if strings.HasPrefix(s, "+") {
return 0, fmt.Errorf("revision token %q: leading \"+\" is not a token RevisionToken ever emits", s)
}
digits := s
negative := strings.HasPrefix(s, "-")
if negative {
digits = s[1:]
}
if negative && digits == "0" {
return 0, fmt.Errorf("revision token %q: \"-0\" is not a token RevisionToken ever emits", s)
}
if len(digits) > 1 && digits[0] == '0' {
return 0, fmt.Errorf("revision token %q: a leading zero is not a token RevisionToken ever emits", s)
}
return strconv.ParseInt(s, 10, 64)
}

View file

@ -1155,6 +1155,35 @@ func TestRevisionTokenSurvivesAJavaScriptRealisticParse(t *testing.T) {
}
}
// TestParseRevisionTokenRejectsMalformedTokens pins that the string<->int64
// boundary is strict in both directions: ParseRevisionToken accepts exactly
// the decimal integer spelling RevisionToken emits (plain digits, an optional
// leading "-", no fractional part, no exponent, no surrounding whitespace, no
// value outside int64) and refuses everything else rather than guessing —
// the same "a token it cannot read is a server this client cannot follow"
// posture ParseRevisionToken's own doc comment describes, now pinned against
// the inputs a float-typed or lenient parser would have let through.
//
// "007" and "-0" pin the exact-inverse-of-FormatInt rule specifically:
// FormatInt never pads a digit string with a leading zero (so "007" is not a
// token any revision ever produced, even though strconv.ParseInt alone would
// accept it as 7), and FormatInt(0, 10) is always "0", never "-0".
func TestParseRevisionTokenRejectsMalformedTokens(t *testing.T) {
for _, token := range []string{
"", "1.0", "1.5", "1e10", "1e0", "+1", " 1", "1 ", "0x1", "abc",
"9223372036854775808", // math.MaxInt64 + 1, one past the boundary
"-9223372036854775809", // math.MinInt64 - 1, one past the boundary
"NaN", "Infinity", "1", // fullwidth digit, not ASCII
"007", // leading zero FormatInt never pads in
"-007", // leading zero on the negative digit run
"-0", // FormatInt(0, 10) is "0", never "-0"
} {
if got, err := ParseRevisionToken(token); err == nil {
t.Errorf("ParseRevisionToken(%q) = %d, nil, want an error", token, got)
}
}
}
func TestReclaimedLeaseJSONSerialization(t *testing.T) {
b, err := json.Marshal(ReclaimedLease{ID: "bd-1", PreviousOwner: "worker-a"})
if err != nil {