feat(httpclient): OSS HTTP client store and roles + a served http conformance leg (contributed from bd-enterprise under MIT) (#7247)

* feat(httpclient): lift the HTTP client store and roles from bd-enterprise (MIT contribution)

Contributed by gascity from bd-enterprise (github.com/gascity/bd-enterprise,
internal/enterprise/httpstore @ 49d1df2f6) to OSS beads under the MIT
license, with the owner's explicit approval. Every lifted file carries a
provenance header naming its source path.

Lifted into internal/httpclient: the Store (DoltStorage over the wire), the
dial/register glue, the read roles (reader, querier, counters, edges,
relations, graph, tree, cycles, stats, config, memories, journal), the write
roles (lifecycle, claimer, releaser, deleter, dependency editor, metadata
CAS, commenter, batch closer/creator/applier, ready claimer, sweeper), and
their tests. The store transport seam (WireClient/WireDialer) and the
store-dependent tests deferred from the S2 lift are restored here.

Not lifted: the hosted gateway (httpgw/gwauth), box-login, storage profiles
and gasworks. dial.go only mentions the gateway in comments.

This commit is the mechanical lift and does NOT build yet. It references
enterprise-only APIs absent from OSS: issueops.ReadyLister,
journalops.Watcher, storage.ServerEnforcedPolicy, the
NonCommitGraphBackend/RemoteWorkspaceBackend markers, DoltStorage
differences, and BatchCloseRequest.claim_next. The following commits
reconcile it with OSS (S3/S4/S5).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(httpclient): reconcile the bd-enterprise lift's compile-time API surface against OSS

The mechanical lift (02a9dad17) carried several bd-enterprise-only shapes
that do not exist in OSS beads:

- ReadyLister, journalops.Watcher/StreamWire, and ServerEnforcedPolicy have
  no OSS wire counterpart; drop the role, its served/journal-watch tests,
  and the policy enforcement path entirely rather than leave dead code that
  cannot compile against OSS's apigen types.
- claim_hook_gate_test.go exercised a hook surface OSS does not publish.
- recordingWire/fakeWire no longer embed a StreamWire double now that no
  read role can reach a watch stream; testTarget's two conflicting
  package-scope declarations (store_test.go and helpers_test.go) are split
  apart as pinnedProjectTarget vs. the generic helper.
- unsupported_gen.go is regenerated from scratch against OSS's actual
  storage.DoltStorage via a new, from-scratch reflection-based generator
  (internal/storage/unsupportedgen) rather than hand-copied from
  bd-enterprise's generated output; completeness_test.go's
  legitimatelyUnsupported map grows the handful of OSS-only or
  previously-missed methods (AddRemoteWithRef, RenameLabel, etc.) this
  regeneration surfaces.
- write_ledger_test.go and the divergence ledger doc gain the
  force_notes_overwrite and claim pending rows OSS's apigen.UpdateRequest
  and SweepRequest actually carry, and drop the Remaining/LiveDependent
  assertions SweepResult/SweepSkips have no wire member to ever populate.

go build ./... and go vet ./... are clean after this change. No behavior
beyond the removed surfaces changes here; read-role and write-role
reconciliation land in follow-up commits.

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

* fix(httpclient): stop sending listIssues a reverse/sort vocabulary OSS does not publish

The bd-enterprise lift's sortedPage pushdown assumed GET /v0/beads/issues
(listIssues) shared the same sort vocabulary and a reverse parameter with
GET /v0/beads/issues:query (handleQueryIssues) -- a different operation.
OSS's openapi.v0.yaml publishes listIssues a CLOSED two-value `sort` enum
(created, priority; deliberately smaller than the nine values :query
takes) and no `reverse` parameter at all. Sending either would earn an
unknown-parameter or invalid_value refusal from the real server, not a
silently-wrong answer -- which is why this only surfaces against a served
backend, not a Go-side unit test of the request builder.

Add listSortPushdownEligible to gate the pushdown fast path to the two
keyset orders listIssues can actually page, unconditionally refusing any
reversed request (listIssues has no parameter that names a reversed
direction, so a reversed request of any order walks and sorts
client-side). Drop the unconditional `reverse` send from sortedPage.

served_list_test.go's three affected cases encoded the wrong,
enterprise-only wire shape (expecting reverse=false on the fallback path,
expecting a reversed order to push down with sort+reverse, and expecting a
Go-side/SQL-side mix in listIssues' sort enum); corrected to match OSS's
actual, provable wire contract rather than left red. list_sort_test.go's
publishedParamEnum helper now reads the OpenAPI document via the
go:embed'd spec.OpenAPIV0() accessor instead of a relative os.ReadFile, so
it no longer depends on the test's working directory (this also fixes the
same test failing under Bazel's sandbox, which does not expose arbitrary
relative-path files).

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

* fix(httpclient): reconcile write-role tests against OSS's BatchClose/Update shapes

OSS's apigen.BatchCloseRequest and BatchCloseResponse publish no
claim_next/claimed_next member at all (ledger row
W-CloseBatchRequest.ClaimNext) -- bd-enterprise's claim-folded-into-close
shape has no OSS wire counterpart. Replace the three tests that exercised
decoding a served claim (TestBatchCloseRefusesAServedClaimCarryingNoIssue,
TestBatchCloseRefusesAServedClaimTheRequestNeverEarned,
TestBatchCloseKeepsTheClaimItEarned) with
TestBatchCloseRefusesClaimNextUnconditionally, which pins the actual OSS
behavior: a CloseBatchRequest naming ClaimNext refuses before any dial, on
both the unserved and served legs, regardless of what a server would
otherwise answer. Drop the now-dead "claim-next" case and helper claim
variable from TestBatchCloseServesTheSingleItemShapeAndRefusesTheRest.

Also:
- Add the ForceNotesOverwrite case to
  TestUpdateRefusesEveryMemberTheWireExcludes's hand-maintained member
  map -- a ledgered-pending UpdateRequest member (see
  W-UpdateRequest.ForceNotesOverwrite) the lift's test left uncovered.
- Remove write_roles_test.go's duplicate `ptr[T]` generic helper, which
  redeclared the one already in helpers_test.go and never compiled.

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

* test(conformance): pin post-write RowVersion propagation across Update/Close/Reopen

types.Issue.RowVersion is json:"-", so an implementation that forgot to
populate it on the way back from storage would still compile and still
pass every existing content assertion in lifecycle_close_reopen_contract.go
-- none of them read RowVersion. Add
RunLifecycleResultsCarryThePostWriteRowVersion, which chains each write's
result token into the next write's ExpectedVersion (Update -> Close ->
Reopen) with no intervening read, so a dropped or stale token fails closed
on the next write's optimistic-concurrency guard rather than passing
silently.

Register it in role_bundle_cases.go's roleContractCases dispatch table at
its declaration-order position -- TestRoleContractCasesCoverEveryContractCase
was failing because the function existed with no dispatcher entry.

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

* chore(bazel): sync BUILD files via gazelle for the S3 reconciliation

bazel run //:gazelle after the compile/read-role/write-role reconciliation
commits:

- internal/httpclient/BUILD.bazel: regenerate srcs/deps for the files
  added, removed and newly imported above (drops the deleted
  policy/journal-watch/readylister files, adds the spec dep for
  list_sort_test.go's embedded OpenAPI read). Manually add
  `data = glob(["*.go"])` to the go_test rule, matching the idiom already
  used by //internal/httpclient/encode: completeness_test.go and
  divergence_citation_gate_test.go read their own package's .go sources at
  runtime (a regex scan of unsupported_gen.go and an AST walk of the
  package directory), and Bazel's go_test sandbox only copies in files a
  rule declares as `data` -- `srcs` are compiled away, not left readable.
  A `# keep` directive protects the attribute across future gazelle runs
  (confirmed gazelle does not manage `data` on this rule).
- internal/storage/BUILD.bazel,
  internal/storage/unsupportedgen/BUILD.bazel: pick up the new
  from-scratch unsupportedgen generator package.

bazel test //internal/httpclient/... //backend/conformance/... now passes
all 4 targets (previously 4 of the package's tests failed only under
Bazel's sandbox: TestInterfaceCompleteness,
TestTheCountGroupVocabularyMatchesTheSharedOne,
TestFlaglessListSortIsTheSameOrderNamed,
TestDivergenceParkCitationsResolveToLiveLedgerRows).

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

* fix(conformance): close two pre-existing leg-wiring gaps found while registering http

- RunLifecycleResultsCarryThePostWriteRowVersion (added in 536561124) was
  never wired into dolt/embeddeddolt/uow's own lifecycle_close_reopen test
  tables, only into the http leg's. TestEveryLegWiresEveryRoleContract
  catches this once a fourth leg forces the test to actually run again;
  wire the missing t.Run into all three.
- The three StatsReporter "suppressed rows" cases (GateIssues/TemplateIssues
  breakdown) were never added to served_graph_aux_test.go even though the
  wire already carries both fields end-to-end (types.Statistics is shared
  verbatim by apigen.StatsResponse and the client's decode). Wire them; all
  three pass over HTTP with no server or client change needed.

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

* feat(conformance): register the http leg in the role-contract lock

Registers "http" (wiringRoot internal/httpclient) in contractLegRegistry.
The served-surface harness (served_harness_test.go + 16 served_*_test.go
files) already wired 495 of 576 role-contract entrypoints from the
bd-enterprise lift; this change:

- Waives the 3 RunCycleDetectorIncludeTracks* cases: issueops.
  DetectCyclesRequest.IncludeTracks has no plumbing on either side of the
  wire today (cycles.go always calls DetectCycles with a zero-value
  request; the client's DetectCycles ignores its request parameter). No
  slice through S13 adds one, so the waiver says a new slice is needed
  rather than pointing at an existing one.
- Sets adoptionCeiling: 75 for the remaining, not-yet-wired write-role and
  internal-plumbing entrypoints (lifecycle writes, DependencyEditor,
  MetadataCAS, Lease, Sweeper, VersionReconciler, Bootstrapper/
  InitVerifier, cross-record invariants) that S4 and later write slices
  pick up and ratchet down.
- Adds //internal/httpclient:go_srcs to storage_test's data: the leg's
  wiring root lives outside internal/storage, and the Bazel sandbox has no
  other reason to materialize those sources for a test that reads them at
  runtime.

TestEveryLegWiresEveryRoleContract, TestEveryRoleMethodHasAContractCase,
and RunUnsupportedContract (already wired pre-lift in
internal/httpclient/completeness_test.go) all pass for the http leg.

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

* fix(httpclient): close review's HIGH 2-5 gaps and reconcile their test doubles

HIGH 2 (BatchCloser), HIGH 3 (created_by stamping, absent-parent 404/400,
force_notes_overwrite carriage) and HIGH 4 (CapabilityError now unwraps to a
typed *storage.ErrUnsupported with Capability) were implemented in prior
commits on this branch; this change finishes HIGH 5 and the verification the
review asked for:

- role_reader.go's Reader.Get and bridge.go's raw GetIssue both now stitch
  Revision back onto Issue.RowVersion via parseRevision, so a guarded write
  built off either read carries the row's real token instead of a decoded
  zero. Both are pinned by round-trip served tests that guard a write with
  the read's token and require a stale-token replay to refuse.
- Fixed create_test.go's stale assertion that created_by must stay empty
  (contradicted the HIGH 3 stamping fix it predated).
- Fixed recordingWire's canned IssueDetails{} response (roles_test.go): it
  omitted Revision, which is a required field on every getIssue response
  per the OpenAPI spec, and the HIGH 5 stitch now reads it unconditionally.
- Synced internal/httpclient/wire/BUILD.bazel via gazelle: handshake_test.go's
  new internal/storage import had no corresponding dep.
- gofmt'd write_roles_test.go's stubWire struct tags.

Verified: served HTTP conformance tier (BEADS_TEST_EMBEDDED_DOLT=1
BEADS_HTTP_TEST_REQUIRED=1 go test ./internal/httpclient/, -timeout=40m)
600 PASS / 0 FAIL / 72 SKIP (all ledgered known-divergence waivers). One
TLS-handshake-timing test failed in that run and passed 3/3 in isolation
(unrelated file, pre-existing flake under machine load, not reproducible).
Also green: default go test (minus the pre-existing, unrelated
TestEngdocsAndRootMarkdownLinks doc-link drift and the environmental
internal/storage/uow dolt-server-spawn hang), bazel build/test for the
touched packages, make api-check, and gofmt/vet.

Live-mutated and reverted 3 guards to confirm their tests are load-bearing:
role_reader.go's RowVersion stitch, bridge.go's RowVersion stitch, and
lifecycle.go's force_notes_overwrite wiring.

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

* feat(ci): add served HTTP conformance as Tier 3 of the conformance gate

The served tier (internal/httpclient's served_*_test.go corpus) never ran
in CI, so HIGH 2-5's regressions (and any future ones) would merge
undetected. Add it as Tier 3 of scripts/conformance.sh, the existing
required entrypoint conformance.yml already runs on every PR/push/merge_group
(not a new workflow, not wired through ci-gate.sh's aggregation -- this
repo's convention for this gate is a single standalone job):

  CGO_ENABLED=1 BEADS_TEST_EMBEDDED_DOLT=1 BEADS_HTTP_TEST_REQUIRED=1 \
    go test -timeout=40m ./internal/httpclient/

Left unsharded: Tier 1 and Tier 2 are themselves single unsharded
invocations, and Tier 3 is one Go package, not a multi-package corpus the
repo's existing package-sharding scripts apply to. No Bazel-lane addition:
bazel-coverage's embedded/dolt_server outputs only ever substitute for
main.yml/pr-risk.yml jobs, never for conformance.yml's own job, so there is
no existing Bazel-lane relationship for this gate to extend.

Bumped the job's timeout-minutes 45 -> 100 (30m + 10m + 40m budgeted
sub-timeouts plus checkout/setup-go overhead) and updated the three policy
tests that pin this script/workflow byte-for-byte
(TestConformanceScriptUsesExplicitTimeoutBudgets,
TestConformanceScriptPropagatesGoTestFailures,
TestConformanceWorkflowHasOuterTimeoutBudget), re-included
internal/httpclient/** in both path filters (push and pull_request, kept
identical) since served_*_test.go files are the suite itself and would
otherwise be excluded by the shared !**_test.go negation, and documented the
new filter entry in ci_f7c_advisory_test.go's own-entries map.

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

* fix(httpclient): root-cause and fix the Happy-Eyeballs TLS flake in store_dependent_test.go

TestTransportForSucceedsWithEnvCAFile (and 3 Handshake-based siblings that
assert on a successful dial through a configured CA: SidecarCAFile,
CAFileEnvAgreeingWithSidecarSucceeds, DialWithNilTransportHTTPClientGetsCAInjectedOnACopy)
flaked once with "tls: first record does not look like a TLS handshake".

Root cause: our code, same class S2 already fixed for TransportFor's direct
callers (forceIPv4Loopback in ca_test.go/ca_wrong_ca_test.go). Every server
these tests dial is addressed by hostname "localhost" (ca.startServer
rewrites it there deliberately, so SNI is actually sent), which Go's
default dialer races a tcp6 dial to ::1:<port> against the real tcp4 dial to
127.0.0.1:<port> for (RFC 6555). An unrelated local process already bound to
a colliding ephemeral port on ::1 can occasionally win that race before the
real dial completes, and the client speaks TLS to that unrelated process
instead -- the misleading handshake error, not a real hang or a product bug.

These four tests go through Handshake with DialOptions{} (HTTPClient left
nil deliberately, since that is itself the nil-HTTPClient branch of DialWith
under test), so they never get a *http.Transport back to mutate the way
forceIPv4Loopback's existing callers do. Fixed via warmIPv4OnlyCATransport:
pre-build the target's CA-scoped transport through the same public
TransportFor the product code itself calls (so it lands in the exact
(path, content)-keyed cache transportForFile's cache hit returns), force
tcp4-only on that cached pointer, and let Handshake's own DialWith run
unchanged -- same branch under test, same cached transport, no sleeps, no
retries. Verified with -race -count=50 on all four: 200/200 pass.

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

* fix(httpclient): refuse DetectCycles(IncludeTracks=true) instead of silently ignoring it

roles_graph.go's httpCycleDetector.DetectCycles took its request as `_`,
forwarding nothing: a caller asking for the widened (tracks-following) walk
silently got the narrower default walk back with no error. listDependencyCycles
has no include_tracks wire parameter at all, so there is no way to honor the
field — only to refuse it loudly or drop it silently. Switch to the typed,
ledger-cited refusal (encode.RefusedError via refuse(), citing new row
"L-cycles-tracks") that CountEdges' own wire bound already uses, add the
ledger row and its Op, regenerate the auto-generated ledger doc, and pin the
behavior with a unit test (no served-tier case needed: the refusal is
pre-dial by design, same reasoning as the existing edge-count bound pin).

Also fix leg_contract_wiring_test.go's cycleTracksWireGapWaiverReason, which
had gone stale: it described the http leg as silently forwarding nothing for
this field, which was true before this change and is not after. The waiver
itself (the three RunCycleDetectorIncludeTracks* contract cases stay unwired
for the http leg) is unaffected — they were never wired, and still are not —
only the reason text needed updating to describe a typed refusal instead of a
silent ignore.

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

* fix(storage): name the http leg's permanent contract gaps instead of budgeting them

The http leg's role-contract adoption ceiling (internal/storage/contract_leg_registry_test.go)
sat at a flat 75, with a prose "adopting" note that bundled every skip into
one vague bucket — including MetadataCAS, which is in fact fully wired (0
missing cases), a false claim left over from an earlier wiring pass.

Twenty-six of the 75 skips are not S4-and-later work at all: they are
PERMANENT gaps that no future slice closes, because the contract itself has
no publicops role for an HTTP client to route through:

  - Importer (4 cases): uow is Importer's one accessor, same precedent the
    dolt and embeddeddolt legs already carry (importerOneAccessorWaiverReason).
  - RetentionFixture/EpochFixture (15 cases) and CrossRecordInvariantFixture
    (7 cases): both fixtures carry raw storage hooks (Resolve, Erase, Mint,
    CurrentEpoch, GuardedWrite, EnforceCrossRecordInvariant, ...) with no
    publicops field at all. dolt, embeddeddolt and uow wire these because
    they ARE the storage engine this address/epoch/retention and
    cross-record transaction bookkeeping belongs to; the http leg is a
    remote client with none of its own to report. There is no wire surface
    for this to ever route through short of a new role being designed from
    scratch — a new slice, not a missing test line.

These 26 are now named, reasoned waivers in unwiredContractEntrypoints
(two new reason constants: retentionEpochNoRoleWaiverReason and
crossRecordInvariantNoRoleWaiverReason), and the ceiling drops from 75 to 49
to match. The "adopting" note is rewritten to correctly name every remaining
category under budget (lifecycle writes, DependencyEditor, DualWrite,
Sweeper, VersionReconciler, Bootstrapper/InitVerifier, ExpectedRevision/
Refusal) and to drop the false MetadataCAS claim.

Also documents, at conformanceEntrypointsWiredBy, why a leg wiring a
conformance.RunX reference with every hook left nil would read as "adopted"
by this lock's static source grep while actually running as a skip —
matching the loophole internal/httpclient's divergence_citation_gate_test.go
already closes for skipKnownDivergence call sites. No leg currently does
this (verified by inspection); the note sets the review expectation for
future wiring rather than papering over the gap with no record of the policy.

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

* fix(licensing): scrub internal program/org naming and a leaked private ID from OSS-visible text

MEDIUM 8 of the S3 ship review: remove licensing-hygiene leaks found by a
read-only repo-wide survey, while leaving every legitimate "Contributed by
gascity from bd-enterprise ... to OSS beads under the MIT license." provenance
header and every genuine public gascity/gastownhall self-reference (the real
OSS org, beads.gascity.com docs domain, RBE infra) untouched:

- Delete release-gates/ga-7psli2-3-1-baseline-cmd-bd-fix-gate.md: the only
  file in release-gates/ keyed by a private `ga-` tracker ID instead of the
  directory's established public `be-` convention (30 other files), and the
  only one leaking internal filesystem paths (/home/jaword/...,
  gc-management/.gc/artifacts) and internal routing terms (mayor/mpr,
  "deployer session"). Not referenced from anywhere else in the tree.
- .golangci.yml: drop two private `ga-2ltro.12`/`ga-26w10` history citations
  used as nolint-comment justifications; reworded to the same explanatory
  content without naming a private tracker ID.
- Reword 19 "gc native-program" occurrences (14 files, comments and one
  design doc) to drop the internal program name while keeping the "S3
  reconciliation (2026-10)" dating they were attached to.
- cmd/bd/if_revision.go, if_revision_test.go, update.go,
  update_proxied_server.go: drop literal citations of gascity's private
  bdstore_conditional.go classifier (including a test function name,
  TestIfRevisionEnvelopeGascityContract -> ...DownstreamContract) while
  keeping the substantive explanation of why this envelope's shape is
  load-bearing for a downstream consumer.
- internal/httpclient/lifecycle.go: drop a citation of gascity's private
  internal/beads/bdstore.go.
- internal/httpclient/dial.go: drop the internal/enterprise/httpgw package
  path, keeping "a gateway dialer outside this repo".
- internal/httpclient/register.go: reword away from naming "the enterprise
  distribution" while keeping the build-tag-opt-in behavior it documents.

Verified: go build ./..., go vet ./internal/httpclient/... ./cmd/bd/...,
go test ./internal/httpclient/... and ./cmd/bd/... -run TestIfRevision all
pass; TestDivergenceLedgerDocMatchesLedger still passes (ledger.go and its
doc were edited in lockstep). gofmt -l reports no diffs on any touched file.

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

* fix(httpclient/wire): correct the CapExternalDependencies doc's implied false claim

MEDIUM 9 of the S3 ship review. The old comment on CapExternalDependencies
said this client "has no external-dependency policy layer to gate" and that
"OSS publishes no storage.ExternalDependencyQueryStore-backed client policy
... to compose" immediately after naming bd-enterprise's removed policy.go --
easily misread as "OSS has no external-dependency decorator at all." It does:
internal/storage/externaldeps's decorator is unconditional (no build tag) and
is wired into every local storage chain by cmd/bd/storage_chain.go.

Reworded to say precisely what is and is not true: the decorator exists and
runs for local backends; what this http client lacks is a client-side
composition of that decorator around a remote store, which is moot anyway
because a server advertising this capability already applies the policy
itself before answering. (Rolled in the same "gc native-program" wording
removal from the MEDIUM 8 commit, since both edits touch this comment block.)

A second claim from the same review item -- that OSS is said somewhere not to
serve events:watch -- could not be located despite an exhaustive repo-wide
search (this file, engdocs/, docs/reference/events-journal.md,
SERVE_RUNBOOK.md, the divergence ledger, CHANGELOG.md, and a dedicated
read-only research pass). internal/httpapi/events_watch.go,
routes.go's events.watch route entry, and internal/httpclient/wire/stream.go
all confirm OSS serves it unconditionally (gated only per-workspace by the
events journal setting, not by build/distribution). No corresponding false
claim exists in this worktree to fix; noting this rather than editing
something that already reads correctly.

Verified: go build ./internal/httpclient/..., go vet, go test
./internal/httpclient/wire/... pass. gofmt -l clean.

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

* test(unsupportedgen): add a freshness check for the generated shell

LOW item from the S3 ship review: internal/storage/unsupportedgen had no
tests of its own, so the generator could drift from the checked-in
internal/httpclient/unsupported_gen.go (a storage.DoltStorage interface
change, or a hand-written method added/removed on Store) with nothing to
catch it short of a human noticing the diff. TestInterfaceCompleteness
(completeness_test.go) already pins which methods belong in the shell by
name, but not whether the checked-in bytes match what the generator would
produce today.

TestGeneratedShellIsFresh runs the same scan-then-generate pipeline main()
runs for the registered DoltStorage/httpclient/Store consumer and diffs the
result against the checked-in file -- mirrors the existing
TestDivergenceLedgerDocMatchesLedger pattern in
internal/httpclient/encode/ledger_render_test.go. Added
TestScanHandWrittenMethodsExcludesOwnOutput alongside it to pin the
correctness property the freshness check depends on (scanning must not see
the generator's own prior output as hand-written).

BUILD.bazel: added the go_test rule by hand (gazelle cannot infer the
cross-package `data` dependency a relative-path os.ReadFile needs under the
Bazel sandbox) with data = ["//internal/httpclient:go_srcs"], following the
existing cross-package data pattern in
internal/httpclient/encode/BUILD.bazel. Placed go_test before the
go_srcs.py-managed filegroup block, which `make bazel-sync-check` requires.
Verified: `bazel run //:gazelle` leaves the rule untouched, `bazel test
//internal/storage/unsupportedgen:unsupportedgen_test` passes, `make
bazel-sync-check` is clean, go build/vet/test ./... all pass.

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

* fix(httpclient/encode): scrub a private tracker-ID cluster from the shipped divergence-ledger doc

Follow-up to the MEDIUM 8 licensing scrub: internal/httpclient/encode's
ledger_render.go header and ledger.go's comments/pinnedElsewhere constant/two
Why strings cited "ga-b8ddd.12/.19/.23/.30" by name. These feed directly into
engdocs/design/http-divergence-ledger.md -- a shipped, generated OSS design
doc, the most visible surface this private ID cluster reached (Fork A's
MEDIUM 8 survey found ~40 occurrences of "ga-b8ddd" across the httpclient
package; this commit addresses the subset inside package encode that is
checked-in prose/doc text, not test-fixture or assertion values). Reworded to
keep the same substantive explanation (what closed, what's still deferred,
which dual run resolved L17) without naming the private ID.

The remaining ~30 occurrences of "ga-b8ddd" outside package encode
(offrole.go, metadata.go, store.go, roles_test.go, wire/*_test.go,
served_*_test.go) are left for a follow-up pass: scrubbing them individually
needs the same per-file verification this commit did, and is a larger,
separate blast radius than was practical in this pass.

Regenerated engdocs/design/http-divergence-ledger.md via
`go test ./internal/httpclient/encode -run TestDivergenceLedgerDocMatchesLedger
-update-ledger-doc`; diff confirmed only the ga-b8ddd text changed. go build
./..., go vet ./internal/httpclient/..., and go test ./internal/httpclient/...
all pass.

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

* docs(httpclient): drop a private host reference from a test comment

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* revert(licensing): keep the scrub to the contributed client code

The previous scrub also edited upstream files this PR doesn't otherwise
touch (.golangci.yml, cmd/bd --if-revision files from #7203) and deleted an
upstream release-gate record. Restore them; the provenance scrub applies only
to the code contributed from bd-enterprise.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(httpclient): wire S8 count-scope fields on the client

Encode ParentID/NoParent/ExcludeTypes/ExcludeStatus onto countIssues
(table.go + encode.go), add issues.count.scope to the client capability
table (wire/handshake.go, wire/vocabulary_test.go), and refuse locally
before dialing when the server hasn't advertised the token and any scope
field is set (counter.go's refuseUnservedScope), returning a typed
*storage.ErrUnsupported{Capability:"issues.count.scope"} rather than
dropping fields or taking a guaranteed-400 round trip.

Adds encoding-parity coverage (counts_test.go), a masked-token skew test
proving the pre-dial refusal and zero dials (counts_test.go), roundtrip
and skew-table fixes for the newly-encoded fields (encode/roundtrip_test.go,
encode/skew.go), and wires S8's nine shared Counter conformance cases into
the served http leg (served_counter_test.go), including AddDependency so
the wisp/compose cases run instead of skipping. List stays nil on this
fixture since listTable() has pre-existing, unrelated permanent refusals
for ListRequest.NoParent/ExcludeTypes, so the three *MatchesListCardinality
cases skip here by design.

internal/storage's TestEveryLegWiresEveryRoleContract/http ceiling check
remains red (53 skipped vs ceiling 49) after this change, but strictly
improved: before this change the inherited baseline was 62 skipped (13
over ceiling), all nine of S8's new entrypoints unwired. This change wires
all nine, closing exactly that gap; the remaining 4-over are named
RunBootstrapper*/RunDependencyEditor* cases unrelated to count-scope,
pre-existing debt from other already-merged slices whose ceiling was
never bumped for them. Left the ceiling constant alone rather than
raising it to paper over debt this change doesn't own.

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

* fix(storage): close the http leg's role-contract ceiling regression

TestEveryLegWiresEveryRoleContract/http went red after the rebase (62
skipped, 13 past its ceiling of 49) before any work in this session; the
prior commit closed 9 of those (S8's Counter cases). The remaining 4-over
were RunBootstrapper* (9 entries) and RunDependencyEditor* (2 entries),
both newly-merged contracts this leg had never classified.

RunBootstrapper*: internal/httpclient/accessors.go already names
Bootstrapper PERMANENTLY UNSERVABLE over http (bd init resolves its
substrate identity entirely client-side, before any server exists to
dial) — add a new named waiver, bootstrapperPermanentlyUnservableWaiverReason,
covering all nine entrypoints. VersionReconciler and InitVerifier are
named permanently unservable by the same accessors.go comment but are
left under the ceiling for their own reviewed change, out of scope here.

RunDependencyEditor*: the OSS server already serves add/remove and the
http leg already wires nearly all of DependencyEditor's contract. The two
missing cases (SameTypeReAddWithChangedMetadataMintsOneVersion,
SameTypeReAddWithIdenticalMetadataIsANoOp) only needed
SetVersionedHistoryEnabled wired onto the fixture, the same way
SetJournalEnabled already is — wired it for real; both pass served.

With Bootstrapper waived and DependencyEditor fully wired, the leg's
unwaived-missing count drops from 53 to 42, so adoptionCeiling moves
from 49 to 42 to keep the ratchet exact, with the adopting prose updated
to match.

TestEveryLegWiresEveryRoleContract is green. Served tier (real, CGO +
embedded dolt): 611 PASS, 0 FAIL, 72 SKIP (up from 609). bazel build/test
and make api-check pass for the touched targets.

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

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/37307836753
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

* fix(conformance): pass -tags gms_pure_go to Tier 3's served httpclient run

scripts/conformance.sh:61 ran a bare `go test -timeout=40m ./internal/httpclient/`
for Tier 3 (served HTTP client/role conformance), which `make ci-pr-policy`'s
build-tag policy check refuses ("bare go test without -tags=gms_pure_go").
Pass the same -tags Tier 1 already does, and update
TestConformanceScriptUsesExplicitTimeoutBudgets' pinned argv to match.

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

* fix(bazel): give //internal/httpclient:httpclient_test room to run

The package takes ~350s under --config=ci (BEADS_TEST_SKIP=dolt, no
BEADS_TEST_EMBEDDED_DOLT) — mostly wall-clock wait on the CA tests'
dialer/keep-alive timeouts, not CPU — but the go_test had no size/timeout
override, so it inherited the medium default's 300s and timed out
intermittently under Bazel (and took "Go test equivalence" down with it).
Set size = "large", timeout = "long", matching
//internal/storage/embeddeddolt's go_test.

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

* fix(httpclient): fix data race in caContextHandler test helper

TestTransportForRaisesMaxIdleConnsPerHostForBursts drives caContextHandler
with 8 concurrent requests; handler() wrote requestSeen/host/sni from every
server goroutine with no synchronization, and the other nine callers (all
single-request) never exercised the race. go test -race reproduced it as
3x DATA RACE across repeated runs.

Guard the fields with a mutex and expose them only through accessor methods
(sawRequest/seenHost/seenSNI), updating every call site in
store_dependent_test.go accordingly.

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

* fix(unsupportedgen): canonicalize reflect-visible stdlib aliases

TestGeneratedShellIsFresh fails on Go >= 1.27: encoding/json.RawMessage
became an alias of encoding/json/jsontext.Value, and reflect only ever sees
an alias's underlying type, so formatType rendered
storage.DoltStorage.MergeMetadata's signature with the new, non-portable
name even though the signature itself did not change. A contributor on
1.27 following the freshness test's own advice ("go generate
./internal/httpclient") would commit a shell that does not compile on the
1.26.7 SDK this repo pins.

Add reflectAliasCanonical, a table mapping a reflect-visible alias target
back to the name a human wrote in source, consulted by namedType. Add an
entry here for any future stdlib alias this generator's output needs to
stay stable across.

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

* fix(httpclient): claimOnlyUpdate propagates the claim's RowVersion

bridge.go's GetIssue already stitches details.Revision onto
hydrated.RowVersion when claimOnlyUpdate rehydrates labels/CreatedBy onto
the claim response, but the claim response itself (issueops.Claimer's
bare-row contract) carries no revision at all, and the copy-back only
touched Labels and CreatedBy. So Lifecycle.Update({Actor, IssueID, Claim:
true}) — `bd update X --claim` — handed back Issue.RowVersion == 0 over
http where the local leg returns the real token, and feeding that into the
next write's ExpectedVersion got a spurious mismatch instead of none.

Copy RowVersion back too. Extend
RunLifecycleResultsCarryThePostWriteRowVersion (shared lifecycle/close/reopen
conformance contract) with a claim-shaped first link in the chain: claim,
then guard the next write with the claim result's own token, proving the
claim-only path populates the real version rather than a nonzero constant.

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

* fix(httpclient): stitch RowVersion on SearchIssues' exact-id fast path

resolve.go's getIssuesByExactID decodes the same IssueDetails shape
bridge.go's GetIssue does, but never parsed details.Revision the way
GetIssue's own stitch does, so SearchIssues(ctx, "<exact id>") answered
RowVersion 0 — a one-line gap: Issue.RowVersion is json:"-", so the decode
left it at zero, and only the explicit parseRevision stitch recovers it from
the response's own Revision string member.

Add TestSearchIssuesExactIDPopulatesRowVersionForAGuardedWrite, pinning the
same guarded-write round trip TestBridgeGetIssuePopulatesRowVersionForAGuardedWrite
already pins for the plain GetIssue path.

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

* fix(httpclient): route every write role's refusals through inexpressible

Review finding 7: write-side refusals were not uniformly *ErrUnsupported.
Read roles already wrap encoder refusals through Store.inexpressible, which
reaches both encode.RefusedError and encode.CapabilityError; the write side's
refuse() returned a bare *encode.RefusedError instead, so a caller doing
errors.As(err, &unsupported) caught the count-scope refusal but missed
Sweeper.Sweep(Limit), DetectCycles(IncludeTracks), ReadyClaimer.ClaimNext,
BatchApplier.ApplyBatch, BatchCloser.CloseBatch, Deleter.Delete,
DependencyEditor.AddDependencies, and BatchCreator.CreateBatch.

Give InexpressibleError a detail field that preserves the original error's
composite text (an "items[%d]..." or "Issue.%s:" prefix a deeper encoder
helper already adds) instead of collapsing the message to the bare ledger
row text, and wrap every remaining write role's exported method in a single
named-return defer calling store.inexpressible, matching the pattern
lifecycle.go's Create/Update/Reopen already use.

Add TestWriteRoleRefusalsMatchTheReadShape, pinning three write-side
refusals (Sweeper.Sweep Limit, CycleDetector.DetectCycles IncludeTracks,
ReadyClaimer.ClaimNext) now classify via errors.As(*storage.ErrUnsupported)
the same way a read-side refusal does.

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

* fix(cmd/bd): stop spelling out Status: StatusOpen on a markdown batch create

Review nit 8: batchcreator.go's refuseUnwirableIssue refuses a populated
Status (apigen.BatchCreateItem has no wire slot for it), and
buildMarkdownBatchRequest always set Status: types.StatusOpen explicitly, so
`bd create --file` refused on every call against an http-backed store.

PreparePublicCreateRequest already defaults an empty Status to StatusOpen on
every backend, including the http client store's own server, so the explicit
assignment here was never a different outcome - only a populated member the
wire can't carry. Leave it unset; the created issue is identical on every
backend, and the http leg's role-level accounting for why Status and
CreatedBy are excluded from its allowlists is documented on
batchCreateCarriedIssueMembers (internal/httpclient/batchcreator.go).

CreatedBy is left as-is: that member genuinely has no wire slot AND the
server does not yet stamp it from Actor (a gap already tracked in this PR's
Follow-ups), so its refusal is correct, not a bug to route around.

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

* docs(httpapi): correct create.go's CreatedBy comment to caller-asserted

Review nit 8: the comment claimed CreatedBy is stamped from the
"authenticated actor," but actor is parsed straight from the request body
(s.bodyActor) and never authenticated - exactly as this file's own doc
comment states a few lines above. Reword to "caller-asserted actor" and
cross-reference that doc comment so the two stay consistent. No behavior
change: the stamp itself and its test coverage were already correct.

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

* fix(httpclient): raise MaxIdleConnsPerHost for a supplied client's nil Transport

Review nit 8: DialWith's doc comment promises the raised MaxIdleConnsPerHost
ceiling on every dial, "whether or not a CA is configured," but the
opts.HTTPClient.Transport == nil arm only injected a transport when the
target's CA was configured (resolved.configured()). A caller-supplied
*http.Client with a nil Transport and no CA fell through untouched, so it
defaulted to http.DefaultTransport's own ceiling of 2 at request time instead
- silently exempting this one shape from the doc's promise and forcing a
fresh TLS handshake on most of a concurrent burst even once the pool is warm.

Route this arm through the same dialTransport helper the opts.HTTPClient ==
nil arm above already uses (the CA-scoped transport when a CA is configured,
the shared baseline otherwise), injected onto a copy so the caller's own
*http.Client fields (Timeout, CheckRedirect, Jar) stay untouched.

Add TestDialWithSuppliedClientNilTransportNoCARaisesMaxIdleConnsPerHost: an
end-to-end burst through wire.Client.Do, traced with httptrace, asserting the
connection pool settles into reuse at a burst size the default ceiling of 2
cannot sustain.

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

* docs(httpclient): stop citing nonexistent design docs from new source files

Review nit 8: several comments added by this lift cited
engdocs/design/http-client-backend.md, "D8 row N", and beads-design/slices.json
- none of which exist in this repository (the design lived in the
bd-enterprise-internal source this code was lifted from).

Point each citation at what actually ships in-repo instead:
engdocs/design/http-divergence-ledger.md (the generated, human-readable
rendering of the divergence ledger in encode/ledger.go) for the D7/D8/D9
discipline citations in encode.go, ledger.go, bijection_test.go,
write_ledger_test.go, wire/credential.go and store.go's package doc; and a
direct description of the wire-gap it records, rather than a slices.json
scope reference, in leg_contract_wiring_test.go's cycle-tracks waiver
rationale. Regenerate http-divergence-ledger.md from ledger_render.go (which
had the same stale citation) via
`go test ./internal/httpclient/encode -run TestDivergenceLedgerDocMatchesLedger -update-ledger-doc`
so the shipped doc and its generator agree.

No behavior change; comment and generated-doc text only.

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

* feat(httpclient): implement issueops.BatchGetter for the HTTP client leg

The rebase onto origin/main (item 9 of PR #7247's review) brought in
upstream #7248's new issueops.BatchGetter role on storage.DoltStorage,
breaking the HTTP client leg's interface satisfaction. This wires it up
as a read role (no actor, no version guard, writes nothing — dialed as
a POST only because MaxGetManyIDs ids cannot ride a GET query string),
mirroring Counter/Querier rather than the WriteWire-wrapped roles.

- wire/paths.go: add PathIssuesBatchGet ("/v0/beads/issues:batchGet").
- batchgetter.go: httpBatchGetter.GetMany dials the server and stitches
  each resolved issue's RowVersion from apigen.BatchGetIssue.Revision
  (the role's only wire spelling of the row token, since RowVersion is
  json:"-"). checkGetManyIDs pre-validates the cap and blank-id rules,
  in the same order internal/storage/issueops.ValidateGetManyRequest
  applies them, because batch_get.go's failBatchGetErr collapses every
  validation failure into one generic, code-less InvalidArgument the
  client could never decode back into *issueops.TooManyIDsError.
- accessors.go: add the BatchGetter() accessor (26th wire-backed role).
- unsupported_gen.go: regenerated, dropping the now-implemented stub.
- completeness_test.go: move BatchGetter into wireBackedAccessors and
  bump the asserted accessor-matrix total from 28 to 29.
- served_test.go / served_harness_test.go: both package-local "by hand"
  httpapi.Config builders (serveRoles, serveConfig) now wire
  cfg.BatchGetter, fixing ~56 served-tier tests that broke once
  BatchGetter joined httpapi.Listen's required role set.
- served_batch_getter_test.go: wire the HTTP leg into all 14
  backend/conformance.RunBatchGetterXxx cases, following
  served_graph_counter_test.go's pattern. This surfaced a real bug:
  GetMany built Missing via append([]string(nil), body.Missing...),
  which stays nil when the server reports no misses, violating the
  role's "Missing is never nil on success" contract — fixed to build
  via make([]string, len(body.Missing)) + copy.

Verified: go build/vet clean; internal/httpclient suite green
(including the embedded-dolt served tier); TestEveryLegWiresEveryRoleContract
holds the http leg's adoption ceiling at exactly 42 with no change needed;
TestInterfaceCompleteness and TestAccessorMatrixMatchesDesign pass.

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

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/37450731721
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

* test(httpclient): lock contextServer.seen against concurrent handler goroutines

TestDialWithSuppliedClientNilTransportNoCARaisesMaxIdleConnsPerHost drives
the stub with bursts of 8 concurrent requests; the handler appended to
seen without a lock. Readers only look at seen after their requests return.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(bazel): sync go_srcs managed blocks for unsupportedgen after the main merge

The PR adds internal/storage/unsupportedgen on a base that predates #7320,
which gave every Bazel package a managed repo_files filegroup. On the merge,
`python3 tools/bazel/go_srcs.py --check` (TestBazelGoSrcsBlocksCurrent) found
3 stale blocks: the package's own repo_files block, its entry in the root
BUILD.bazel repo_files list, and its entry in tools/bazel/BUILD.bazel.
`make bazel-sync` regenerated exactly those; gazelle changed nothing else.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): refuse DepAddItem.HasSpawner and ThreadID on applyBatch after the main merge

Main's #7209 gave issueops.DepAddItem two members, HasSpawner and
ThreadID, and a conformance case, RunBatchApplyStampsSpawnerIDOnlyWhenNamed.
ApplyDepAddItem on the v0 wire publishes source, target, type and
metadata only, so on the merge the http leg dropped both silently and
two of the PR's gates went red:

- TestEveryWireExcludedWriteMemberCarriesALedgerRow: the reflective
  census found two wire-excluded DepAddItem members with no ledger row.
- TestEveryLegWiresEveryRoleContract/http: the new case left the leg
  at 43 unwired cases against its exact ceiling of 42.

applyDepAddItemBody now refuses each member where the role would store
something the wire cannot say, under two new KindRefuse rows,
W-DepAddItem.HasSpawner and W-DepAddItem.ThreadID. The spawner flag
refuses only on a waits-for edge, because the role ignores it on every
other type and stores the same row either way. The ledger doc is
regenerated (264 rows).

The served tier wires the new case as a park on W-DepAddItem.HasSpawner,
owned by the family's existing bead, which brings the http leg back to
its ceiling. With the skip removed the case fails on the client's
refusal; with the refusal also removed it fails on the drop the row
names: spawner_id "" where the role stamps the resolved target.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): address #7247 relaunch review iteration 1

Review iteration 1 of the relaunched adoption raised six majors. This
commit fixes all six. Five are the majors the first adoption's
iteration 1 raised. Its fixup, 696803f250 (tag
adopt-pr/bd-f5illd/stranded-fixup-696803f250), fixed them but never
reached the branch. That fix is ported here onto the contributor's
current head, with its reasoning unchanged; the sixth is new.

Creates refused what the CLI sends. Every `bd create` carries
CreatedBy, a workspace whose config.yaml names a prefix also carries
IDPrefix, and the client refused both.
- The server stamps created_by from the actor on all three create
  shapes: batch_create.go and batch_apply.go now match create.go.
- The client sends a CreatedBy that names the actor and refuses any
  other value, which the server's stamp would silently replace.
  createIssue and the apply create item share
  refuseUnwirableIssueMembers.
- IDPrefix refuses only where the role would act on it: an explicit,
  unforced id.
- `bd create --file` stays refused over http. Dropping its Status was
  safe but not enough: the batch create still refuses its Provenance
  and Owner. The markdown.go and batchcreator.go comments that called
  it servable now say so.

keysetFilter ignored AfterPriority. It now compares priority first,
mirroring sqlbuild's KeysetPriorityCreatedAtIDPredicate, and a new
served case resumes a priority keyset position. AfterID or AfterPriority
without AfterCreatedAt no longer reads as a zero-instant position that
discarded every row (the AfterID minor).

Claim with a patch was refused on a false ledger claim. `claim`,
`force_assignee_transfer` and `force_close_policy` now ride updateBody
like `force_notes_overwrite`, so a claim with a patch or a version guard
is one updateIssue call. A claim ALONE sent to a server that predates
the member (#6890) falls back to claimIssue. The three ledger rows are
retired, and the served cases parked on them now run.

OpenReadOnly returns a writable store. It stays writable, as a
documented exception: backends.Backend.OpenReadOnly also serves the
root pre-run's classified reads, and `bd ready --claim` writes through
that store. The exception is named in the backends.Backend contract,
the store_factory invariant and the store doc, and
TestReadOnlyOpenServesTheClaimBdReadyMakes pins it. An OpenNonMutating
backend hook is the follow-up.

Security surface.
- http_target.json is in the doctor gitignore template and its required
  patterns.
- BEADS_HTTP_TOKEN and BEADS_HTTP_TOKEN_COMMAND are host-scoped with
  BEADS_HTTP_CA_FILE's "host[:port]=value" syntax. A value scoped to
  another server falls through to the next rung, and a command scoped
  elsewhere never runs.
- LoadTarget and SaveTarget refuse a url that carries userinfo, and
  Target.String drops userinfo.

The served Tier 3 had no CI home. The new target
//internal/httpclient:httpclient_served_test is an `embedded`-tagged
sh_test. It reruns httpclient_test's binary through
tools/bazel/go_test_variant.sh with the script's
BEADS_TEST_EMBEDDED_DOLT=1 and BEADS_HTTP_TEST_REQUIRED=1, in 24 shards
on the embedded lane's race build. bazel.yml's bazel-embedded job
already runs `bazel test //... --config=embedded`, so no workflow
changes.
- -test.timeout=19m, not the script's 40m: Go's own timeout then fires,
  and dumps every goroutine, before the action's 1200s limit.
- TestBazelRetiredLanesCannotBeNarrowed pins its args and env. The new
  TestConformanceServedTierRunsUnderBazel ties the script's Tier 3
  switches to the rule.
- The new untagged TestServedTierIsLinkedWhenRequired fails a required
  run built without cgo, which drops every served file (the sentinel
  minor).
- A first 12-shard run found two test defects; both are fixed.
  TestServedBatchApplyBoundsTheItemCount's 1000-item apply outlasts the
  client's 60s per-request timeout under -race, so a
  race_detector_{on,off}_test.go pair scales its "at bound" half to 150
  there, as embeddeddolt's TestBatchApplyContract does. And
  TestTheCompositionCatchesAWrongParameter's dropped-filter case leaned
  on rows earlier tests had seeded: run alone, or first in its shard,
  it failed. It now seeds its own row outside the scope.
- conformance.sh, its script test and
  engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md name the target.

Deviations from the review's suggested fixes:
- A bare BEADS_HTTP_TOKEN(_COMMAND) fails closed rather than falling
  back, and the error does not echo the value: a bare token split at an
  "=" would put token text into the pattern half. Dropping the bare
  syntax is safe today: the backend has no Register call site and no
  docs/ page names the variables.
- Target.String drops userinfo instead of using url.URL.Redacted, which
  masks only the password, so a token used as the username would print.
- The pre-#6890 claimIssue fallback leaves RowVersion unset instead of
  borrowing the follow-up read's token. That read is a second snapshot,
  so its token could postdate a write this claim never saw and arm a
  guard that should miss; a guard built from the unset token fails
  closed. Against a current server the claim rides updateIssue, whose
  `revision` is stitched as for any update.

Also fixed: the nit about the completeness failure message, which now
says to regenerate the shell, and the offrole.go tombstone comment that
named a skip list which no longer exists. Left for follow-up (all
latent, since httpclient.Register has no production caller): vocabOnce
latching a failed fetch, snapshot holding s.mu across the handshake
dial, unchunked graph anchors, private tracker IDs in park owners, and
the bounded journal limit above 10000.

Validation:
- git diff --check; gofmt -l; go vet over internal/httpclient/... and
  scripts
- go test -tags gms_pure_go over internal/httpapi/...,
  internal/httpclient/..., internal/storage/backends/... and
  backend/conformance/...; the doctor gitignore tests; the cmd/bd
  events-journal construction guard; ./scripts
- bazel test --config=embedded
  //internal/httpclient:httpclient_served_test on the lane's remote
  executors: 24 shards, 702 top-level tests, 632 pass, 70 skip (69
  ledgered KNOWN DIVERGENCE, plus
  TestCAFileHygieneRefusesGroupWritableFile, which finds no
  supplementary group on the executor), 0 fail, 0 data races; slowest
  shard 283s. tools/bazel/check_testcases.py --bep passes.
- each of the 702 tests run alone (go test -run '^Name$', without
  -race): 0 fail
- the whole tier under go test without -race, with the script's
  switches and -timeout=40m, before the two test fixes: 633 pass, 69
  skip, 0 fail
- removing BEADS_HTTP_TEST_REQUIRED from the rule fails both policy
  tests
- bazel test --config=ci over //internal/httpclient/...,
  //internal/httpapi/..., //scripts/..., //test/docsync/...,
  //internal/storage/backends/..., //backend/conformance/... and
  //cmd/bd/doctor/...: 32 tests pass
- make ci-pr-lint: nogo native plus windows/darwin, passes

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
This commit is contained in:
Julian Knutsen 2026-10-08 12:01:09 +00:00 • committed by GitHub
commit 6d21d337ad
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
154 changed files with 33661 additions and 231 deletions

View file

@ -345,6 +345,7 @@ filegroup(
"//internal/storage/sqlclass:repo_files",
"//internal/storage/sqlcount:repo_files",
"//internal/storage/storagecontract:repo_files",
"//internal/storage/unsupportedgen:repo_files",
"//internal/storage/uow:repo_files",
"//internal/storage/versioncontrolops:repo_files",
"//internal/telemetry:repo_files",

View file

@ -1092,6 +1092,87 @@ func RunLifecycleResultsAreHydratedPostStateSnapshots(t *testing.T, ctx context.
lifecycleCloseReopenAssertSnapshot(t, "reopen result", reopened.Issue, peer)
}
// RunLifecycleResultsCarryThePostWriteRowVersion pins that every write this
// role owns — Update, Close and Reopen — hands back a result whose
// Issue.RowVersion is the row's REAL post-write optimistic-concurrency token,
// not a zero value. types.Issue.RowVersion is `json:"-"`: an implementation
// that forgot to populate it on the way back from its own storage would still
// compile and would still pass every content assertion elsewhere in this
// file, because none of them read RowVersion.
//
// The assertion is a CHAIN rather than three independent zero-checks, because
// a zero-check alone cannot tell a dropped token from a WRONG one (an
// implementation could answer a nonzero constant, or the PRE-write version,
// and still clear it). Each step feeds the token the previous write answered
// with straight into the next write's ExpectedVersion, with no intervening
// read: the claim's token guards the Notes update, Update's token guards
// Close, and Close's token guards Reopen. A guard only passes if the token it
// was given equals the row's actual current version at the instant the next
// write runs, so a wrong or stale token fails closed — the next write
// refuses with ErrVersionMismatch — rather than silently succeeding. Any one
// dropped member breaks the chain at that link.
//
// The chain's first link is a CLAIM-ONLY request (Claim: true, no Patch),
// deliberately unguarded (UpdateRequest.Claim forbids combining Claim with
// ExpectedVersion — see issueops.UpdateRequest's doc): a backend that answers
// Lifecycle.Update's generic patch wire but special-cases a bare claim onto a
// different internal path (the http leg once dialed the Claimer role directly
// for one; it now folds the claim into updateIssue, keeping claimIssue only as
// the fallback for a server that predates updateIssue's `claim` member) could
// easily populate RowVersion on one path and not the other; this exercises
// the claim-only shape specifically, not just the Patch shape the rest of the
// chain already covered.
func RunLifecycleResultsCarryThePostWriteRowVersion(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) {
t.Helper()
id := fixture.IssuePrefix + "-lcr-rowversion"
lifecycleCloseReopenSeedIssue(t, ctx, fixture, id, types.StatusOpen, nil)
claimed, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{
Actor: "writer", IssueID: id, Claim: true,
})
if err != nil {
t.Fatalf("claim %s: %v", id, err)
}
if claimed.Issue == nil || claimed.Issue.RowVersion == 0 {
t.Fatalf("claim result RowVersion = %+v, want a nonzero post-write token", claimed.Issue)
}
claimVersion := claimed.Issue.RowVersion
updated, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{
Actor: "writer", IssueID: id, ExpectedVersion: &claimVersion,
Patch: publicops.IssuePatch{Notes: publicops.Field[string]{Set: true, Value: "rowversion chain"}},
})
if err != nil {
t.Fatalf("update %s guarded by the claim's own token: %v — the claim result's RowVersion was not the row's real current version", id, err)
}
if updated.Issue == nil || updated.Issue.RowVersion == 0 {
t.Fatalf("update result RowVersion = %+v, want a nonzero post-write token", updated.Issue)
}
updateVersion := updated.Issue.RowVersion
closed, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{
Actor: "writer", IssueID: id, ExpectedVersion: &updateVersion,
})
if err != nil {
t.Fatalf("close %s guarded by the update's own token: %v — the update result's RowVersion was not the row's real current version", id, err)
}
if closed.Issue == nil || closed.Issue.RowVersion == 0 {
t.Fatalf("close result RowVersion = %+v, want a nonzero post-write token", closed.Issue)
}
closeVersion := closed.Issue.RowVersion
reopened, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{
Actor: "writer", IssueID: id, ExpectedVersion: &closeVersion,
})
if err != nil {
t.Fatalf("reopen %s guarded by the close's own token: %v — the close result's RowVersion was not the row's real current version", id, err)
}
if reopened.Issue == nil || reopened.Issue.RowVersion == 0 {
t.Fatalf("reopen result RowVersion = %+v, want a nonzero post-write token", reopened.Issue)
}
}
// RunLifecycleCloseAndReopenRequireActorAndIssueID pins the deterministic
// validation floor both verbs sit on. The Lifecycle doc states "Deterministic
// request validation failures match ErrValidation" and "Refusals and

View file

@ -429,6 +429,7 @@ var roleContractCases = []roleContract{
RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps,
RunLifecycleReopenRecordsItsReason,
RunLifecycleResultsAreHydratedPostStateSnapshots,
RunLifecycleResultsCarryThePostWriteRowVersion,
RunLifecycleCloseAndReopenRequireActorAndIssueID,
RunLifecycleReopenProvenanceLabelsHistory,
RunLifecycleCloseSettlesItsTransitiveAndCrossPlaneDependers,

View file

@ -66,8 +66,19 @@ var ErrNotInitialized = errors.New("database not initialized")
type ErrUnsupported struct {
Op string // method name, e.g. "AddLabel" or "Transaction.CreateIssues"
Backend string // e.g. "dolt-server"
// Capability names the advertised token a server-version skew refusal was
// missing, when that is the reason — e.g. the http backend's own
// *wire.CapabilityError, which unwraps to one of these so a caller holding
// only a role interface can classify a skew refusal the same way as any
// other unsupported capability, without importing the wire package.
// Empty for every refusal that is not a skew: a backend that simply never
// implemented an accessor names no token it could have advertised.
Capability string
}
func (e *ErrUnsupported) Error() string {
if e.Capability != "" {
return fmt.Sprintf("operation %q not supported by the %s backend (capability %q not advertised)", e.Op, e.Backend, e.Capability)
}
return fmt.Sprintf("operation %q not supported by the %s backend", e.Op, e.Backend)
}

View file

@ -41,6 +41,9 @@ push-state.json
proxied_server_client_info.json
# http backend activation sidecar (per-user server URL and identity pin)
http_target.json
# Worktree redirect file (contains relative path to main repo's .beads/)
# Must not be committed as paths would be wrong in other clones
redirect
@ -139,6 +142,7 @@ var requiredPatterns = []string{
"*.corrupt.backup/",
".beads-credential-key",
"proxied_server_client_info.json",
"http_target.json",
".local_version",
"backup/",
}

View file

@ -1664,6 +1664,36 @@ func TestGitignore_ContainsDoltServerConfig(t *testing.T) {
}
}
// TestGitignore_ContainsHTTPTarget verifies that the http backend's activation
// sidecar is ignored like proxied_server_client_info.json, the per-user
// sidecar it follows. It names the server the bearer ladder authorizes
// against, so a committed copy would point every clone at that server. It
// must be in requiredPatterns too, so bd doctor --fix heals an existing
// .beads/.gitignore.
func TestGitignore_ContainsHTTPTarget(t *testing.T) {
// Keep this in sync with httpclient.TargetFileName; cmd/bd/doctor does not
// import the client for a string constant.
const pattern = "http_target.json"
if !containsGitignorePattern(GitignoreTemplate, pattern) {
t.Errorf("GitignoreTemplate should contain %q", pattern)
}
if missing := missingGitignorePatterns(GitignoreTemplate); len(missing) != 0 {
t.Errorf("GitignoreTemplate is missing required patterns %v", missing)
}
found := false
for _, p := range requiredPatterns {
if p == pattern {
found = true
break
}
}
if !found {
t.Errorf("requiredPatterns should include %q", pattern)
}
}
// TestCheckLastTouchedNotTracked_NoFile verifies that check passes when no last-touched file exists
func TestCheckLastTouchedNotTracked_NoFile(t *testing.T) {
tmpDir := t.TempDir()

View file

@ -113,11 +113,13 @@ var scannedPackages = map[string]string{
// The staleness check below fails if an exemption stops matching a real
// construction site, so an exemption cannot rot into a permanent excuse.
var constructionExemptions = map[string]string{
// Non-mutating opens. Every arm returns a store that refuses writes
// (OpenReadOnly / OpenForPreviewCommand / a ReadOnly server config), so
// there is no mutation for a journal row to accompany.
"store_factory.go:openNonMutatingStoreFromConfig": "read-only/preview open: the store refuses writes, so no mutation can go unrecorded",
"store_factory_nocgo.go:newReadOnlyStoreFromConfig": "read-only open: the store refuses writes, so no mutation can go unrecorded",
// Non-mutating opens. Every built-in arm returns a store that refuses
// writes (OpenReadOnly / OpenForPreviewCommand / a ReadOnly server config),
// so there is no mutation for a journal row to accompany. The registry arm
// may not refuse — the http client's read-only open is writable — but its
// writes are applied, and journaled, by the bd serve it dials.
"store_factory.go:openNonMutatingStoreFromConfig": "read-only/preview open: built-in arms refuse writes and the http arm's writes are journaled by its server, so no mutation can go unrecorded",
"store_factory_nocgo.go:newReadOnlyStoreFromConfig": "read-only open: built-in arms refuse writes and the http arm's writes are journaled by its server, so no mutation can go unrecorded",
// Store-open-time reconciliation, which runs BEFORE the command's own store
// exists and therefore before any workspace config could be applied to it.

View file

@ -383,17 +383,27 @@ func buildMarkdownBatchRequest(templates []*IssueTemplate, in createInput) (issu
Description: template.Description,
Design: template.Design,
AcceptanceCriteria: template.AcceptanceCriteria,
Status: types.StatusOpen,
Priority: template.Priority,
IssueType: template.IssueType,
Assignee: template.Assignee,
Labels: template.Labels,
Ephemeral: ephemeral,
NoHistory: in.noHistory,
StorageClass: storageClass,
MolType: in.molType,
CreatedBy: in.createdBy,
Owner: in.owner,
// Status is left unset rather than spelled out as
// types.StatusOpen: PreparePublicCreateRequest (shared by every
// backend, including the http client store's server) already
// defaults an empty Status to StatusOpen, so an explicit "open"
// here was never a different outcome — only a populated member
// the http wire's BatchCreateItem has no slot for and the role
// (correctly) refuses rather than drops. Leaving it unset removes
// that one refusal without changing what gets created; the http
// wire still refuses this request's Provenance and Owner (see
// internal/httpclient/batchcreator.go), so `--file` is not
// servable there yet.
Priority: template.Priority,
IssueType: template.IssueType,
Assignee: template.Assignee,
Labels: template.Labels,
Ephemeral: ephemeral,
NoHistory: in.noHistory,
StorageClass: storageClass,
MolType: in.molType,
CreatedBy: in.createdBy,
Owner: in.owner,
},
Dependencies: dependencies,
})

View file

@ -259,6 +259,16 @@ func newPreviewStoreFromConfig(ctx context.Context, beadsDir string) (storage.Do
// OpenForPreviewCommand, ReadOnly server config), so there is no mutation for a
// journal row to accompany. Registered in the construction guard's exemption
// list with that reason.
//
// The registry arm is the exception: it returns whatever the backend's
// OpenReadOnly means, and that one hook also serves the root pre-run's
// classified reads, `bd ready --claim` included, so it may be writable. The
// http client backend's read-only open is (httpclient.NewReadOnlyFromConfig),
// and a write through it reaches its bd serve. The journal exemption still
// holds there: recording that write is the business of the server that applies
// it, and the client has no journal of its own to activate. A separate
// OpenNonMutating hook on backends.Backend, which this function would call
// instead, is the follow-up that closes the exception.
func openNonMutatingStoreFromConfig(ctx context.Context, beadsDir string, preview bool) (storage.DoltStorage, error) {
cfg, err := configfile.Load(beadsDir)
if err != nil {

View file

@ -92,7 +92,8 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.Dol
// newReadOnlyStoreFromConfig creates a read-only SQL-server-backed storage
// backend. It does not activate the events journal: the store refuses writes,
// so there is no mutation for a journal row to accompany (exemption is recorded
// in the construction guard).
// in the construction guard). The registry arm is the exception the cgo
// twin, openNonMutatingStoreFromConfig, describes.
func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) {
cfg, err := configfile.Load(beadsDir)
if err != nil {

View file

@ -1063,6 +1063,10 @@ Required` requires them to have run remotely and passed.
it in `bazel-integration`, which `pr.yml`'s gate requires (PR Core's `go
test` builds neither tag). Neither tier was part of a required gate
before. `scripts/conformance.sh` stays as the local `go test` entrypoint.
Its Tier 3, the served HTTP corpus (`./internal/httpclient` with
`BEADS_TEST_EMBEDDED_DOLT=1` and `BEADS_HTTP_TEST_REQUIRED=1`), runs in
the embedded lane as `//internal/httpclient:httpclient_served_test`
(race build, 24 shards).
`docs-mintlify.yml` likewise drops its docsync job (`go test
./test/docsync`, which `bazel-test` runs as `//test/docsync:docsync_test`)
and keeps only Mintlify's network-bound broken-link check.

View file

@ -22,17 +22,17 @@ hand-edit it: change the ledger in Go and regenerate. Two gates keep it honest
the encoder's reflection **bijection gate** pins the ledger to the wire (a
request field added upstream lands here or fails CI), and the golden test
`TestDivergenceLedgerDocMatchesLedger` pins this doc to the ledger. The prose
rationale, the decision numbers (D-rows) each entry cites, and the full test-lane
map live in the architecture spec, `http-client-backend.md`, which is not
included in this repository.
rationale and the decision numbers (D-rows) each entry cites trace back to the
original (bd-enterprise-internal) design's decision log, which is not included
in this repository; the full test-lane map lives alongside each row below.
A handful of rows still carry a `TODO` pin: these are the read-display and
pre-run residuals (wisp-in-list, the pretty `bd ready` parent-epic map, the
molecule/auto-import pre-run degradations). The
client core is complete; `ga-b8ddd.12` (per-request project-id enforcement)
closed the read-display escalation, so pinning the remaining fixture corpus is
deferred work, tracked on `ga-b8ddd.23` (the read-display residual)
and `ga-b8ddd.19` (the per-id D7 taxonomy). They are refusals or degradations
client core is complete; a since-closed per-request project-id enforcement
follow-up closed the read-display escalation, so pinning the remaining
fixture corpus is deferred work (tracked as a read-display residual and a
per-id D7 taxonomy follow-up). They are refusals or degradations
already in force — the `TODO` is on the test that will hold each one, not on
the behavior.
@ -47,7 +47,7 @@ the behavior.
## Summary
257 rows: 206 refuse, 33 degrade, 18 retired.
264 rows: 209 refuse, 33 degrade, 22 retired.
## Whole-behavior divergences (D9 ledger)
@ -56,42 +56,43 @@ The L-rows the design's D9 table names: whole behaviors that differ over HTTP, e
| ID | Kind | Field / flag | Divergence | Why | Spec | Pinned test |
|---|---|---|---|---|---|---|
| L1 | retired | — | RETIRED — `bd list` over http could not ask for the wisp plane | retired by the upstream ask the design page filed for it: "include_ephemeral on listIssues (retires L1)". Upstream published the parameter, the server decodes it (internal/httpapi/reads.go handleListIssues), and the encoder emits it whenever ListRequest.IncludeEphemeral is set. THERE IS NO DIVERGENCE LEFT TO RECORD. `bd list` still shows no wisps, but it shows none LOCALLY either: the front door registers no --include-ephemeral (only `bd ready` does, ready.go), so the field is unset on both paths and both answer the durable plane. A degrade row describing behavior the local oracle shares is not a degradation, and keeping it as one would be the same falsified-premise problem the W- rows had — a ledger arguing from a document that moved | D9 L1 (RETIRED), D8 row 1 | TestEncodedParametersRoundTripThroughTheServerDecoder |
| L2 | degrade | — | a non-created `bd list` sort, the flagless default included, costs page-to-exhaustion on the three legs that cannot push the order down: an unlimited read (--limit 0), a caller-supplied keyset position, and a server that does not advertise issues.list.sort | NARROWED, not retired, by the upstream ask this row named: listIssues publishes `sort` and `reverse`, and the pager's pushdown leg (list_walk.go sortedPage) answers a bounded, position-free request against an advertising server in ONE request, with the server's own LIMIT deciding which rows survive the caller's order. What is left is the legs where that is unavailable or unsafe. An unlimited read has to cross every row whatever the order, and `limit=0` pushed down would newly meet the server's unlimited-read refusal. A keyset position is defined in the created order, and the pager's prefix discard run against a page some other order truncated would drop rows whose replacements were never fetched — a wrong answer rather than a slow one. A down-level server is the fallback the capability probe exists to reach. On all three the client still fetches every page and applies the SQL order's own Go-side mirror plus a copy of the page epilogue's comparator. The weld itself is NOT a divergence and never was: a cursor is bound to the paged order it was minted in (`created` or `priority`) and the server refuses it under any other `sort` | D9 L2, D8 row 1 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L3 | degrade | — | a multi-page fetch has no snapshot isolation | the keyset cursor pins a position, not a snapshot: rows created mid-walk are missed and row states mix instants, where local mode is one query | D9 L3 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L4 | retired | — | `bd show` dependents sections and comment bodies were degraded | retired by council #1: the write-lifecycle wave landed include_dependents/include_comments on getIssue, and both the off-role text path and the on-role JSON path are wired | D9 L4 (RETIRED), D4, D8 row 1 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L5 | degrade | — | molecules are not auto-loaded pre-run | the loader writes, the write refuses, and the call site swallows the refusal to debug.Logf | D9 L5, D4 | TODO(ga-b8ddd.23): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it |
| L6 | degrade | — | a pre-run auto-import ATTEMPT reaches an http workspace and fails as a best-effort stderr warning; nothing is imported | THE MECHANISM THIS ROW USED TO NAME DOES NOT EXIST. It said the path was "force-disabled through an import.auto=false env override", and there is no such override anywhere: shouldRunAutoImportJSONL (cmd/bd/main.go) reads the config key, whose default is true (internal/config/config.go), and no http path sets it false. WHAT ACTUALLY HAPPENS is that maybeAutoImportJSONL runs — on any non-read-only, non-global, non-server-mode command — and is stopped by its own guards rather than by a switch: a missing or empty issues.jsonl, the attempt stamp, or the emptiness guard, which is a GetStatistics the server serves. Where all three pass (an empty server beside a non-empty local JSONL) the import is attempted and fails, because the client is not a jsonlImporter and the fallback importer's first write — SetConfig, or CreateIssuesWithFullOptions — is on the unsupported allowlist. The function is documented best-effort, so the failure is an stderr warning and the command proceeds. The DEGRADATION is therefore that nothing imports, which is the outcome the design wanted for the right reason — importing a local JSONL into a shared server is not a pre-run side effect — reached by refusal rather than by configuration. It stays a degrade because the command proceeds and the answer is not narrower or wider than the caller asked for. The retirement path is a real skip on the http backend, so the warning stops being the mechanism | D9 L6, D4 | TODO(ga-b8ddd.23): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it |
| L7 | degrade | — | the client-side status/type vocabulary is defaults plus the status.custom/types.custom/types.infra config keys; table-backed customs are invisible client-side | the custom_statuses/custom_types tables have no wire operation; server-side role validation still uses the true vocabulary | D9 L7, D4 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L8 | refuse | `--deps` | `bd list --deps` refuses, and the pretty/--format dependency-decoration arms render undecorated | GetAllDependencyRecords has no wire mapping in v1; listDependencies is an anchored read. --tree is NOT in this row: it defaults true and is `bd list`'s default text rendering | D9 L8, D4 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L9 | degrade | — | credential-bearing settings are unreadable client-side | the server redacts by omission and says so on the wire in Setting.redacted; the client answers absent-WITH-A-REASON rather than the empty string a caller would read as unset | D9 L9 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L10 | refuse | `--watch` | `bd list --watch` and `bd show --watch` refuse | the loops poll every 2s, each `bd list` tick is a full cursor walk (L2), per-tick errors spam or vanish, and the decoration is refused anyway (L8); N watchers against one server is a request storm its semaphore answers with 503s the loop does not back off from | D9 L10, D10 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L11 | degrade | — | hooks fire client-side after the server's commit with no shared transaction, on connected workspaces only | the seam sits below HookFiringStore in the client process; a --server-url ephemeral invocation has no hook directory and runs none | D9 L11, D1 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L2 | degrade | — | a non-created `bd list` sort, the flagless default included, costs page-to-exhaustion on the three legs that cannot push the order down: an unlimited read (--limit 0), a caller-supplied keyset position, and a server that does not advertise issues.list.sort | NARROWED, not retired, by the upstream ask this row named: listIssues publishes `sort` and `reverse`, and the pager's pushdown leg (list_walk.go sortedPage) answers a bounded, position-free request against an advertising server in ONE request, with the server's own LIMIT deciding which rows survive the caller's order. What is left is the legs where that is unavailable or unsafe. An unlimited read has to cross every row whatever the order, and `limit=0` pushed down would newly meet the server's unlimited-read refusal. A keyset position is defined in the created order, and the pager's prefix discard run against a page some other order truncated would drop rows whose replacements were never fetched — a wrong answer rather than a slow one. A down-level server is the fallback the capability probe exists to reach. On all three the client still fetches every page and applies the SQL order's own Go-side mirror plus a copy of the page epilogue's comparator. The weld itself is NOT a divergence and never was: a cursor is bound to the paged order it was minted in (`created` or `priority`) and the server refuses it under any other `sort` | D9 L2, D8 row 1 | 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 |
| L3 | degrade | — | a multi-page fetch has no snapshot isolation | the keyset cursor pins a position, not a snapshot: rows created mid-walk are missed and row states mix instants, where local mode is one query | D9 L3 | 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 |
| L4 | retired | — | `bd show` dependents sections and comment bodies were degraded | retired by council #1: the write-lifecycle wave landed include_dependents/include_comments on getIssue, and both the off-role text path and the on-role JSON path are wired | D9 L4 (RETIRED), D4, D8 row 1 | 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 |
| L5 | degrade | — | molecules are not auto-loaded pre-run | the loader writes, the write refuses, and the call site swallows the refusal to debug.Logf | D9 L5, D4 | TODO(S3): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it |
| L6 | degrade | — | a pre-run auto-import ATTEMPT reaches an http workspace and fails as a best-effort stderr warning; nothing is imported | THE MECHANISM THIS ROW USED TO NAME DOES NOT EXIST. It said the path was "force-disabled through an import.auto=false env override", and there is no such override anywhere: shouldRunAutoImportJSONL (cmd/bd/main.go) reads the config key, whose default is true (internal/config/config.go), and no http path sets it false. WHAT ACTUALLY HAPPENS is that maybeAutoImportJSONL runs — on any non-read-only, non-global, non-server-mode command — and is stopped by its own guards rather than by a switch: a missing or empty issues.jsonl, the attempt stamp, or the emptiness guard, which is a GetStatistics the server serves. Where all three pass (an empty server beside a non-empty local JSONL) the import is attempted and fails, because the client is not a jsonlImporter and the fallback importer's first write — SetConfig, or CreateIssuesWithFullOptions — is on the unsupported allowlist. The function is documented best-effort, so the failure is an stderr warning and the command proceeds. The DEGRADATION is therefore that nothing imports, which is the outcome the design wanted for the right reason — importing a local JSONL into a shared server is not a pre-run side effect — reached by refusal rather than by configuration. It stays a degrade because the command proceeds and the answer is not narrower or wider than the caller asked for. The retirement path is a real skip on the http backend, so the warning stops being the mechanism | D9 L6, D4 | TODO(S3): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it |
| L7 | degrade | — | the client-side status/type vocabulary is defaults plus the status.custom/types.custom/types.infra config keys; table-backed customs are invisible client-side | the custom_statuses/custom_types tables have no wire operation; server-side role validation still uses the true vocabulary | D9 L7, D4 | 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 |
| L8 | refuse | `--deps` | `bd list --deps` refuses, and the pretty/--format dependency-decoration arms render undecorated | GetAllDependencyRecords has no wire mapping in v1; listDependencies is an anchored read. --tree is NOT in this row: it defaults true and is `bd list`'s default text rendering | D9 L8, D4 | 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 |
| L9 | degrade | — | credential-bearing settings are unreadable client-side | the server redacts by omission and says so on the wire in Setting.redacted; the client answers absent-WITH-A-REASON rather than the empty string a caller would read as unset | D9 L9 | 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 |
| L10 | refuse | `--watch` | `bd list --watch` and `bd show --watch` refuse | the loops poll every 2s, each `bd list` tick is a full cursor walk (L2), per-tick errors spam or vanish, and the decoration is refused anyway (L8); N watchers against one server is a request storm its semaphore answers with 503s the loop does not back off from | D9 L10, D10 | 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 |
| L11 | degrade | — | hooks fire client-side after the server's commit with no shared transaction, on connected workspaces only | the seam sits below HookFiringStore in the client process; a --server-url ephemeral invocation has no hook directory and runs none | D9 L11, D1 | 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 |
| L12 | refuse | — | an inexpressible filter refuses, never drops — the class rule every E- row below is an instance of | a dropped filter widens a result set invisibly, and the server can only reject parameters it receives | D9 L12, D7 | TestEncoderHonorsEveryTableDisposition |
| L13 | degrade | — | pretty `bd ready` shows no parent-epic context | buildParentEpicMap swallows the GetDependencyRecordsForIssues refusal into a nil map; the retirement path is an anchored listDependencies plus per-parent getIssue | D9 L13, D4 | TODO(ga-b8ddd.23): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it |
| L14 | degrade | — | against a server that does NOT advertise issues.claimNext, the composed ReadyClaimer leaves three residues: the ready-at-fetch/claim-at-dial window, a false empty under contention after the bounded refetch, and a claimed row whose CARDINALITIES are as of the listing rather than of the claiming transaction | claimIssue validates claimability, not readiness, so a listing plus a claim is not the local role's one transaction and cannot be made into one. THE ROW IS NARROWER THAN IT WAS. Upstream published POST /v0/beads/issues:claimNext (#5510) and client wave ga-jpywb dials it, so on any server that advertises the token NONE of these three residues exists: selection, the compare-and-set and the hydration share the server's own transaction, an empty front is a 200 with `claimed` absent rather than a lost-races error, and the counts describe the state the claim produced. The whole ReadyClaimer contract tier runs against that leg with nothing parked, which is the measurement that says the residues were the COMPOSITION's rather than the wire's. WHAT KEEPS THE ROW ALIVE is the DOWN-LEVEL leg, which survives on purpose: `bd ready --claim` worked against pre-#5510 servers before this port, and refusing it now would be a regression dressed as progress. It is the posture BatchCloser takes toward issues.batchClose, and it is why this row describes shipped behavior rather than history. The third residue is stated in its IMPLEMENTED form, which is not the one the design anticipated: the design expected a follow-up getIssue to hydrate the counts, and therefore a read that could fail AFTER the claim was durable. The composition takes the counts from the ready page it already fetched instead, so that failure mode does not exist — a claim changes no dependency, dependent or comment count, and what is left is staleness bounded by the same fetch-to-dial window residue (a) already owns. Retirement is no longer an upstream ask but a fleet fact: the row goes when no server this client may meet is older than #5510 | D9 L14, D8 row 4 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L15 | degrade | — | a --max-rows cap can fire over http on a query whose Limit is at or under the cap, on the `bd list` legs that still walk | locally the effective SQL LIMIT is min(Limit, MaxRows+1), so a window at or under the cap can never exceed it; over http a walk to exhaustion fetches far more than the window and the cap deliberately bounds WIRE ROWS FETCHED — safety wins over exit-code parity on exactly the unbounded walk the cap exists to bound. NARROWED by the same pushdown that narrowed L2: the pushdown leg asks for min(limit, MaxRows+1) rows in one request, which IS the local expression, so a cap at or above the limit can no longer fire there and a request that used to exit 2 now answers. That is a convergence toward the contract, and it is observable — the same command changes from a refusal to a page. THE NARROWING IS SCOPED TO THE ORDERS SQL CAN EXPRESS, and that scope is a correctness bound rather than an optimization left on the table. For a GO-SIDE sort — sqlbuild.IsGoSideSort, today `--sort id`, which needs the natural-numeric comparison (bd-9 before bd-10) no ORDER BY renders — workapi.SQLLimit pushes 0 down instead of the limit, so LOCALLY the window is MaxRows+1 whatever the limit is and the cap fires on the overage even under a limit at or below it. min(limit, MaxRows+1) is therefore NOT the local expression there, and a request bounded by the limit cannot see the overage at all. walkIssues' gate keeps a capped Go-side sort on the walk, where fetching MaxRows+1 wire rows reproduces that unbounded local window exactly and raises the same refusal — so on this one shape the walk leg is the CONVERGENT one and pushing down would have been the divergence. What keeps the row live is the walk legs (unlimited reads, keyset positions, down-level servers), where the old accounting is unchanged and correct, and `bd ready`, which has no pushdown at all | D9 L15, D12 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L16 | refuse | `--file` | `bd dep add --file` carrying more than 100 edges refuses, naming the wire bound; it is never chunked | maxAddDependencyEdges = 100 (internal/httpapi/dependency_edit.go); chunking is the one path that silently breaks the request's one-transaction/one-history-entry contract, where naive forwarding at least fails loudly | D9 L16, D7, D8 row 18 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-close-cap | refuse | — | a batch close naming more than 100 items refuses, naming the wire bound; it is never chunked | maxBatchCloseItems = 100 (internal/httpapi/batch_close.go); the item cap bounds how long one request may hold a write transaction. Chunking is the one path that silently breaks the request's one-transaction/one-history-entry contract — the same reason L16 refuses a bulk dependency add rather than splitting it — so a larger list refuses and the caller splits it, each request atomic on its own | D9 L-close-cap, D7 F-close, D8 row 17 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-dep-endpoint | degrade | — | a dependency add whose source or target names no issue refuses as ErrValidation over http, not as *DependencyEndpointNotFoundError wrapping ErrDependencySourceNotFound or ErrDependencyTargetNotFound | the wire spells that refusal as a 400 invalid_argument with reason `invalid_value` and the offending member in `param` (internal/httpapi/dependency_edit.go). Reason and code are the same ones a malformed id earns, so the two are indistinguishable without reading `detail` prose — which is exactly what the extension-member vocabulary exists to avoid. The refusal still FAILS the request and still writes nothing; only its classification is coarser. Upstream ask: a distinguishing code or reason for the endpoint-not-found refusal, which retires this row | D8 row 18 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-claim-prose | degrade | — | a claim refusal's MESSAGE does not carry the ClaimedBy/NotClaimableStatus fragments, so beads.ParseClaimConflict recovers nothing from it over http | the fragments exist so that parser can recover the conflicting assignee and status from PROSE. Over the wire both arrive as typed extension members and *ClaimConflictError is reconstructed whole, so a caller reading the FIELDS loses nothing. Recomposing the copy client-side would mean re-implementing which copy each refusal shape gets — an open issue held by someone else deliberately omits the assignee tail, an in-progress one carries it — which is a second implementation of the very rule the fragments were introduced to keep single | D8 row 3 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-delete-notfound | degrade | — | issueops.Deleter.Delete over http refuses an absent id as issueops.ErrNotFound, not as *NotFoundError naming WHICH ids did not resolve | the role's error is a typo report and names every missing id; the wire deliberately does not repeat them (internal/httpapi's NotFound() carries a FIXED detail, so a 404 body cannot echo caller input back). The refusal still FAILS the request and still deletes NOTHING — not even the ids beside the typo — so the all-or-nothing promise is intact and only the classification is coarser. It is stated at the ROLE rather than at a command because `bd delete` is not reachable against an http workspace at all (see httpUnconsumedCapabilities); the embedder holding the role is the audience. Upstream ask: an ids extension member on the not_found problem, which retires this row | D8 row 13 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-delete-dependents | degrade | — | the unforced dependents guard refuses as issueops.ErrValidation, not as *DependentsOutsideRequestError wrapping ErrDependentsOutsideRequest | the wire spells that refusal as a 400 invalid_argument with no `param` (internal/httpapi's failDeleteErr) — the fix is to change the REQUEST, by sending cascade or force — so the blocked id and its dependents cannot be reconstructed without parsing detail prose, which is what the extension-member vocabulary exists to avoid. The guard itself is untouched: the request fails and the graph is whole. Upstream ask: a dependents_outside_request code carrying issue_id and dependents, which retires this row | D8 row 13 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-delete-bound | refuse | — | issueops.Deleter.Delete refuses a request naming more than 1000 ids, citing the wire bound; it is never split across requests | maxDeleteIDs = 1000 (internal/httpapi/delete.go). Splitting is the one path that silently breaks the request's one-transaction, one-history-entry contract — and it would ask the dependents guard about half a request at a time, so a pair the caller deliberately listed together would be refused as an outside dependent. Naive forwarding at least fails loudly. Stated at the ROLE: `bd delete` cannot reach an http workspace, so the embedder is the audience | D8 row 13, D9 L16 (the same argument, on the other bulk write) | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-batchcreate-bound | refuse | — | `bd create --file` carrying more than 100 issues refuses, naming the wire bound; it is never split across requests | maxBatchCreateItems = 100 (internal/httpapi/batch_create.go). The request IS the transaction, so two requests are two transactions and two history entries where the role promises one — and a failure in the second leaves half a plan created, which is the outcome all-or-nothing exists to make impossible | D8 row 14, D9 L16 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-edgecount-bound | refuse | — | issueops.GraphCounter.CountEdges refuses a request naming more than 100 DISTINCT anchors, citing the wire bound; it is never chunked across requests | maxDependencyAnchors = 100 (internal/httpapi/edges.go), the same bound the stored-edge read on this collection carries — the role deliberately sets none of its own and says the bound belongs to the WIRE. Chunking is what a READ could get away with and this one cannot: CountEdges promises that an anchor's EXISTENCE and its edge count are read from one consistent view, so two requests would let an anchor be reported missing by a probe that raced a create the other chunk's count already saw — one answer contradicting itself, which is the exact failure AnchorEdgeCount.Missing exists to make impossible. Refusing at the bound fails loudly instead, and the caller splits the question knowing it asked twice. Upstream ask: a cursor or a higher bound on the anchor list, which retires this row | D9 L16 (the same argument, on a read), D8 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-batchcreate-target | degrade | — | a batch create whose edge target names no issue refuses as issueops.ErrValidation alone, not as ErrValidation WRAPPING ErrNotFound | the wire answers a dangling edge target with a 400 invalid_argument naming `items` (internal/httpapi's failBatchCreate), and deliberately does not quote the role's own message, which arrives as a driver error naming tables and constraints. The refusal still fails the whole batch and creates nothing — the promise the row is about — and only the second sentinel is lost. Upstream ask: a distinguishing code for the absent-target refusal | D8 row 14 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-batchcreate-inbatch | refuse | — | an edge onto an EARLIER ITEM OF THE SAME BATCH cannot be expressed at all over http | the capability needs the earlier item to have named an id for itself, and apigen.BatchCreateItem publishes no id member — an explicit id is refused with the rest of W-BatchCreateItem.Issue. So the target of an in-batch edge can only be a row the workspace already holds. It is a REFUSE row rather than a degrade because the request that asks for it fails: the client refuses the explicit id before the dial, and there is no second spelling that would land the edge silently. The wire's own `target_id` description names this case, so the gap is in the SCHEMA rather than in the handler — the upstream ask is an item id member, which retires this row | D8 row 14 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L18 | degrade | — | DOWN-LEVEL ONLY: against a server that does not advertise issues.batchClose, a single-id `bd close` still composes onto closeIssue and records the SERVER's own close commit message rather than the batch's id-naming entry; the multi-id and --claim-next shapes refuse there | the composed leg is one closeIssue call, so the history entry it leaves is the one that operation writes for itself — the batch's entry names the ids it closed and this one cannot, because no batch ran. Where issues.batchClose IS advertised the whole request is one call and one server-side transaction, so this divergence does not arise at all; the down-level leg survives on purpose, because `bd close` worked against pre-batchClose servers before this port and refusing it now would be a regression dressed as progress. It is the same posture L14 takes toward issues.claimNext. It is a degrade rather than a refuse because the close LANDS and the answer is neither narrower nor wider than the caller asked for — only the record of it is the operation's rather than the batch's. Retirement is a fleet fact rather than an upstream ask: the row goes when no server this client may meet is older than issues.batchClose | D9 L18, D8 row 17 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-create-notfound | degrade | — | a create whose dependency or waits-for target names no row refuses as issueops.ErrValidation ALONE — not as ErrValidation wrapping ErrNotFound — and does not name the target | the wire answers a dangling target with a 400 invalid_argument naming `dependencies` and a FIXED detail (internal/httpapi's failCreateIssue), which deliberately does not quote the role's own message: that message arrives as a driver error naming tables and constraints, and 4xx details on this surface reflect the caller's own input back rather than server internals. The refusal still fails the whole request and creates NOTHING — the promise the row is about — and only the second sentinel and the target's name are lost. It is batchCreateIssues' L-batchcreate-notfound on the single create, and it retires the same way: an upstream code that distinguishes the absent-target refusal and carries the target. A missing --parent target already retired out of this row: failCreateIssue's errors.As(&parentNotFound) arm answers it with a distinguishing 404 not_found that names the target, and the client maps that to issueops.ErrNotFound (see TestServedCreateRefusesAnAbsentParentAsNotFound) — the row now covers only dependency and waits-for targets | D8 row 16 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-create-prefix | degrade | — | an unforced explicit id outside the workspace's configured prefix refuses as issueops.ErrValidation rather than as storage.ErrPrefixMismatch | the wire spells that refusal as a 400 invalid_argument with `param: "id"` and `reason: invalid_value` (internal/httpapi's failCreateIssue), which is the SAME pair a malformed or oversized `id` earns — so nothing on the wire tells the two apart, and reconstructing the typed sentinel from the pair would misclassify every other refusal of that member. The guard itself is untouched: the id is refused, nothing is created, and the detail names `force_id_prefix` as the bypass, which is the recovery a caller needs. What is lost is the errors.Is arm both local front doors use to decide whether to re-offer the create with --force. Upstream ask: a prefix_mismatch code, or a reason that distinguishes it, which retires this row | D8 row 16 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-apply-snapshot | degrade | — | every ItemResult of a batch apply comes back with Issue nil, where a local backend hydrates a post-item snapshot | the WIRE result is lean by the document's own decision and the role's leaf says why: ApplyItemResult carries ids, `changed` and `revision` and no issue, because the Go contract carries the snapshot for its COMPLETION HOOKS — which hand a script the row they are telling it about — and hooks never fire on the http surface at all. A hundred hydrated issues with their labels and edges would be a response an order of magnitude larger than the request that produced it. What a caller loses is a read it can make: the ids ARE published, per item and through Keys, so the rows are one getIssue away and the plan's next step is composed from ids rather than from snapshots. It is a degradation rather than a refusal because nothing about the WRITE differs — every item landed exactly as asked — and refusing would make the whole operation unavailable over http to keep a member no consumer on this surface can use | D8 refuse-not-drop (result half) | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-apply-ref | degrade | — | an unresolvable metadata_refs key comes back as a *RefError naming the MEMBER rather than the key, and the reconstructed error replaces the server's problem envelope | the wire's 400 names the offending member in `param` — `items[3].create.metadata_refs` — and carries the item index, the item's key and `declared_later`, but not WHICH entry of the refs map failed: the role's RefError.Member is diagnostic prose (`metadata_ref <key>`) rather than a vocabulary, so the server maps it onto the document's own member names instead of publishing it. The two ADDRESSING refs, target and source, are named exactly. The envelope is dropped because issueops.RefError has nowhere to put it: its Unwrap is hardcoded to ErrValidation and it carries no member for a cause, which is the role type's shape rather than a choice made here. The discriminator a caller ACTS on — an ordering mistake against a typo — survives whole, in both polarities. Upstream ask: a typed ref-key member on the problem document, which retires this row | D8 refuse-not-drop (result half) | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-comment-author | degrade | — | a comment's AUTHOR is subject to the server's own actor rule, which no local leg applies: it is stored TRIMMED where a local backend stores it verbatim, and one carrying a control character is refused (issueops.ErrValidation) where a local backend stores it | the operation validates `author` with the `actor` rules whole (internal/httpapi's validateNameMember: trim, refuse empty, refuse past 256 bytes or 255 characters, refuse any control rune) and passes the TRIMMED value on to the role, while issueops.ValidateAddCommentRequest checks only that the field is non-empty and stores what it was given. So the same request produces a different STORED VALUE on the two legs, and a value one leg stores the other refuses. IT IS THE SERVER'S RULE AND THE DOCUMENT PUBLISHES IT, which is why this is a ledger row rather than a bug on either side: the schema states the trim and the character rule in as many words, and the reason is the column — `author` is 255 characters wide and every renderer of the thread prints it, where an unfiltered C1 introducer is an escape-sequence payload. The refusal half is a NARROWING the wire makes on purpose. THE CLIENT DOES NOT ANTICIPATE EITHER HALF, and that is the decision this row records. Trimming here would make the client agree with the server about the stored value and disagree with the role's own contract — and it would silently rewrite a caller's request, which is the one thing this seam never does. Refusing the control rune here would be a second copy of a server rule that is free to move. So the value travels as the caller wrote it and the server's answer is reported unchanged, which keeps the divergence visible instead of laundering it. IT IS A DEGRADE RATHER THAN A REFUSE because the ordinary path PROCEEDS: a well-formed author is stored, and the difference cannot be misread as a wider or narrower answer — a comment lands on the thread the caller named either way. The refusal half is the SERVER's, not this client's refuse-not-drop, which is what KindRefuse classifies. What a caller loses is an author whose surrounding space survives, and the recovery is the one the role's own contract already implies: compose the author from a value you would be willing to see printed. Upstream ask: either the role trimming its own author on every leg, or the operation storing it verbatim — the rows agree the day the two rules become one | D8 row 19 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-release-notclaimed | degrade | — | a release of a row that holds NO CLAIM answers issueops.ErrNotReleasable rather than issueops.ErrNotClaimed; a status that will not accept a release answers ErrNotReleasable as it does everywhere | the role splits the two — ErrNotClaimed for a row nobody holds, ErrNotReleasable for a status the transition is not defined over — and the wire spells BOTH `not_releasable` under one code, with no member telling them apart. That is the server's deliberate choice (internal/httpapi's CodeNotReleasable) rather than an omission, and its detail names both conditions instead of guessing between them. So this client maps to the WIDER of the two, which is the only honest read: reconstructing ErrNotClaimed would assert a fact about the row that the wire never sent, and scraping the detail for it would bind a sentinel to prose. NOTHING ELSE ABOUT THE REFUSAL MOVES — nothing is written, the row and its version are untouched, and the conditional path is unaffected: a caller that named a holder gets ErrAssigneeMismatch on both sides, because that refusal has a code of its own. The caller who loses something is the one that told 'I already released this' from 'the row was never claimed', and the recovery is the one the server's own detail prescribes: READ THE ROW rather than retrying blind. Upstream ask: a code, or a member, that distinguishes the unheld row from the unreleasable status — which retires this row | D8 (Releaser), D9 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-release-notowner | degrade | — | an unforced, unconditional release by an actor that is NOT the holder answers issueops.ErrAlreadyClaimed — carrying *issueops.ClaimConflictError — rather than issueops.ErrNotOwner | the wire answers the ownership fence with `already_claimed`, which is the code updateIssue already gives the same situation (a live foreign owner refusing a write, with a force bypass and a name-the-holder bypass), and this client maps that code to the sentinel every other operation means by it. The two sentinels are distinct values in issueops and neither wraps the other, so the arm a caller writes differs. REPORTING IT AS ErrNotOwner WOULD BE THE WORSE TRADE, not merely a different one: the code is shared with the claim refusals, so a client that special-cased it for this operation would be reading the OPERATION to decide the sentinel rather than the code — and would then answer ErrNotOwner for a genuine already_claimed the day the server reuses the code here for anything else. WHAT SURVIVES IS EVERYTHING A CALLER ACTS ON: the refusal is typed, it names the row (the request supplied the id the wire leaves out), nothing is written, and BOTH bypasses answer exactly as the role says — force releases the foreign claim, and naming the holder in expected_assignee releases it too, because a match replaces the fence. The wire deliberately sends no `assignee` member here, so the holder is not named: absence means 're-read the row', never 'nobody holds it'. Upstream ask: a code, or a member, that separates the release's fence from a claim conflict — which retires this row | D8 (Releaser), D9 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-config-bounds | degrade | — | a setting VALUE past types.MaxTextBytes bytes, and a setting KEY past types.MaxFieldLen characters on the WRITE, are refused with issueops.ErrValidation naming the member; on a local leg the same request reaches the column and fails with the engine's own `too large for column` error, which is no sentinel at all | the bound belongs to the OPERATION rather than to the role: internal/httpapi's settingWriteKey and settingValue check both before the role is called, because a request the caller could have fixed should be a 400 naming the member rather than the 500 a column overflow would otherwise produce. workapi.ValidateSettingWrite — the rule every leg shares — applies no length bound at all, so below the wire the column is the only check there is. MEASURED, not inferred: a 65536-byte value answers `400 invalid_argument: \`value\` is 65536 bytes; storage holds at most 65535` over http and `Error 1105: string ... is too large for column 'value'` on the embedded leg, and a 306-character key splits the same way. Exactly 65535 bytes is accepted on both. THIS CLIENT RESTATES NEITHER BOUND, and that is the decision this row records. They are the SERVER's policy on a value whose shape the role accepted, one release away from moving, so a second copy here would either drift or refuse a request a newer server would take — the same argument L-comment-author makes about the author rule, and the same posture. What travels back is the operation's own 400, which the problem mapper turns into ErrValidation. IT IS A DEGRADE RATHER THAN A REFUSE because the ordinary path PROCEEDS and because the divergence runs in the CALLER'S FAVOR: over http an oversized write is a typed, member-named refusal that wrote nothing, where a local leg hands back a driver error no caller can classify. What a caller loses is nothing; what a caller must not assume is that a value a local workspace stored will store here. THE TWO BOUNDS ARE NOT SYMMETRIC ACROSS THE VERBS, and the asymmetry is the operation's: DELETE checks only that the key names something, so removing a 306-character key succeeds over http exactly as it does locally. Upstream ask: the length rules moving onto the shared validator, which retires this row by making the two legs one | D8 row 11, D9 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-update-fieldlen | degrade | — | an updateIssue patch member past types.MaxFieldLen characters — a label on any of the three label members, `title`, `external_ref` — is refused with issueops.ErrValidation naming the member; on a local leg the same request answers types.ErrFieldTooLong | the bound is applied TWICE and identically: internal/httpapi/update.go checks types.CheckFieldLen at the edge before the role is called, and internal/storage/issueops applies the same function below it. So this is a classification divergence and not a policy one — a value one leg stores the other stores, and a value one leg refuses the other refuses. WHAT COARSENS IT is the spelling: the operation refuses with `invalid_argument` and reason `invalid_value` (internal/httpapi's refuse on the patch member), which is the SAME pair a malformed status, an unparseable timestamp or any other bad value on the same member earns. Nothing on the wire tells them apart, so reconstructing ErrFieldTooLong from the pair would misclassify every other refusal of that member — the argument L-create-prefix makes about the id, on the patch. MEASURED, not inferred: a 256-character label answers `400 invalid_argument: \`add_labels[0]\` is 256 characters; storage holds at most 255` over http and ErrFieldTooLong through the reference store's own Lifecycle role, and exactly 255 characters is accepted on both. THIS CLIENT RESTATES THE BOUND NOWHERE, and the reason differs from L-config-bounds': not that the rule is the server's to move, but that a second copy of a rule two layers already apply is a third place for it to drift. What travels back is the operation's own 400. IT IS A DEGRADE RATHER THAN A REFUSE because the path PROCEEDS and the outcome is identical on both legs — the request fails, the row is untouched, and no truncated value is stored — while the detail names the offending member and its length, which is the recovery a caller needs. What is lost is the errors.Is arm a caller writes to tell 'too long' from 'malformed'. Upstream ask: a `too_long` reason, or a code of its own, which retires this row | D8 row 16, D9 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L-events-paging | degrade | — | an UNCAPPED journal read (limit 0) is served as a loop of handler-sized requests rather than one, so its rows and its head no longer come from a single instant; a bounded read is one request and is unaffected | the role imposes no ceiling of its own — journalops.Journal says a limit of 0 means uncapped, because the caller that pages a hundred thousand records out to a file is as legitimate as the one polling for ten — and the OPERATION refuses `limit=0` by value, capping a page at 10000 (internal/httpapi's maxEventsLimit). That cap is the handler's promise to its clients rather than a narrowing of the role, and this client is on the other side of it. SO THE LOOP IS THE ONLY HONEST READING. Refusing an uncapped read would refuse something the role permits; capping one silently at 10000 would answer a partial page beside a head saying there is more, which is a consumer stalling on a gap nobody told it about. Both are worse than N transactions. WHAT SURVIVES IS WHAT A CONSUMER ACTS ON: rows stay contiguous and seq-ascending, because each page continues exactly where the last ended; the head is the LAST page's, so it is the freshest and can only be at or ahead of the last row served; and a truncation on any page is the whole read's failure, never a shorter answer — a loop that returned the prefix it had already gathered would answer a gap with a plausible-looking suffix, which is the one failure a replay feed must never ship. WHAT DOES NOT SURVIVE is atomicity across the whole answer: a mutation committing mid-loop appears in a later page of the SAME call rather than in the next one. A consumer cannot observe that as a gap or a duplicate — it reads as records it would have received on its next poll, arriving early — which is why this is a degrade rather than a refusal. IT IS A DEGRADE RATHER THAN A REFUSE for the ordinary reason too: the path proceeds, and the answer cannot be misread as narrower or wider than the caller asked for. Upstream ask: an unlimited spelling on the operation, or a cursor the page can hand back — either retires this row | D8 (Journal), D9 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| L13 | degrade | — | pretty `bd ready` shows no parent-epic context | buildParentEpicMap swallows the GetDependencyRecordsForIssues refusal into a nil map; the retirement path is an anchored listDependencies plus per-parent getIssue | D9 L13, D4 | TODO(S3): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it |
| L14 | degrade | — | against a server that does NOT advertise issues.claimNext, the composed ReadyClaimer leaves three residues: the ready-at-fetch/claim-at-dial window, a false empty under contention after the bounded refetch, and a claimed row whose CARDINALITIES are as of the listing rather than of the claiming transaction | claimIssue validates claimability, not readiness, so a listing plus a claim is not the local role's one transaction and cannot be made into one. THE ROW IS NARROWER THAN IT WAS. Upstream published POST /v0/beads/issues:claimNext (#5510) and client wave ga-jpywb dials it, so on any server that advertises the token NONE of these three residues exists: selection, the compare-and-set and the hydration share the server's own transaction, an empty front is a 200 with `claimed` absent rather than a lost-races error, and the counts describe the state the claim produced. The whole ReadyClaimer contract tier runs against that leg with nothing parked, which is the measurement that says the residues were the COMPOSITION's rather than the wire's. WHAT KEEPS THE ROW ALIVE is the DOWN-LEVEL leg, which survives on purpose: `bd ready --claim` worked against pre-#5510 servers before this port, and refusing it now would be a regression dressed as progress. It is the posture BatchCloser takes toward issues.batchClose, and it is why this row describes shipped behavior rather than history. The third residue is stated in its IMPLEMENTED form, which is not the one the design anticipated: the design expected a follow-up getIssue to hydrate the counts, and therefore a read that could fail AFTER the claim was durable. The composition takes the counts from the ready page it already fetched instead, so that failure mode does not exist — a claim changes no dependency, dependent or comment count, and what is left is staleness bounded by the same fetch-to-dial window residue (a) already owns. Retirement is no longer an upstream ask but a fleet fact: the row goes when no server this client may meet is older than #5510 | D9 L14, D8 row 4 | 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 |
| L15 | degrade | — | a --max-rows cap can fire over http on a query whose Limit is at or under the cap, on the `bd list` legs that still walk | locally the effective SQL LIMIT is min(Limit, MaxRows+1), so a window at or under the cap can never exceed it; over http a walk to exhaustion fetches far more than the window and the cap deliberately bounds WIRE ROWS FETCHED — safety wins over exit-code parity on exactly the unbounded walk the cap exists to bound. NARROWED by the same pushdown that narrowed L2: the pushdown leg asks for min(limit, MaxRows+1) rows in one request, which IS the local expression, so a cap at or above the limit can no longer fire there and a request that used to exit 2 now answers. That is a convergence toward the contract, and it is observable — the same command changes from a refusal to a page. THE NARROWING IS SCOPED TO THE ORDERS SQL CAN EXPRESS, and that scope is a correctness bound rather than an optimization left on the table. For a GO-SIDE sort — sqlbuild.IsGoSideSort, today `--sort id`, which needs the natural-numeric comparison (bd-9 before bd-10) no ORDER BY renders — workapi.SQLLimit pushes 0 down instead of the limit, so LOCALLY the window is MaxRows+1 whatever the limit is and the cap fires on the overage even under a limit at or below it. min(limit, MaxRows+1) is therefore NOT the local expression there, and a request bounded by the limit cannot see the overage at all. walkIssues' gate keeps a capped Go-side sort on the walk, where fetching MaxRows+1 wire rows reproduces that unbounded local window exactly and raises the same refusal — so on this one shape the walk leg is the CONVERGENT one and pushing down would have been the divergence. What keeps the row live is the walk legs (unlimited reads, keyset positions, down-level servers), where the old accounting is unchanged and correct, and `bd ready`, which has no pushdown at all | D9 L15, D12 | 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 |
| L16 | refuse | `--file` | `bd dep add --file` carrying more than 100 edges refuses, naming the wire bound; it is never chunked | maxAddDependencyEdges = 100 (internal/httpapi/dependency_edit.go); chunking is the one path that silently breaks the request's one-transaction/one-history-entry contract, where naive forwarding at least fails loudly | D9 L16, D7, D8 row 18 | 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 |
| L-close-cap | refuse | — | a batch close naming more than 100 items refuses, naming the wire bound; it is never chunked | maxBatchCloseItems = 100 (internal/httpapi/batch_close.go); the item cap bounds how long one request may hold a write transaction. Chunking is the one path that silently breaks the request's one-transaction/one-history-entry contract — the same reason L16 refuses a bulk dependency add rather than splitting it — so a larger list refuses and the caller splits it, each request atomic on its own | D9 L-close-cap, D7 F-close, D8 row 17 | 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 |
| L-dep-endpoint | degrade | — | a dependency add whose source or target names no issue refuses as ErrValidation over http, not as *DependencyEndpointNotFoundError wrapping ErrDependencySourceNotFound or ErrDependencyTargetNotFound | the wire spells that refusal as a 400 invalid_argument with reason `invalid_value` and the offending member in `param` (internal/httpapi/dependency_edit.go). Reason and code are the same ones a malformed id earns, so the two are indistinguishable without reading `detail` prose — which is exactly what the extension-member vocabulary exists to avoid. The refusal still FAILS the request and still writes nothing; only its classification is coarser. Upstream ask: a distinguishing code or reason for the endpoint-not-found refusal, which retires this row | D8 row 18 | 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 |
| L-claim-prose | degrade | — | a claim refusal's MESSAGE does not carry the ClaimedBy/NotClaimableStatus fragments, so beads.ParseClaimConflict recovers nothing from it over http | the fragments exist so that parser can recover the conflicting assignee and status from PROSE. Over the wire both arrive as typed extension members and *ClaimConflictError is reconstructed whole, so a caller reading the FIELDS loses nothing. Recomposing the copy client-side would mean re-implementing which copy each refusal shape gets — an open issue held by someone else deliberately omits the assignee tail, an in-progress one carries it — which is a second implementation of the very rule the fragments were introduced to keep single | D8 row 3 | 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 |
| L-delete-notfound | degrade | — | issueops.Deleter.Delete over http refuses an absent id as issueops.ErrNotFound, not as *NotFoundError naming WHICH ids did not resolve | the role's error is a typo report and names every missing id; the wire deliberately does not repeat them (internal/httpapi's NotFound() carries a FIXED detail, so a 404 body cannot echo caller input back). The refusal still FAILS the request and still deletes NOTHING — not even the ids beside the typo — so the all-or-nothing promise is intact and only the classification is coarser. It is stated at the ROLE rather than at a command because `bd delete` is not reachable against an http workspace at all (see httpUnconsumedCapabilities); the embedder holding the role is the audience. Upstream ask: an ids extension member on the not_found problem, which retires this row | D8 row 13 | 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 |
| L-delete-dependents | degrade | — | the unforced dependents guard refuses as issueops.ErrValidation, not as *DependentsOutsideRequestError wrapping ErrDependentsOutsideRequest | the wire spells that refusal as a 400 invalid_argument with no `param` (internal/httpapi's failDeleteErr) — the fix is to change the REQUEST, by sending cascade or force — so the blocked id and its dependents cannot be reconstructed without parsing detail prose, which is what the extension-member vocabulary exists to avoid. The guard itself is untouched: the request fails and the graph is whole. Upstream ask: a dependents_outside_request code carrying issue_id and dependents, which retires this row | D8 row 13 | 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 |
| L-delete-bound | refuse | — | issueops.Deleter.Delete refuses a request naming more than 1000 ids, citing the wire bound; it is never split across requests | maxDeleteIDs = 1000 (internal/httpapi/delete.go). Splitting is the one path that silently breaks the request's one-transaction, one-history-entry contract — and it would ask the dependents guard about half a request at a time, so a pair the caller deliberately listed together would be refused as an outside dependent. Naive forwarding at least fails loudly. Stated at the ROLE: `bd delete` cannot reach an http workspace, so the embedder is the audience | D8 row 13, D9 L16 (the same argument, on the other bulk write) | 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 |
| L-batchcreate-bound | refuse | — | `bd create --file` carrying more than 100 issues refuses, naming the wire bound; it is never split across requests | maxBatchCreateItems = 100 (internal/httpapi/batch_create.go). The request IS the transaction, so two requests are two transactions and two history entries where the role promises one — and a failure in the second leaves half a plan created, which is the outcome all-or-nothing exists to make impossible | D8 row 14, D9 L16 | 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 |
| L-edgecount-bound | refuse | — | issueops.GraphCounter.CountEdges refuses a request naming more than 100 DISTINCT anchors, citing the wire bound; it is never chunked across requests | maxDependencyAnchors = 100 (internal/httpapi/edges.go), the same bound the stored-edge read on this collection carries — the role deliberately sets none of its own and says the bound belongs to the WIRE. Chunking is what a READ could get away with and this one cannot: CountEdges promises that an anchor's EXISTENCE and its edge count are read from one consistent view, so two requests would let an anchor be reported missing by a probe that raced a create the other chunk's count already saw — one answer contradicting itself, which is the exact failure AnchorEdgeCount.Missing exists to make impossible. Refusing at the bound fails loudly instead, and the caller splits the question knowing it asked twice. Upstream ask: a cursor or a higher bound on the anchor list, which retires this row | D9 L16 (the same argument, on a read), D8 | 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 |
| L-cycles-tracks | refuse | `DetectCyclesRequest.IncludeTracks` | issueops.CycleDetector.DetectCycles refuses a request with IncludeTracks set, rather than silently answering the narrower (tracks-excluded) walk | listDependencyCycles (wire.OpListDependencyCycles) publishes no include_tracks parameter at all — there is no wire member to widen the walk onto, not merely one this client chose not to send. Honoring the request field anyway (by just not sending it, the way a dropped filter would) would answer the DEFAULT walk to a caller who explicitly asked for the wider one that also follows `tracks` edges: a narrower answer with no error, exactly the failure mode ErrUnsupported exists to make loud instead of silent (see its own doc). Upstream ask: an include_tracks query parameter on listDependencyCycles, which retires this row | D8 (refuse-not-drop), D9 L16 (the same argument, on a read) | 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 |
| L-batchcreate-target | degrade | — | a batch create whose edge target names no issue refuses as issueops.ErrValidation alone, not as ErrValidation WRAPPING ErrNotFound | the wire answers a dangling edge target with a 400 invalid_argument naming `items` (internal/httpapi's failBatchCreate), and deliberately does not quote the role's own message, which arrives as a driver error naming tables and constraints. The refusal still fails the whole batch and creates nothing — the promise the row is about — and only the second sentinel is lost. Upstream ask: a distinguishing code for the absent-target refusal | D8 row 14 | 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 |
| L-batchcreate-inbatch | refuse | — | an edge onto an EARLIER ITEM OF THE SAME BATCH cannot be expressed at all over http | the capability needs the earlier item to have named an id for itself, and apigen.BatchCreateItem publishes no id member — an explicit id is refused with the rest of W-BatchCreateItem.Issue. So the target of an in-batch edge can only be a row the workspace already holds. It is a REFUSE row rather than a degrade because the request that asks for it fails: the client refuses the explicit id before the dial, and there is no second spelling that would land the edge silently. The wire's own `target_id` description names this case, so the gap is in the SCHEMA rather than in the handler — the upstream ask is an item id member, which retires this row | D8 row 14 | 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 |
| L18 | degrade | — | DOWN-LEVEL ONLY: against a server that does not advertise issues.batchClose, a single-id `bd close` still composes onto closeIssue and records the SERVER's own close commit message rather than the batch's id-naming entry; the multi-id and --claim-next shapes refuse there | the composed leg is one closeIssue call, so the history entry it leaves is the one that operation writes for itself — the batch's entry names the ids it closed and this one cannot, because no batch ran. Where issues.batchClose IS advertised the whole request is one call and one server-side transaction, so this divergence does not arise at all; the down-level leg survives on purpose, because `bd close` worked against pre-batchClose servers before this port and refusing it now would be a regression dressed as progress. It is the same posture L14 takes toward issues.claimNext. It is a degrade rather than a refuse because the close LANDS and the answer is neither narrower nor wider than the caller asked for — only the record of it is the operation's rather than the batch's. Retirement is a fleet fact rather than an upstream ask: the row goes when no server this client may meet is older than issues.batchClose | D9 L18, D8 row 17 | 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 |
| L-create-notfound | degrade | — | a create whose dependency or waits-for target names no row refuses as issueops.ErrValidation ALONE — not as ErrValidation wrapping ErrNotFound — and does not name the target | the wire answers a dangling target with a 400 invalid_argument naming `dependencies` and a FIXED detail (internal/httpapi's failCreateIssue), which deliberately does not quote the role's own message: that message arrives as a driver error naming tables and constraints, and 4xx details on this surface reflect the caller's own input back rather than server internals. The refusal still fails the whole request and creates NOTHING — the promise the row is about — and only the second sentinel and the target's name are lost. It is batchCreateIssues' L-batchcreate-notfound on the single create, and it retires the same way: an upstream code that distinguishes the absent-target refusal and carries the target. A missing --parent target stays on this row beside dependency and waits-for targets, not ahead of them: OpCreateIssue's problem-code table documents NO 404 for ANY edge target on purpose (internal/httpapi/problem.go) — there is no id in the path for parent_id to have missed any more than dependencies[i].target_id or waits_for.spawner_id has, so carving a parent-only not_found out of this row would contradict that design rather than follow it. A prior draft of this row and its pin (TestServedCreateRefusesAnAbsentParentAsNotFound) described that carve-out as already shipped; it never was, and the S3 review that found the drift retired the draft rather than the design | D8 row 16 | 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 |
| L-create-prefix | degrade | — | an unforced explicit id outside the workspace's configured prefix refuses as issueops.ErrValidation rather than as storage.ErrPrefixMismatch | the wire spells that refusal as a 400 invalid_argument with `param: "id"` and `reason: invalid_value` (internal/httpapi's failCreateIssue), which is the SAME pair a malformed or oversized `id` earns — so nothing on the wire tells the two apart, and reconstructing the typed sentinel from the pair would misclassify every other refusal of that member. The guard itself is untouched: the id is refused, nothing is created, and the detail names `force_id_prefix` as the bypass, which is the recovery a caller needs. What is lost is the errors.Is arm both local front doors use to decide whether to re-offer the create with --force. Upstream ask: a prefix_mismatch code, or a reason that distinguishes it, which retires this row | D8 row 16 | 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 |
| L-apply-snapshot | degrade | — | every ItemResult of a batch apply comes back with Issue nil, where a local backend hydrates a post-item snapshot | the WIRE result is lean by the document's own decision and the role's leaf says why: ApplyItemResult carries ids, `changed` and `revision` and no issue, because the Go contract carries the snapshot for its COMPLETION HOOKS — which hand a script the row they are telling it about — and hooks never fire on the http surface at all. A hundred hydrated issues with their labels and edges would be a response an order of magnitude larger than the request that produced it. What a caller loses is a read it can make: the ids ARE published, per item and through Keys, so the rows are one getIssue away and the plan's next step is composed from ids rather than from snapshots. It is a degradation rather than a refusal because nothing about the WRITE differs — every item landed exactly as asked — and refusing would make the whole operation unavailable over http to keep a member no consumer on this surface can use | D8 refuse-not-drop (result half) | 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 |
| L-apply-ref | degrade | — | an unresolvable metadata_refs key comes back as a *RefError naming the MEMBER rather than the key, and the reconstructed error replaces the server's problem envelope | the wire's 400 names the offending member in `param` — `items[3].create.metadata_refs` — and carries the item index, the item's key and `declared_later`, but not WHICH entry of the refs map failed: the role's RefError.Member is diagnostic prose (`metadata_ref <key>`) rather than a vocabulary, so the server maps it onto the document's own member names instead of publishing it. The two ADDRESSING refs, target and source, are named exactly. The envelope is dropped because issueops.RefError has nowhere to put it: its Unwrap is hardcoded to ErrValidation and it carries no member for a cause, which is the role type's shape rather than a choice made here. The discriminator a caller ACTS on — an ordering mistake against a typo — survives whole, in both polarities. Upstream ask: a typed ref-key member on the problem document, which retires this row | D8 refuse-not-drop (result half) | 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 |
| L-comment-author | degrade | — | a comment's AUTHOR is subject to the server's own actor rule, which no local leg applies: it is stored TRIMMED where a local backend stores it verbatim, and one carrying a control character is refused (issueops.ErrValidation) where a local backend stores it | the operation validates `author` with the `actor` rules whole (internal/httpapi's validateNameMember: trim, refuse empty, refuse past 256 bytes or 255 characters, refuse any control rune) and passes the TRIMMED value on to the role, while issueops.ValidateAddCommentRequest checks only that the field is non-empty and stores what it was given. So the same request produces a different STORED VALUE on the two legs, and a value one leg stores the other refuses. IT IS THE SERVER'S RULE AND THE DOCUMENT PUBLISHES IT, which is why this is a ledger row rather than a bug on either side: the schema states the trim and the character rule in as many words, and the reason is the column — `author` is 255 characters wide and every renderer of the thread prints it, where an unfiltered C1 introducer is an escape-sequence payload. The refusal half is a NARROWING the wire makes on purpose. THE CLIENT DOES NOT ANTICIPATE EITHER HALF, and that is the decision this row records. Trimming here would make the client agree with the server about the stored value and disagree with the role's own contract — and it would silently rewrite a caller's request, which is the one thing this seam never does. Refusing the control rune here would be a second copy of a server rule that is free to move. So the value travels as the caller wrote it and the server's answer is reported unchanged, which keeps the divergence visible instead of laundering it. IT IS A DEGRADE RATHER THAN A REFUSE because the ordinary path PROCEEDS: a well-formed author is stored, and the difference cannot be misread as a wider or narrower answer — a comment lands on the thread the caller named either way. The refusal half is the SERVER's, not this client's refuse-not-drop, which is what KindRefuse classifies. What a caller loses is an author whose surrounding space survives, and the recovery is the one the role's own contract already implies: compose the author from a value you would be willing to see printed. Upstream ask: either the role trimming its own author on every leg, or the operation storing it verbatim — the rows agree the day the two rules become one | D8 row 19 | 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 |
| L-release-notclaimed | degrade | — | a release of a row that holds NO CLAIM answers issueops.ErrNotReleasable rather than issueops.ErrNotClaimed; a status that will not accept a release answers ErrNotReleasable as it does everywhere | the role splits the two — ErrNotClaimed for a row nobody holds, ErrNotReleasable for a status the transition is not defined over — and the wire spells BOTH `not_releasable` under one code, with no member telling them apart. That is the server's deliberate choice (internal/httpapi's CodeNotReleasable) rather than an omission, and its detail names both conditions instead of guessing between them. So this client maps to the WIDER of the two, which is the only honest read: reconstructing ErrNotClaimed would assert a fact about the row that the wire never sent, and scraping the detail for it would bind a sentinel to prose. NOTHING ELSE ABOUT THE REFUSAL MOVES — nothing is written, the row and its version are untouched, and the conditional path is unaffected: a caller that named a holder gets ErrAssigneeMismatch on both sides, because that refusal has a code of its own. The caller who loses something is the one that told 'I already released this' from 'the row was never claimed', and the recovery is the one the server's own detail prescribes: READ THE ROW rather than retrying blind. Upstream ask: a code, or a member, that distinguishes the unheld row from the unreleasable status — which retires this row | D8 (Releaser), D9 | 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 |
| L-release-notowner | degrade | — | an unforced, unconditional release by an actor that is NOT the holder answers issueops.ErrAlreadyClaimed — carrying *issueops.ClaimConflictError — rather than issueops.ErrNotOwner | the wire answers the ownership fence with `already_claimed`, which is the code updateIssue already gives the same situation (a live foreign owner refusing a write, with a force bypass and a name-the-holder bypass), and this client maps that code to the sentinel every other operation means by it. The two sentinels are distinct values in issueops and neither wraps the other, so the arm a caller writes differs. REPORTING IT AS ErrNotOwner WOULD BE THE WORSE TRADE, not merely a different one: the code is shared with the claim refusals, so a client that special-cased it for this operation would be reading the OPERATION to decide the sentinel rather than the code — and would then answer ErrNotOwner for a genuine already_claimed the day the server reuses the code here for anything else. WHAT SURVIVES IS EVERYTHING A CALLER ACTS ON: the refusal is typed, it names the row (the request supplied the id the wire leaves out), nothing is written, and BOTH bypasses answer exactly as the role says — force releases the foreign claim, and naming the holder in expected_assignee releases it too, because a match replaces the fence. The wire deliberately sends no `assignee` member here, so the holder is not named: absence means 're-read the row', never 'nobody holds it'. Upstream ask: a code, or a member, that separates the release's fence from a claim conflict — which retires this row | D8 (Releaser), D9 | 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 |
| L-config-bounds | degrade | — | a setting VALUE past types.MaxTextBytes bytes, and a setting KEY past types.MaxFieldLen characters on the WRITE, are refused with issueops.ErrValidation naming the member; on a local leg the same request reaches the column and fails with the engine's own `too large for column` error, which is no sentinel at all | the bound belongs to the OPERATION rather than to the role: internal/httpapi's settingWriteKey and settingValue check both before the role is called, because a request the caller could have fixed should be a 400 naming the member rather than the 500 a column overflow would otherwise produce. workapi.ValidateSettingWrite — the rule every leg shares — applies no length bound at all, so below the wire the column is the only check there is. MEASURED, not inferred: a 65536-byte value answers `400 invalid_argument: \`value\` is 65536 bytes; storage holds at most 65535` over http and `Error 1105: string ... is too large for column 'value'` on the embedded leg, and a 306-character key splits the same way. Exactly 65535 bytes is accepted on both. THIS CLIENT RESTATES NEITHER BOUND, and that is the decision this row records. They are the SERVER's policy on a value whose shape the role accepted, one release away from moving, so a second copy here would either drift or refuse a request a newer server would take — the same argument L-comment-author makes about the author rule, and the same posture. What travels back is the operation's own 400, which the problem mapper turns into ErrValidation. IT IS A DEGRADE RATHER THAN A REFUSE because the ordinary path PROCEEDS and because the divergence runs in the CALLER'S FAVOR: over http an oversized write is a typed, member-named refusal that wrote nothing, where a local leg hands back a driver error no caller can classify. What a caller loses is nothing; what a caller must not assume is that a value a local workspace stored will store here. THE TWO BOUNDS ARE NOT SYMMETRIC ACROSS THE VERBS, and the asymmetry is the operation's: DELETE checks only that the key names something, so removing a 306-character key succeeds over http exactly as it does locally. Upstream ask: the length rules moving onto the shared validator, which retires this row by making the two legs one | D8 row 11, D9 | 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 |
| L-update-fieldlen | degrade | — | an updateIssue patch member past types.MaxFieldLen characters — a label on any of the three label members, `title`, `external_ref` — is refused with issueops.ErrValidation naming the member; on a local leg the same request answers types.ErrFieldTooLong | the bound is applied TWICE and identically: internal/httpapi/update.go checks types.CheckFieldLen at the edge before the role is called, and internal/storage/issueops applies the same function below it. So this is a classification divergence and not a policy one — a value one leg stores the other stores, and a value one leg refuses the other refuses. WHAT COARSENS IT is the spelling: the operation refuses with `invalid_argument` and reason `invalid_value` (internal/httpapi's refuse on the patch member), which is the SAME pair a malformed status, an unparseable timestamp or any other bad value on the same member earns. Nothing on the wire tells them apart, so reconstructing ErrFieldTooLong from the pair would misclassify every other refusal of that member — the argument L-create-prefix makes about the id, on the patch. MEASURED, not inferred: a 256-character label answers `400 invalid_argument: \`add_labels[0]\` is 256 characters; storage holds at most 255` over http and ErrFieldTooLong through the reference store's own Lifecycle role, and exactly 255 characters is accepted on both. THIS CLIENT RESTATES THE BOUND NOWHERE, and the reason differs from L-config-bounds': not that the rule is the server's to move, but that a second copy of a rule two layers already apply is a third place for it to drift. What travels back is the operation's own 400. IT IS A DEGRADE RATHER THAN A REFUSE because the path PROCEEDS and the outcome is identical on both legs — the request fails, the row is untouched, and no truncated value is stored — while the detail names the offending member and its length, which is the recovery a caller needs. What is lost is the errors.Is arm a caller writes to tell 'too long' from 'malformed'. Upstream ask: a `too_long` reason, or a code of its own, which retires this row | D8 row 16, D9 | 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 |
| L-events-paging | degrade | — | an UNCAPPED journal read (limit 0) is served as a loop of handler-sized requests rather than one, so its rows and its head no longer come from a single instant; a bounded read is one request and is unaffected | the role imposes no ceiling of its own — journalops.Journal says a limit of 0 means uncapped, because the caller that pages a hundred thousand records out to a file is as legitimate as the one polling for ten — and the OPERATION refuses `limit=0` by value, capping a page at 10000 (internal/httpapi's maxEventsLimit). That cap is the handler's promise to its clients rather than a narrowing of the role, and this client is on the other side of it. SO THE LOOP IS THE ONLY HONEST READING. Refusing an uncapped read would refuse something the role permits; capping one silently at 10000 would answer a partial page beside a head saying there is more, which is a consumer stalling on a gap nobody told it about. Both are worse than N transactions. WHAT SURVIVES IS WHAT A CONSUMER ACTS ON: rows stay contiguous and seq-ascending, because each page continues exactly where the last ended; the head is the LAST page's, so it is the freshest and can only be at or ahead of the last row served; and a truncation on any page is the whole read's failure, never a shorter answer — a loop that returned the prefix it had already gathered would answer a gap with a plausible-looking suffix, which is the one failure a replay feed must never ship. WHAT DOES NOT SURVIVE is atomicity across the whole answer: a mutation committing mid-loop appears in a later page of the SAME call rather than in the next one. A consumer cannot observe that as a gap or a duplicate — it reads as records it would have received on its next poll, arriving early — which is why this is a degrade rather than a refusal. IT IS A DEGRADE RATHER THAN A REFUSE for the ordinary reason too: the path proceeds, and the answer cannot be misread as narrower or wider than the caller asked for. Upstream ask: an unlimited spelling on the operation, or a cursor the page can hand back — either retires this row | D8 (Journal), D9 | 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 |
## Write-side refuse-not-drop (D8)
@ -99,40 +100,46 @@ Role-request fields on the served writes that the v0 wire publishes no member fo
| ID | Kind | Field / flag | Divergence | Why | Spec | Pinned test |
|---|---|---|---|---|---|---|
| W-UpdateRequest.Claim | refuse | `UpdateRequest.Claim` | a claim combined with any other UpdateRequest member refuses; a claim ALONE does not — it dials claimIssue directly (see httpLifecycle.claimOnlyUpdate) | a claim is claimIssue's own operation and updateIssue cannot perform one, on this wire or on any other; it is the one row here that upstream #5484 did not touch. claimIssue's own request is the actor alone, so a claim-only UpdateRequest IS that request and is served through the Claimer role instead of refusing — that is gc's exclusive claim path, `bd update <id> --claim --json`. What still refuses is PATCH claim: a claim folded into one atomic transaction WITH a patch, a guard or a force override, which no operation on this wire publishes and which is not synthesized as two calls (claimIssue then updateIssue), since that would let a caller observe an issue claimed but not yet patched. Upstream gastownhall/beads#6890 tracks the capability that would carry both in one call | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-ClaimRequest.Wisp | refuse | — | claiming a wisp is not supported over http | the v0 wire's claim operation excludes the wisp plane on every backend; claim this issue from a local workspace instead | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.ForceAssigneeTransfer | refuse | `UpdateRequest.ForceAssigneeTransfer` `--force` | bypassing the anti-steal assignee fence refuses | the wire publishes `force_assignee_transfer` (upstream #5484) and this client does not send it. What the refusal STANDS ON changed with client wave ga-7i6by and the row is narrower for it: the `assignee` the fence guards IS now sent (W-IssuePatch.Assignee), so what is left is the bypass alone. The fence itself is unbypassable rather than absent — a transfer away from a live foreign in-progress owner refuses with already_claimed, and a matched `expected_assignee` is the OTHER bypass, which this client does send. Carrying this one is a two-member port tracked as ga-2ltro.15 | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.ForceClosePolicy | refuse | `UpdateRequest.ForceClosePolicy` `--force` | bypassing close policy on a status-crossing update refuses | the wire publishes `force_close_policy` (upstream #5484) and this client does not send it; see W-UpdateRequest.ForceAssigneeTransfer for what the refusal now stands on, since client wave ga-7i6by sends the `status` whose crossing the policy gates. The policy is therefore enforced and not bypassable here: a status crossing into the done category with open children or a live blocker refuses with not_closable, typed, and writes nothing. Tracked as ga-2ltro.15 | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.ExpectedVersion | retired | — | the compare-and-set row-version precondition used to refuse | RETIRED by the client wave that sends it (ga-jbuyf). The refusal was always the CLIENT's rather than the document's — upstream #5484 published `expected_version` and this client had not been taught to emit it — and the row said so in as many words: 'flipping it is a port, not a decision: send the member, retire this row, and turn the refusal pin into a round-trip pin'. That is what happened. The member is now sent as a POINTER, so absent stays absent: 0 is a legal token (the migration-0054 backfill left rows holding it) and encoding 'no guard' as 0 would have armed a guard on every unguarded update. The pin below asserts the round trip in both directions | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.ExpectedAssignee | retired | — | the compare-and-set assignee precondition used to refuse | RETIRED with W-UpdateRequest.ExpectedVersion (ga-jbuyf). Its own trap is the mirror image of that one's: the EMPTY assignee is a real guard — it is how a caller says 'only if nobody holds it' — so this member cannot be omitted when it is empty either. A pointer expresses both, and the pin drives the empty-string guard as its own case | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.ExpectedStatus | retired | — | the compare-and-set status precondition used to refuse | RETIRED with W-UpdateRequest.ExpectedVersion (ga-jbuyf). The status guard is the readable one — `Issue.status` is on every read of this surface, so a caller can guard a transition with no token at all — and it is sent as the workspace's own status vocabulary, verbatim | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.IssuePlaneOnly | refuse | `UpdateRequest.IssuePlaneOnly` | restricting an update to the issue plane refuses | updateIssue publishes no plane restriction and the server's role auto-resolves both planes, so dropping the flag would EDIT the wisp the caller asked to be told did not exist — the widening refuse-not-drop exists to stop. Not in the design's own enumeration: the page lists the UpdateRequest members it had reviewed, and this one was found while wiring the role | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.Provenance | refuse | `UpdateRequest.Provenance` | labeling an update's history entry refuses | updateIssue publishes no provenance member and the server writes its own label, so a dropped Provenance would leave the history entry naming the SERVER's surface while the caller believed it named theirs. It is refused rather than degraded because the field's whole purpose is the label, so dropping it drops the request | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CloseRequest.ExpectedVersion | retired | — | the compare-and-set row-version precondition on a close used to refuse | RETIRED by the client wave that sends it (ga-jbuyf). CloseIssueRequest publishes expected_version (upstream #5506) and this client now emits it, so the guard reaches the server rather than refusing here — and the ordering the role promises, that the precondition is checked BEFORE the idempotent re-close, is the server's to keep and the served tier's to assert | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-ReopenRequest.ExpectedVersion | retired | — | the compare-and-set row-version precondition on a reopen used to refuse | RETIRED with W-CloseRequest.ExpectedVersion (ga-jbuyf). The design's enumeration named the close half only, and the reopen half is the same field on the same verb pair — it retires the same way | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-DeleteRequest.ExpectedVersion | retired | — | the compare-and-delete row-version precondition used to refuse | RETIRED with W-CloseRequest.ExpectedVersion (ga-jbuyf), and it is the one whose stakes made the refusal worth having: dropping this guard erases a row the caller had asked not to erase, with nothing left to compare afterwards. The multi-id refusal the wire attaches to it is deliberately NOT anticipated client-side: distinctness is measured after trimming and collapsing duplicates, which is the normalization this role sends its ids verbatim to avoid re-implementing | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-ReopenRequest.Provenance | refuse | `ReopenRequest.Provenance` | labeling a reopen's history entry refuses | reopenIssue publishes no provenance member and the server writes its own fixed label (`bd serve: reopen issue`); see W-UpdateRequest.Provenance | D8 refuse-not-drop, D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-AddDependenciesRequest.SkipPerEdgeCycleCheck | refuse | `AddDependenciesRequest.SkipPerEdgeCycleCheck` `--no-cycle-check` | `bd dep add --no-cycle-check` refuses on the bulk --file path | the wire deliberately leaves SkipPerEdgeCycleCheck UNPUBLISHED and therefore false (internal/httpapi/dependency_edit.go). The single-edge spelling forwards false and only gates the post-hoc cycle warning, which the wire-backed CycleDetector serves, so it is served-with-note rather than refused | D7, D8 row 18, D9 L16 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.Status | retired | — | `bd update -s` used to refuse | RETIRED with client wave ga-7i6by. IssuePatchBody published `status` with upstream #5484 and this client's encoder now emits it; close and reopen still carry the lifecycle semantics a status write has nowhere to put — the reason and session under first-close-wins, the done-status normalization, the already-closed idempotence flag — and stay the operations to reach for. What this member serves is the status moved ALONGSIDE other fields in one transaction, which is the thing two calls cannot do | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.Assignee | retired | — | assignment and unassignment through update used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). The EMPTY STRING is the half that makes this member more than a rename: it UNASSIGNS, so a client that skipped an empty value would turn a real edit into no edit at all. The anti-steal fence around it is the server's and is unchanged — a transfer away from a live foreign in-progress owner still refuses with already_claimed, and the two bypasses (`force_assignee_transfer` and a matched `expected_assignee`) are W-UpdateRequest.ForceAssigneeTransfer and the guard wave's own | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.Metadata | retired | — | a metadata patch used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). IssuePatchBody publishes the same replace/merge/set/unset algebra MetadataPatch carries, member for member, so the client projects it rather than translating it and the ordering rule — merge, then set in key order, then unset, with replace refusing beside the other three — stays the ROLE's, applied by the same body a local workspace runs. The CLEAR is the one state the wire's own struct cannot spell (`omitempty` omits it), which is why the document is built as a map and an empty replacement travels as the empty document. The compare-and-set door is a different question and is served by its own accessor (issues.casMetadata, ga-7i6by's other half) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.SpecID | refuse | `IssuePatch.SpecID` | a spec-id edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes spec_id (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.AwaitID | refuse | `IssuePatch.AwaitID` | an await-id edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes await_id (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.Owner | refuse | `IssuePatch.Owner` | an owner edit refuses ON updateIssue | IssuePatchBody excludes owner — which the document itself calls an accident of order rather than a decision, since ApplyPatchBody DOES publish it and issues:batchApply's update item carries it (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.ClosedBySession | refuse | `IssuePatch.ClosedBySession` | a closed-by-session edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes closed_by_session (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.Persistence | refuse | `IssuePatch.Persistence` | a persistence-mode edit refuses | neither body publishes persistence: moving a row between planes mid-plan is a different act from writing its fields (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-IssuePatch.ParentID | retired | — | a parent re-hang through update used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). It is ONE call rather than a remove-then-add pair, which is the whole reason the member exists: the two-call spelling leaves the issue parentless if the second call fails, and dependencies:add/remove — still the general write side of the graph over this wire — cannot express the atomic replacement. The empty string removes every parent-child edge, so it travels like `assignee`'s empty string rather than being skipped. The graph refusals it earns are the server's and arrive typed: a cycle through the issue's own descendant as the PLAIN dependency_cycle, and an existing edge of another type as dependency_exists | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateBatchRequest.Provenance | refuse | `CreateBatchRequest.Provenance` | labeling a batch create's history entry refuses | batchCreateIssues publishes actor and items only, and the server writes its own label; see W-UpdateRequest.Provenance. It is the one Provenance whose ABSENCE is visible in shipped history — the surface this role serves has always named its source file in the entry (`bd: create 3 issue(s) from plan.md`) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateBatchRequest.ForceIDPrefix | refuse | `CreateBatchRequest.ForceIDPrefix` `--force` | permitting explicit ids outside the workspace's configured prefix refuses | the wire publishes no such member — and could not honor one, since it publishes no explicit id for the flag to permit (W-BatchCreateItem.Issue). Dropping it would answer a request about WHERE ids may be written with a batch whose ids the server chose | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-BatchCreateItem.Issue | refuse | `BatchCreateItem.Issue` | an item whose Issue populates any member outside the wire's eight refuses, naming the member | apigen.BatchCreateItem carries title, description, design, acceptance_criteria, priority, issue_type, assignee and labels and nothing else, while the role accepts far more of a types.Issue: an explicit id, the wisp flags, metadata, the storage class, every timestamp, the gate/molecule/event fields. ONE row rather than one per member because the reason is one reason — the wire's item vocabulary — and forty rows repeating it would say nothing a reader does not learn here. Exhaustiveness is held by REFLECTION instead: the client's carried and role-ignored tables are checked against types.Issue field by field, so a member added upstream is refused the day it lands rather than dropped until someone notices. The members the role ITSELF ignores on a create (ContentHash, RowVersion, lease, compaction, routing overrides, hydration flags) are not in this population and are not refused: a local create drops them too | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateDependency.Reverse | refuse | `CreateDependency.Reverse` | an edge written from the target back to the new issue refuses ON A BATCH CREATE | BatchCreateDependency carries target_id and type only; dropping Reverse would write the edge in the OPPOSITE direction from the one asked for, which is a different graph. createIssue's CreateIssueDependency DOES publish it, and the single-create path sends it (internal/httpapi/spec BatchCreateDependency) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateDependency.Metadata | refuse | `CreateDependency.Metadata` | typed edge metadata refuses ON A BATCH CREATE | BatchCreateDependency publishes no metadata member, and a waits-for gate whose metadata was dropped is a readiness rule that silently does not hold. createIssue's edge publishes it, and the single-create path sends it verbatim (internal/httpapi/spec BatchCreateDependency) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateDependency.ThreadID | refuse | `CreateDependency.ThreadID` | associating an edge with a discussion thread refuses | neither BatchCreateDependency nor CreateIssueDependency publishes a thread member (internal/httpapi/spec BatchCreateDependency) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateRequest.IDPrefix | refuse | `CreateRequest.IDPrefix` | overriding the prefix an explicit id is checked against refuses | createIssue publishes no `id_prefix`, and the omission is the SERVER's decision rather than a gap (internal/httpapi/create.go): the field exists because a workspace's own config.yaml prefix wins over the database's and only a local front door can read that file, so a remote caller's config.yaml describes a workspace this server does not serve. Publishing it would let a caller override the served workspace's prefix rule from outside it. Dropping it instead would check the id against the SERVER's prefix while the caller believed it was checked against theirs — the same request, two different answers to 'may this workspace mint this id' | D8 row 16 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateRequest.Issue | refuse | `CreateRequest.Issue` | a create whose Issue populates any member outside the wire's twenty refuses, naming the member | createIssue publishes the whole create VOCABULARY — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue: the creation stamp (created_at, created_by), because a caller-supplied creation time makes the row disagree with the journal entry that records it and re-dating history is what an import is for; and spec_id, await_*, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface publishes on no operation, read or write. ONE row rather than one per member for W-BatchCreateItem.Issue's reason — the reason is one reason — and exhaustiveness is held by the same REFLECTION over types.Issue, sharing the role-ignored table with the batch so the two operations cannot disagree about what the ROLE drops. Issue.Comments and Issue.Dependencies are not in this population: the role itself refuses them, so a local create fails too and this is validation rather than divergence | D8 row 16 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-CreateItem.Issue | refuse | `CreateItem.Issue` | a create ITEM whose Issue populates any member outside the wire's twenty refuses, naming the member | ApplyCreateItem publishes exactly createIssue's create vocabulary — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue, for the reasons W-CreateRequest.Issue gives in full. It is a row of its OWN rather than a citation of that one because the operations are different: a caller auditing why their PLAN refuses must not be sent to a row about a single create, and the two can diverge the day either vocabulary moves. The partition itself is SHARED — one carried table, one role-ignored table, held against types.Issue by the same reflection — so they cannot disagree about what the wire carries or about what the role drops. Issue.Comments and Issue.Dependencies are not in this population and are refused as validation on both sides: edges in this role are ITEMS, so a create item has nowhere to put one 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 S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-ApplyPatch.ParentID | refuse | `IssuePatch.ParentID` | a parent re-hang inside an update ITEM refuses, where the same member serves on updateIssue | ApplyPatchBody deliberately publishes no parent_id, and the absence is this operation's ONE-EDGE-ONE-SPELLING rule rather than a gap: a parent is a dep_add item of type parent-child, so the ORDER of every edge in a plan stays total and there is exactly one place an edge is written. The single patch has no ordering to express and publishes the member directly (W-IssuePatch.ParentID, retired by client wave ga-7i6by), which is why the same Go field is carried by one document and refused by the other. Refusing is not a loss of capability, only of spelling: a plan re-hangs a parent with a dep_add item, which is the atomic replacement in the position the caller declared it | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 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 S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| W-UpdateRequest.Claim | retired | `UpdateRequest.Claim` | a claim combined with a patch, a guard or a force override used to refuse | RETIRED by the #7247 review port. The refusal stood on 'updateIssue cannot perform a claim, on this wire or on any other' — and upstream gastownhall/beads#6890, the capability the row itself named, had already published `claim` on updateIssue: the claim and the patch applied by the same role in one transaction, so PATCH claim was the server's shape and only this client's refusal. The body now sends `claim` as a pointer set true only on request, so a claim alone, a claim with a patch and a claim with a version guard are each ONE updateIssue call, answered with the post-write `revision` like every other update. The claimIssue route survives as the fallback for a claim ALONE against a server that predates the member, which refuses it as an unknown parameter before any database work; a combination against such a server returns that skew refusal rather than splitting into two calls | D8 refuse-not-drop, D7 | 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-ClaimRequest.Wisp | refuse | — | claiming a wisp is not supported by this bd serve | the server predates claiming through its update operation, and its separate claim operation excludes the wisp plane; upgrade bd serve, or claim this issue from a local workspace | D8 refuse-not-drop, D7 | 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-UpdateRequest.ForceAssigneeTransfer | retired | `UpdateRequest.ForceAssigneeTransfer` `--force` | bypassing the anti-steal assignee fence used to refuse | RETIRED by the #7247 review port, the two-member port ga-2ltro.15 named. The wire publishes `force_assignee_transfer` (upstream #5484) and the refusal was always this client's: client wave ga-7i6by had already narrowed it to the bypass alone by sending the `assignee` the fence guards, and issues:batchApply's update item already carried the same flag. The body now sends it as a pointer set true only on request. The fence itself is unchanged — a transfer away from a live foreign in-progress owner refuses with already_claimed unless one of the two bypasses rides with it, this one or a matched `expected_assignee` — and the server refuses the bypass without a `patch.assignee` or beside `expected_assignee` or `claim` | D8 refuse-not-drop, D7 | 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-UpdateRequest.ForceClosePolicy | retired | `UpdateRequest.ForceClosePolicy` `--force` | bypassing close policy on a status-crossing update used to refuse | RETIRED with W-UpdateRequest.ForceAssigneeTransfer, the other half of ga-2ltro.15's port. The wire publishes `force_close_policy` (upstream #5484), client wave ga-7i6by sends the `status` whose crossing the policy gates, and issues:batchApply's update item already carried the flag. The body now sends it as a pointer set true only on request; unforced, a status crossing into the done category with open children or a live blocker still refuses with not_closable, typed, and writes nothing | D8 refuse-not-drop, D7 | 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-UpdateRequest.ForceNotesOverwrite | retired | `UpdateRequest.ForceNotesOverwrite` | bypassing the notes-overwrite fence on a single update used to refuse | RETIRED by the S3 reconciliation that found it (2026-10). It was discovered refused on the single-patch updateIssue path while the identical flag was already carried on issues:batchApply's update item (W table entry applyBatch/item/update) — the same trio member, wired on one shape and not the other with no decision on record for the gap. Flipping it was a port, not a decision, same as W-UpdateRequest.ExpectedVersion's: the body now sends `force_notes_overwrite` as a pointer set true only on request, so a Patch.Notes that would replace existing non-empty notes with different non-empty content is bypassable here exactly as it already was on the batch path | D8 refuse-not-drop, D7 | 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-UpdateRequest.ExpectedVersion | retired | — | the compare-and-set row-version precondition used to refuse | RETIRED by the client wave that sends it (ga-jbuyf). The refusal was always the CLIENT's rather than the document's — upstream #5484 published `expected_version` and this client had not been taught to emit it — and the row said so in as many words: 'flipping it is a port, not a decision: send the member, retire this row, and turn the refusal pin into a round-trip pin'. That is what happened. The member is now sent as a POINTER, so absent stays absent: 0 is a legal token (the migration-0054 backfill left rows holding it) and encoding 'no guard' as 0 would have armed a guard on every unguarded update. The pin below asserts the round trip in both directions | D8 refuse-not-drop, D7 | 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-UpdateRequest.ExpectedAssignee | retired | — | the compare-and-set assignee precondition used to refuse | RETIRED with W-UpdateRequest.ExpectedVersion (ga-jbuyf). Its own trap is the mirror image of that one's: the EMPTY assignee is a real guard — it is how a caller says 'only if nobody holds it' — so this member cannot be omitted when it is empty either. A pointer expresses both, and the pin drives the empty-string guard as its own case | D8 refuse-not-drop, D7 | 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-UpdateRequest.ExpectedStatus | retired | — | the compare-and-set status precondition used to refuse | RETIRED with W-UpdateRequest.ExpectedVersion (ga-jbuyf). The status guard is the readable one — `Issue.status` is on every read of this surface, so a caller can guard a transition with no token at all — and it is sent as the workspace's own status vocabulary, verbatim | D8 refuse-not-drop, D7 | 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-UpdateRequest.IssuePlaneOnly | refuse | `UpdateRequest.IssuePlaneOnly` | restricting an update to the issue plane refuses | updateIssue publishes no plane restriction and the server's role auto-resolves both planes, so dropping the flag would EDIT the wisp the caller asked to be told did not exist — the widening refuse-not-drop exists to stop. Not in the design's own enumeration: the page lists the UpdateRequest members it had reviewed, and this one was found while wiring the role | D8 refuse-not-drop, D7 | 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-UpdateRequest.Provenance | refuse | `UpdateRequest.Provenance` | labeling an update's history entry refuses | updateIssue publishes no provenance member and the server writes its own label, so a dropped Provenance would leave the history entry naming the SERVER's surface while the caller believed it named theirs. It is refused rather than degraded because the field's whole purpose is the label, so dropping it drops the request | D8 refuse-not-drop, D7 | 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-CloseRequest.ExpectedVersion | retired | — | the compare-and-set row-version precondition on a close used to refuse | RETIRED by the client wave that sends it (ga-jbuyf). CloseIssueRequest publishes expected_version (upstream #5506) and this client now emits it, so the guard reaches the server rather than refusing here — and the ordering the role promises, that the precondition is checked BEFORE the idempotent re-close, is the server's to keep and the served tier's to assert | D8 refuse-not-drop, D7 | 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-ReopenRequest.ExpectedVersion | retired | — | the compare-and-set row-version precondition on a reopen used to refuse | RETIRED with W-CloseRequest.ExpectedVersion (ga-jbuyf). The design's enumeration named the close half only, and the reopen half is the same field on the same verb pair — it retires the same way | D8 refuse-not-drop, D7 | 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-DeleteRequest.ExpectedVersion | retired | — | the compare-and-delete row-version precondition used to refuse | RETIRED with W-CloseRequest.ExpectedVersion (ga-jbuyf), and it is the one whose stakes made the refusal worth having: dropping this guard erases a row the caller had asked not to erase, with nothing left to compare afterwards. The multi-id refusal the wire attaches to it is deliberately NOT anticipated client-side: distinctness is measured after trimming and collapsing duplicates, which is the normalization this role sends its ids verbatim to avoid re-implementing | D8 refuse-not-drop, D7 | 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-ReopenRequest.Provenance | refuse | `ReopenRequest.Provenance` | labeling a reopen's history entry refuses | reopenIssue publishes no provenance member and the server writes its own fixed label (`bd serve: reopen issue`); see W-UpdateRequest.Provenance | D8 refuse-not-drop, D7 | 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-AddDependenciesRequest.SkipPerEdgeCycleCheck | refuse | `AddDependenciesRequest.SkipPerEdgeCycleCheck` `--no-cycle-check` | `bd dep add --no-cycle-check` refuses on the bulk --file path | the wire deliberately leaves SkipPerEdgeCycleCheck UNPUBLISHED and therefore false (internal/httpapi/dependency_edit.go). The single-edge spelling forwards false and only gates the post-hoc cycle warning, which the wire-backed CycleDetector serves, so it is served-with-note rather than refused | D7, D8 row 18, D9 L16 | 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.Status | retired | — | `bd update -s` used to refuse | RETIRED with client wave ga-7i6by. IssuePatchBody published `status` with upstream #5484 and this client's encoder now emits it; close and reopen still carry the lifecycle semantics a status write has nowhere to put — the reason and session under first-close-wins, the done-status normalization, the already-closed idempotence flag — and stay the operations to reach for. What this member serves is the status moved ALONGSIDE other fields in one transaction, which is the thing two calls cannot do | 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.Assignee | retired | — | assignment and unassignment through update used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). The EMPTY STRING is the half that makes this member more than a rename: it UNASSIGNS, so a client that skipped an empty value would turn a real edit into no edit at all. The anti-steal fence around it is the server's and is unchanged — a transfer away from a live foreign in-progress owner still refuses with already_claimed, and the two bypasses (`force_assignee_transfer` and a matched `expected_assignee`) are both sent — the first since W-UpdateRequest.ForceAssigneeTransfer retired, the second since the guard wave | 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.Metadata | retired | — | a metadata patch used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). IssuePatchBody publishes the same replace/merge/set/unset algebra MetadataPatch carries, member for member, so the client projects it rather than translating it and the ordering rule — merge, then set in key order, then unset, with replace refusing beside the other three — stays the ROLE's, applied by the same body a local workspace runs. The CLEAR is the one state the wire's own struct cannot spell (`omitempty` omits it), which is why the document is built as a map and an empty replacement travels as the empty document. The compare-and-set door is a different question and is served by its own accessor (issues.casMetadata, ga-7i6by's other half) | 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.SpecID | refuse | `IssuePatch.SpecID` | a spec-id edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes spec_id (internal/httpapi/update.go issuePatchMembers) | 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.AwaitID | refuse | `IssuePatch.AwaitID` | an await-id edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes await_id (internal/httpapi/update.go issuePatchMembers) | 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.Owner | refuse | `IssuePatch.Owner` | an owner edit refuses ON updateIssue | IssuePatchBody excludes owner — which the document itself calls an accident of order rather than a decision, since ApplyPatchBody DOES publish it and issues:batchApply's update item carries it (internal/httpapi/update.go issuePatchMembers) | 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.ClosedBySession | refuse | `IssuePatch.ClosedBySession` | a closed-by-session edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes closed_by_session (internal/httpapi/update.go issuePatchMembers) | 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.Persistence | refuse | `IssuePatch.Persistence` | a persistence-mode edit refuses | neither body publishes persistence: moving a row between planes mid-plan is a different act from writing its fields (internal/httpapi/update.go issuePatchMembers) | 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.ParentID | retired | — | a parent re-hang through update used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). It is ONE call rather than a remove-then-add pair, which is the whole reason the member exists: the two-call spelling leaves the issue parentless if the second call fails, and dependencies:add/remove — still the general write side of the graph over this wire — cannot express the atomic replacement. The empty string removes every parent-child edge, so it travels like `assignee`'s empty string rather than being skipped. The graph refusals it earns are the server's and arrive typed: a cycle through the issue's own descendant as the PLAIN dependency_cycle, and an existing edge of another type as dependency_exists | 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-CreateBatchRequest.Provenance | refuse | `CreateBatchRequest.Provenance` | labeling a batch create's history entry refuses | batchCreateIssues publishes actor and items only, and the server writes its own label; see W-UpdateRequest.Provenance. It is the one Provenance whose ABSENCE is visible in shipped history — the surface this role serves has always named its source file in the entry (`bd: create 3 issue(s) from plan.md`) | D8 row 14 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-CreateBatchRequest.ForceIDPrefix | refuse | `CreateBatchRequest.ForceIDPrefix` `--force` | permitting explicit ids outside the workspace's configured prefix refuses | the wire publishes no such member — and could not honor one, since it publishes no explicit id for the flag to permit (W-BatchCreateItem.Issue). Dropping it would answer a request about WHERE ids may be written with a batch whose ids the server chose | D8 row 14 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-BatchCreateItem.Issue | refuse | `BatchCreateItem.Issue` | an item whose Issue populates any member outside the wire's eight refuses, naming the member | apigen.BatchCreateItem carries title, description, design, acceptance_criteria, priority, issue_type, assignee and labels and nothing else, while the role accepts far more of a types.Issue: an explicit id, the wisp flags, metadata, the storage class, every timestamp, the gate/molecule/event fields. ONE row rather than one per member because the reason is one reason — the wire's item vocabulary — and forty rows repeating it would say nothing a reader does not learn here. Exhaustiveness is held by REFLECTION instead: the client's carried and role-ignored tables are checked against types.Issue field by field, so a member added upstream is refused the day it lands rather than dropped until someone notices. The members the role ITSELF ignores on a create (ContentHash, RowVersion, lease, compaction, routing overrides, hydration flags) are not in this population and are not refused: a local create drops them too. Nor is a CreatedBy that names the request's actor: the server stamps every item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses | D8 row 14 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-CreateDependency.Reverse | refuse | `CreateDependency.Reverse` | an edge written from the target back to the new issue refuses ON A BATCH CREATE | BatchCreateDependency carries target_id and type only; dropping Reverse would write the edge in the OPPOSITE direction from the one asked for, which is a different graph. createIssue's CreateIssueDependency DOES publish it, and the single-create path sends it (internal/httpapi/spec BatchCreateDependency) | D8 row 14 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-CreateDependency.Metadata | refuse | `CreateDependency.Metadata` | typed edge metadata refuses ON A BATCH CREATE | BatchCreateDependency publishes no metadata member, and a waits-for gate whose metadata was dropped is a readiness rule that silently does not hold. createIssue's edge publishes it, and the single-create path sends it verbatim (internal/httpapi/spec BatchCreateDependency) | D8 row 14 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-CreateDependency.ThreadID | refuse | `CreateDependency.ThreadID` | associating an edge with a discussion thread refuses | neither BatchCreateDependency nor CreateIssueDependency publishes a thread member (internal/httpapi/spec BatchCreateDependency) | D8 row 14 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-CreateRequest.IDPrefix | refuse | `CreateRequest.IDPrefix` | overriding the prefix an explicit, unforced id is checked against refuses | createIssue publishes no `id_prefix`, and the omission is the SERVER's decision rather than a gap (internal/httpapi/create.go): the field exists because a workspace's own config.yaml prefix wins over the database's and only a local front door can read that file, so a remote caller's config.yaml describes a workspace this server does not serve. Publishing it would let a caller override the served workspace's prefix rule from outside it. Dropping it instead would check the id against the SERVER's prefix while the caller believed it was checked against theirs — the same request, two different answers to 'may this workspace mint this id'. It refuses only where it would ACT: the role reads the override for nothing but an explicit id it was not told to force, so a create that mints its id, or sets ForceIDPrefix, is the same request with or without it and is sent without it. That matters because `bd create` sends the workspace's prefix on EVERY create, so an unconditional refusal would refuse every create in a workspace whose config.yaml names one | D8 row 16 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-CreateRequest.Issue | refuse | `CreateRequest.Issue` | a create whose Issue populates any member outside the wire's twenty refuses, naming the member | createIssue publishes the whole create VOCABULARY — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue: the creation time (created_at), because a caller-supplied creation time makes the row disagree with the journal entry that records it and re-dating history is what an import is for; and spec_id, await_*, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface publishes on no operation, read or write. ONE row rather than one per member for W-BatchCreateItem.Issue's reason — the reason is one reason — and exhaustiveness is held by the same REFLECTION over types.Issue, sharing the role-ignored table with the batch so the two operations cannot disagree about what the ROLE drops. Issue.Comments and Issue.Dependencies are not in this population: the role itself refuses them, so a local create fails too and this is validation rather than divergence. created_by is published on no create shape either, but every one of them STAMPS it from the request's actor (internal/httpapi's create.go, batch_create.go and batch_apply.go) — the local front doors' own rule, since the role copies the member rather than stamping it. So a CreatedBy that names the actor, which is what every CLI create sends, arrives as written, and only one naming someone else refuses: the stamp would silently replace it. A server that predates the stamp stores an empty created_by for that one member | D8 row 16 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-CreateItem.Issue | refuse | `CreateItem.Issue` | a create ITEM whose Issue populates any member outside the wire's twenty refuses, naming the member | ApplyCreateItem publishes exactly createIssue's create vocabulary — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue, for the reasons W-CreateRequest.Issue gives in full. It is a row of its OWN rather than a citation of that one because the operations are different: a caller auditing why their PLAN refuses must not be sent to a row about a single create, and the two can diverge the day either vocabulary moves. The partition itself is SHARED — one carried table, one role-ignored table, held against types.Issue by the same reflection — so they cannot disagree about what the wire carries or about what the role drops. Issue.Comments and Issue.Dependencies are not in this population and are refused as validation on both sides: edges in this role are ITEMS, so a create item has nowhere to put one at all. Nor is a CreatedBy that names the request's actor: the server stamps every create item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses | 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-ApplyPatch.ParentID | refuse | `IssuePatch.ParentID` | a parent re-hang inside an update ITEM refuses, where the same member serves on updateIssue | ApplyPatchBody deliberately publishes no parent_id, and the absence is this operation's ONE-EDGE-ONE-SPELLING rule rather than a gap: a parent is a dep_add item of type parent-child, so the ORDER of every edge in a plan stays total and there is exactly one place an edge is written. The single patch has no ordering to express and publishes the member directly (W-IssuePatch.ParentID, retired by client wave ga-7i6by), which is why the same Go field is carried by one document and refused by the other. Refusing is not a loss of capability, only of spelling: a plan re-hangs a parent with a dep_add item, which is the atomic replacement in the position the caller declared it | 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-DepAddItem.HasSpawner | refuse | `DepAddItem.HasSpawner` | a waits-for edge ITEM that names its spawner refuses | ApplyDepAddItem publishes source, target, type and metadata and no spawner member, and the flag asks for a write only the ROLE can make: metadata's spawner_id, stamped from the resolved target once every id in the batch exists, because a target named by key has no id before then. Dropping the flag would store the edge's gate-only metadata, so an edge whose caller named a spawner would carry none. On every other edge type the role ignores the flag and stores the same row either way, so there it is dropped rather than refused. Upstream ask: a spawner member on ApplyDepAddItem, which retires this row | 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-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 |
## Command and flag refusals (D7)
@ -140,18 +147,18 @@ Whole commands, and the flag modes of served commands, that dispatch onto method
| ID | Kind | Field / flag | Divergence | Why | Spec | Pinned test |
|---|---|---|---|---|---|---|
| F-ready-explain | refuse | `--explain` | `bd ready --explain` refuses | it dispatches onto raw GetBlockedIssues/GetIssuesByIDs/GetDependencyCounts/DetectCycles, three of which are on the unsupported allowlist | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-ready-mol | refuse | `--mol` | `bd ready --mol` refuses | its molecule subgraph load reaches findHierarchicalChildren, an IDPrefix SearchIssues shape the parent-walk bridge cannot express (E-IssueFilter.noShape). GetDependencyRecords and GetDependentsWithMetadata, which the same load also calls, stopped being the blocker when ga-b8ddd.30 flipped them onto the wire | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-ready-gated | refuse | `--gated` | `bd ready --gated` refuses | it dispatches onto a filtered SearchIssues shape the bridge cannot express, plus GetDependents | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-show-thread | refuse | `--thread` | `bd show --thread` refuses | showMessageThread renders each reply's sender, recipient, body and timestamp off GetDependentsWithMetadata, but ga-b8ddd.30 flipped that read onto getIssue's include_dependents parameter, which carries the collectDependents SHALLOW projection (id/status/type/priority/title + edge type only, be-4d36f2). Those fields come back zeroed over http and zero-timestamp replies sort ahead of the root — a silent-wrong degrade the refuse-over-degrade doctrine forbids. Retires with a full-dependent wire shape, a server-side ask | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-show-refs | refuse | `--refs` | `bd show --refs` refuses | showIssueRefs's --json marshals the full GetDependentsWithMetadata rows, but the wire answers the same collectDependents shallow projection, so created_at/assignee/description come back zeroed and the JSON differs from a local workspace. The text render consumes only the shallow fields, but the flag cannot be split from its --json mode, so the whole flag refuses rather than serve a divergent JSON silently | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-show-children | refuse | `--children` | `bd show --children` refuses | showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http; `bd children` refuses as a whole command for the same reason | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-mol-ready | refuse | — | `bd mol ready` refuses | it is the same runMolReadyGatedCore body as `bd ready --gated` | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-blocked | refuse | — | `bd blocked` refuses | it is raw GetBlockedIssues, which is on the unsupported allowlist | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-count | retired | — | RETIRED — `bd count` is SERVED whole | it said the command refuses because "issueops.Counter has no wire operation; a counts operation is a filed upstream ask", and that ask was DELIVERED: upstream #5508 published countIssues, client wave ga-icks1 wired the Counter accessor, and `count` moved from httpRefusedCommands into httpServedCommands. D8 row 20 and docs/reference/http-workspaces.md have said so since; this row was the last place that did not. Every flag the command publishes reaches a wire member — the whole predicate, the six instant bounds, the three emptiness checks, --include-infra, and the five --by-* flags as the one group_by parameter — so there is no refused mode left to name either. HOW IT ROTTED IS THE PART WORTH KEEPING. Its pin was TestClassifiedRefusedCommandsRefuseBeforeTheOSSPreRun, which walks httpRefusedCommands and drives every entry. The moment `count` left that table the pin stopped covering this row — it stayed LIVE BY NAME, so the well-formedness gate that resolves PinnedBy to a real test kept passing, and DEAD BY COVERAGE, so nothing anywhere asserted the row's claim. A ledger row can be false for a whole wave under a green pin, which is what TestFRowsAgreeWithTheCommandClassification now makes impossible | D7 (RETIRED), D8 row 20 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-serve | refuse | — | `bd serve` refuses against an http workspace | the OSS classifier would happily serve it from the opened store, and a bd serve re-serving a remote bd serve is a proxy chain nobody designed: run serve where the database is | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-close | refuse | — | `bd close` is SERVED whole — single id, several ids and --claim-next — over issues:batchClose; it refuses only against a DOWN-LEVEL server that does not advertise issues.batchClose | the CLI's close front door routes every id, single-id included, through BatchCloser.CloseBatch, and Lifecycle.Close has zero CLI callers at tip. The wire now carries issues:batchClose, so the whole CloseBatchRequest — multi-item and the atomic ClaimNext included — is one wire call and one server-side transaction; nothing is composed or refused where the capability is present. Against a server too old to advertise issues.batchClose, servesBatchClose() reads the handshake snapshot and routes around the batch dial entirely, so no Preflight runs and no wire.ErrCapabilityAbsent is raised: the down-level leg's refuseUnservedCloseShape raises the STORE's own *ErrHTTPUnsupported (batchcloser.go), and cmd/bd's renderEscapedHTTPRefusal turns it into the capability-absent taxonomy (case 2) by scanning the served command's own capability list for the first token the server does not advertise — issues.batchClose, which is the token it then names to upgrade to. The single-item, no-ClaimNext shape still composes onto closeIssue in that down-level leg (see L18); the shapes that cannot compose refuse there. The item cap is L-close-cap | D8 row 17 (resolved, Wire), D9 L18, D9 L-close-cap | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-partial-id | refuse | — | partial-id resolution refuses with its own taxonomy text | SearchIssueIDs has no wire operation, and the client cannot tell a partial id from a full id that does not exist — so the refusal text covers both outcomes rather than falling through to a raw search error | D11 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline |
| F-ready-explain | refuse | `--explain` | `bd ready --explain` refuses | it dispatches onto raw GetBlockedIssues/GetIssuesByIDs/GetDependencyCounts/DetectCycles, three of which are on the unsupported allowlist | D7 | 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 |
| F-ready-mol | refuse | `--mol` | `bd ready --mol` refuses | its molecule subgraph load reaches findHierarchicalChildren, an IDPrefix SearchIssues shape the parent-walk bridge cannot express (E-IssueFilter.noShape). GetDependencyRecords and GetDependentsWithMetadata, which the same load also calls, stopped being the blocker once they flipped onto the wire | D7 | 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 |
| F-ready-gated | refuse | `--gated` | `bd ready --gated` refuses | it dispatches onto a filtered SearchIssues shape the bridge cannot express, plus GetDependents | D7 | 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 |
| F-show-thread | refuse | `--thread` | `bd show --thread` refuses | showMessageThread renders each reply's sender, recipient, body and timestamp off GetDependentsWithMetadata, but that read was flipped onto getIssue's include_dependents parameter, which carries the collectDependents SHALLOW projection (id/status/type/priority/title + edge type only, be-4d36f2). Those fields come back zeroed over http and zero-timestamp replies sort ahead of the root — a silent-wrong degrade the refuse-over-degrade doctrine forbids. Retires with a full-dependent wire shape, a server-side ask | D7 | 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 |
| F-show-refs | refuse | `--refs` | `bd show --refs` refuses | showIssueRefs's --json marshals the full GetDependentsWithMetadata rows, but the wire answers the same collectDependents shallow projection, so created_at/assignee/description come back zeroed and the JSON differs from a local workspace. The text render consumes only the shallow fields, but the flag cannot be split from its --json mode, so the whole flag refuses rather than serve a divergent JSON silently | D7 | 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 |
| F-show-children | refuse | `--children` | `bd show --children` refuses | showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http; `bd children` refuses as a whole command for the same reason | D7 | 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 |
| F-mol-ready | refuse | — | `bd mol ready` refuses | it is the same runMolReadyGatedCore body as `bd ready --gated` | D7 | 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 |
| F-blocked | refuse | — | `bd blocked` refuses | it is raw GetBlockedIssues, which is on the unsupported allowlist | D7 | 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 |
| F-count | retired | — | RETIRED — `bd count` is SERVED whole | it said the command refuses because "issueops.Counter has no wire operation; a counts operation is a filed upstream ask", and that ask was DELIVERED: upstream #5508 published countIssues, client wave ga-icks1 wired the Counter accessor, and `count` moved from httpRefusedCommands into httpServedCommands. D8 row 20 and docs/reference/http-workspaces.md have said so since; this row was the last place that did not. Every flag the command publishes reaches a wire member — the whole predicate, the six instant bounds, the three emptiness checks, --include-infra, and the five --by-* flags as the one group_by parameter — so there is no refused mode left to name either. HOW IT ROTTED IS THE PART WORTH KEEPING. Its pin was TestClassifiedRefusedCommandsRefuseBeforeTheOSSPreRun, which walks httpRefusedCommands and drives every entry. The moment `count` left that table the pin stopped covering this row — it stayed LIVE BY NAME, so the well-formedness gate that resolves PinnedBy to a real test kept passing, and DEAD BY COVERAGE, so nothing anywhere asserted the row's claim. A ledger row can be false for a whole wave under a green pin, which is what TestFRowsAgreeWithTheCommandClassification now makes impossible | D7 (RETIRED), D8 row 20 | 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 |
| F-serve | refuse | — | `bd serve` refuses against an http workspace | the OSS classifier would happily serve it from the opened store, and a bd serve re-serving a remote bd serve is a proxy chain nobody designed: run serve where the database is | D7 | 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 |
| F-close | refuse | — | `bd close` is SERVED whole — single id, several ids and --claim-next — over issues:batchClose; it refuses only against a DOWN-LEVEL server that does not advertise issues.batchClose | the CLI's close front door routes every id, single-id included, through BatchCloser.CloseBatch, and Lifecycle.Close has zero CLI callers at tip. The wire now carries issues:batchClose, so the whole CloseBatchRequest — multi-item and the atomic ClaimNext included — is one wire call and one server-side transaction; nothing is composed or refused where the capability is present. Against a server too old to advertise issues.batchClose, servesBatchClose() reads the handshake snapshot and routes around the batch dial entirely, so no Preflight runs and no wire.ErrCapabilityAbsent is raised: the down-level leg's refuseUnservedCloseShape raises the STORE's own *ErrHTTPUnsupported (batchcloser.go), and cmd/bd's renderEscapedHTTPRefusal turns it into the capability-absent taxonomy (case 2) by scanning the served command's own capability list for the first token the server does not advertise — issues.batchClose, which is the token it then names to upgrade to. The single-item, no-ClaimNext shape still composes onto closeIssue in that down-level leg (see L18); the shapes that cannot compose refuse there. The item cap is L-close-cap | D8 row 17 (resolved, Wire), D9 L18, D9 L-close-cap | 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 |
| F-partial-id | refuse | — | partial-id resolution refuses with its own taxonomy text | SearchIssueIDs has no wire operation, and the client cannot tell a partial id from a full id that does not exist — so the refusal text covers both outcomes rather than falling through to a raw search error | D11 | 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 |
## Ready-request fields

View file

@ -213,6 +213,14 @@ func (s *Server) applyBatchRequest(w http.ResponseWriter, r *http.Request) (issu
if res != nil {
return refuse(res)
}
// created_by is stamped from the actor on every create item, createIssue's
// rule (create.go): the item publishes no created_by and the role copies the
// issue's rather than stamping one.
for _, item := range items {
if item.Create != nil {
item.Create.Issue.CreatedBy = actor
}
}
return issueops.ApplyBatchRequest{
Actor: actor,
Items: items,

View file

@ -144,6 +144,11 @@ func TestApplyBatchForwardsEveryLevelOfTheDocumentedBody(t *testing.T) {
if create.Issue.Priority != 1 {
t.Errorf("create.priority = %d, want 1", create.Issue.Priority)
}
// created_by is stamped from the trimmed actor, createIssue's rule: the
// role copies the issue's and never stamps one itself.
if create.Issue.CreatedBy != "alice" {
t.Errorf("create.created_by = %q, want the actor %q", create.Issue.CreatedBy, "alice")
}
if create.Issue.EstimatedMinutes == nil || *create.Issue.EstimatedMinutes != 30 {
t.Errorf("create.estimated_minutes = %v, want 30", create.Issue.EstimatedMinutes)
}

View file

@ -101,6 +101,13 @@ func (s *Server) batchCreateRequest(w http.ResponseWriter, r *http.Request) (iss
if !ok {
return issueops.CreateBatchRequest{}, false
}
// created_by is stamped from the actor on every item, createIssue's rule
// (create.go): the item publishes no created_by and the role copies the
// issue's rather than stamping one, so without this a batch-created issue
// would store none where `bd create --file` stores its actor.
for _, item := range items {
item.Issue.CreatedBy = actor
}
return issueops.CreateBatchRequest{Actor: actor, Items: items}, true
}

View file

@ -85,6 +85,13 @@ func TestBatchCreatePassesTheRequestToTheRoleAndAnswersWithWhatItCreated(t *test
if got.Items[1].Issue.Priority != 0 || got.Items[1].Issue.Description != "body" {
t.Errorf("item 1 = %+v, want the wire's description and no priority", *got.Items[1].Issue)
}
// created_by is stamped from the actor on EVERY item, createIssue's rule:
// the role copies the issue's and never stamps one itself.
for i, item := range got.Items {
if item.Issue.CreatedBy != "alice" {
t.Errorf("item %d created_by = %q, want the actor %q", i, item.Issue.CreatedBy, "alice")
}
}
// No provenance: the file name a CLI batch spells has no analogue here, so
// the entry reads as the implementation's default rather than as a lie.
if got.Provenance != "" {

View file

@ -202,6 +202,18 @@ func (s *Server) createIssueRequest(w http.ResponseWriter, r *http.Request) (iss
Sender: derefString(wire.Sender),
Ephemeral: derefBool(wire.Ephemeral),
NoHistory: derefBool(wire.NoHistory),
// CreatedBy is stamped from the caller-asserted actor, matching the
// local front door's semantics (cmd/bd/create.go sets issue.CreatedBy
// from getActorWithGit() before calling the same role): the role
// itself never stamps it, copying whatever the caller already put on
// types.Issue (internal/storage/issueops/public_create.go's
// publicCreateIssue). The wire's `actor` member is the caller-asserted
// identity this request carries — provenance for the audit trail, not
// authenticated identity, exactly as this file's own doc comment
// states above — so it is the one value this server has to make that
// stamp from. batch_create.go and batch_apply.go make the same
// stamp, so no create shape stores an empty created_by.
CreatedBy: actor,
}
if wire.Priority != nil {
issue.Priority = *wire.Priority

View file

@ -190,11 +190,17 @@ func TestCreateForwardsEveryDocumentedMember(t *testing.T) {
t.Errorf("the handler put edges or comments on the issue (%d/%d); they belong to the request's own members",
len(issue.Dependencies), len(issue.Comments))
}
// created_at/created_by are unpublished, so a fresh row must reach the role
// with both zero and take the implementation's own values.
if !issue.CreatedAt.IsZero() || issue.CreatedBy != "" {
t.Errorf("the handler set created_at/created_by (%v/%q); neither is published on this operation",
issue.CreatedAt, issue.CreatedBy)
// created_at is unpublished, so a fresh row must reach the role with it
// zero and take the implementation's own value. created_by IS stamped by
// this handler, from the same trimmed actor identity asserted above —
// matching the local front door's semantics (cmd/bd/create.go sets
// issue.CreatedBy from getActorWithGit() before calling the same role,
// because the role itself never stamps it).
if !issue.CreatedAt.IsZero() {
t.Errorf("the handler set created_at (%v); it is not published on this operation", issue.CreatedAt)
}
if issue.CreatedBy != "alice" {
t.Errorf("created_by = %q, want the actor %q", issue.CreatedBy, "alice")
}
if len(req.Dependencies) != 2 {

View file

@ -1,22 +1,77 @@
load("@rules_go//go:def.bzl", "go_library", "go_test")
load("@rules_shell//shell:sh_test.bzl", "sh_test")
go_library(
name = "httpclient",
srcs = [
"accessors.go",
"backend_credential.go",
"batchapplier.go",
"batchcloser.go",
"batchcreator.go",
"batchgetter.go",
"bridge.go",
"ca.go",
"ca_permissions_other.go",
"ca_permissions_unix.go",
"claimer.go",
"commenter.go",
"counter.go",
"credential.go",
"deleter.go",
"dependencyeditor.go",
"detail_reads.go",
"dial.go",
"dispatch.go",
"errors.go",
"journal.go",
"lifecycle.go",
"list_walk.go",
"memories.go",
"metadata.go",
"metadatacas.go",
"offrole.go",
"order.go",
"readyclaimer.go",
"refusal.go",
"register.go",
"relations.go",
"releaser.go",
"resolve.go",
"role_querier.go",
"role_reader.go",
"role_readycounter.go",
"roles_aux.go",
"roles_graph.go",
"servercontext.go",
"store.go",
"sweeper.go",
"target.go",
"target_seam.go",
"unsupported.go",
"unsupported_gen.go",
"vocabulary.go",
"watch.go",
"writewire.go",
],
importpath = "github.com/steveyegge/beads/internal/httpclient",
visibility = ["//:__subpackages__"],
deps = [
"//internal/config",
"//internal/configfile",
"//internal/creds",
"//internal/httpapi/apigen",
"//internal/httpclient/encode",
"//internal/httpclient/wire",
"//internal/storage",
"//internal/storage/backends",
"//internal/storage/issueops",
"//internal/storage/sqlbuild",
"//internal/types",
"//internal/utils",
"//issueops",
"//journalops",
"//memoryops",
"@org_golang_x_net//http/httpproxy",
"@org_golang_x_net//idna",
],
@ -24,23 +79,160 @@ go_library(
go_test(
name = "httpclient_test",
# Unsharded, this package takes ~350s under --config=ci (BEADS_TEST_SKIP=dolt, no
# BEADS_TEST_EMBEDDED_DOLT): mostly wall-clock wait on the CA tests' dialer/keep-alive
# timeouts, not CPU. The go_test default size (medium, 300s timeout) leaves no margin
# and times out intermittently; size=large/timeout=long follows the same convention as
# //internal/storage/embeddeddolt's go_test.
size = "large",
timeout = "long",
srcs = [
"backend_credential_test.go",
"batchapplier_test.go",
"brief_test.go",
"bulk_roles_test.go",
"ca_permissions_unix_test.go",
"ca_test.go",
"ca_wrong_ca_test.go",
"completeness_test.go",
"composition_test.go",
"counts_test.go",
"credential_source_test.go",
"credential_test.go",
"dial_test.go",
"dispatch_test.go",
"divergence_citation_gate_test.go",
"divergence_test.go",
"helpers_test.go",
"lifecycle_create_test.go",
"lifecycle_update_test.go",
"list_sort_test.go",
"metadatacas_test.go",
"race_detector_off_test.go",
"race_detector_on_test.go",
"required_served_tier_test.go",
"roles_graph_cycles_test.go",
"roles_test.go",
"served_batch_apply_test.go",
"served_batch_close_test.go",
"served_batch_getter_test.go",
"served_bridge_test.go",
"served_bulk_test.go",
"served_claim_lifecycle_test.go",
"served_commenter_test.go",
"served_config_test.go",
"served_config_write_test.go",
"served_counter_test.go",
"served_detail_reads_test.go",
"served_dualrun_test.go",
"served_graph_aux_test.go",
"served_graph_counter_test.go",
"served_harness_test.go",
"served_hooks_test.go",
"served_issue_operations_test.go",
"served_journal_test.go",
"served_lifecycle_create_test.go",
"served_list_test.go",
"served_memories_deps_test.go",
"served_metadata_cas_test.go",
"served_project_swap_test.go",
"served_querier_test.go",
"served_reader_test.go",
"served_ready_claimer_test.go",
"served_readycounter_test.go",
"served_relations_test.go",
"served_releaser_test.go",
"served_test.go",
"served_wrong_server_test.go",
"store_dependent_test.go",
"store_test.go",
"target_test.go",
"watch_test.go",
"wave2b_roles_test.go",
"wave2c_claimnext_test.go",
"wave2c_config_test.go",
"wave2c_journal_test.go",
"write_ledger_test.go",
"write_roles_test.go",
],
# keep
#
# TestInterfaceCompleteness (completeness_test.go) reads its own package's
# generated shell, unsupported_gen.go, by a plain relative os.ReadFile to
# regex-match the methods storage.DoltStorage's refusing shell covers. That
# file is already a `srcs` member of :httpclient above, which Bazel compiles
# away rather than leaving as a readable file in the test's sandbox; `data`
# is what actually puts a copy there, exactly as
# //internal/httpclient/encode's own go_test does for the same reason.
# Gazelle does not manage `data` on this rule, so this survives
# `make bazel-sync` (the directive just says so).
data = glob(["*.go"]),
embed = [":httpclient"],
deps = [
"//backend/conformance",
"//internal/eventsjournal",
"//internal/hooks",
"//internal/httpapi",
"//internal/httpapi/apigen",
"//internal/httpapi/spec",
"//internal/httpclient/encode",
"//internal/httpclient/wire",
"//internal/storage",
"//internal/storage/backends",
"//internal/storage/domain",
"//internal/storage/embeddeddolt",
"//internal/storage/issueops",
"//internal/storage/sqlbuild",
"//internal/types",
"//internal/workapi",
"//issueops",
"//journalops",
"//memoryops",
"@in_gopkg_yaml_v3//:yaml_v3",
],
)
# scripts/conformance.sh's Tier 3, the served HTTP corpus: the whole package
# with BEADS_TEST_EMBEDDED_DOLT=1, so the served_*_test.go cases stand a real
# `bd serve` handler over embedded Dolt instead of skipping as they do in
# httpclient_test above, and BEADS_HTTP_TEST_REQUIRED=1, so a missing engine
# fails each served case rather than skipping it. It is the script's run on
# the lane's race build (raceEnabled shrinks its one large apply).
#
# Shard count: on the lane's executors (2026-10-08) the package is 702 tests
# and ~3,700 test-seconds, the heaviest, TestServedBatchGetterContract, at
# 170-230s. rules_go deals the tests out round-robin, so the shard that draws
# it runs it plus about a 24th of the rest: 283s measured, ~370s at the slow
# end. Both are under the ~410s cmd/bd shard that sets the lane's floor (see
# bazel.yml's bazel-embedded), so this target does not lengthen the lane.
#
# Tags:
# embedded: the embedded-Dolt tier; excluded from --config=prcore/ci,
# selected by --config=embedded.
sh_test(
name = "httpclient_served_test",
size = "large",
# Deviation from the script's -timeout=40m: Bazel ends the action at
# 1200s (eternal under --config=embedded), and rules_go's wrapper ignores
# that SIGTERM, so a hang would end as a bare TIMEOUT. 19m lets Go's own
# timeout fire first and dump every goroutine to test.log.
timeout = "eternal",
srcs = ["//tools/bazel:go_test_variant.sh"],
args = [
"$(rootpath :httpclient_test)",
"-test.v",
"-test.count=1",
"-test.timeout=19m",
],
data = [":httpclient_test"],
env = {
"BEADS_HTTP_TEST_REQUIRED": "1",
"BEADS_TEST_EMBEDDED_DOLT": "1",
},
shard_count = 24,
tags = ["embedded"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(

View file

@ -0,0 +1,386 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/accessors.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"github.com/steveyegge/beads/issueops"
"github.com/steveyegge/beads/memoryops"
)
// The TWENTY-FIVE wire-backed role accessors of design D8's allowlist v1, as
// amended by the `bd close` decision that moved row 17 across, and by the
// five the client waves added after it — Counter and GraphCounter (wave 2a),
// Releaser, Commenter and IssueRelations (wave 2b). A count in prose beside a
// list in code is a count that goes stale, so read the list. They are
// off the generated refusing shell — that is what keeps them off the unsupported
// allowlist and out of RunUnsupportedContract — and hand-written here so a role
// bead flips one accessor in place, in the same PR as the method that serves it,
// without touching the generator's skip list.
//
// An accessor that has not been wired yet refuses through (*Store).unsupported,
// so it already carries the server context D7 renders, and the comment on each
// names the v0 operation that will answer it — a flip has nothing left to
// decide. A wired one returns its role bound to the store's transport; the
// implementations live one file per role, so concurrent role beads do not edit
// the same body.
//
// THREE accessors are still on the generated shell, and after client wave 2b
// they are all there for ONE reason: VersionReconciler, Bootstrapper and
// InitVerifier are PERMANENTLY UNSERVABLE — no wire operation and none coming.
//
// THE SECOND LIST IS EMPTY, and it is worth saying that it existed rather than
// deleting it silently. It held the names the wire had published ahead of this
// client — an operation complete on the server with no accessor in front of it —
// and every one of them has now left it by being WIRED: Counter (issues.count,
// #5508) and GraphCounter (dependencies.count, #5536) with client wave 2a
// (ga-icks1), then Releaser (issues.release, #5507), IssueRelations
// (issues.related, #5540) and Commenter (issues.addComment, #5594) with client
// wave 2b (ga-f352s). The next operation upstream publishes ahead of a client
// wave starts the list again, which is what it is for.
//
// "UNCONSUMED" AND "UNWIRED" ARE NOT THE SAME THING, and this comment used to
// spell them as one. A name leaves the second list when its ACCESSOR lands here;
// its entry in cmd/bd's httpUnconsumedCapabilities leaves only when a `bd`
// command reaches the role over http. Counter's went with wave 2a because
// `bd count` became served; GraphCounter's stayed, because no `bd` command
// reaches that role on ANY backend. Wave 2b splits the same way and TWO of its
// three went: Commenter's, because `bd comment` is served, and IssueRelations',
// because `bd dep list` reaches that role on every shape but the multi-anchor
// default — the command was already classified served and was failing LATE, so
// wiring the accessor turned a refusal into an answer rather than moving a row.
// Only Releaser's stayed, RESCOPED from "no accessor" to the front door it
// actually waits on.
//
// WorkspaceConfig used to be on neither list because it was PARTLY wired — its
// reads served and its two write verbs refusing — and it is now simply wired:
// #5596 published PUT and DELETE /v0/beads/config/{key} and client wave 2c
// (ga-jpywb) dials both. THE PARTIAL COLUMN IS EMPTY, for the first time since
// this file was written.
//
// READYLISTER IS NOT AN ACCESSOR HERE, and it is not a removal: this lift
// carried bd-enterprise's issueops.ReadyLister/ReadyListRequest/ReadyListing
// over from a fork where upstream had published them, and S3 reconciliation
// (2026-10) found OSS has published none of the three —
// there is no role type to implement and no accessor return type to name.
// `bd ready`'s listing is unaffected; it already runs on IssueReader. S13
// schedules the role once upstream publishes it.
// IssueReader serves listReadyWork/listIssues/getIssue (D8 row 1).
func (s *Store) IssueReader() (issueops.Reader, error) {
return httpReader{store: s}, nil
}
// ReadyCounter serves countReadyWork (D8 row 2).
func (s *Store) ReadyCounter() (issueops.ReadyCounter, error) {
return httpReadyCounter{store: s}, nil
}
// Counter serves countIssues (GET /v0/beads/issues:count) — the TWENTY-FIRST
// wire-backed accessor, and the one `bd count` routes through.
//
// Its request maps member for member: every one of CountRequest's twenty-three
// filters is a published parameter, so nothing here refuses and no ledger row
// names a member. What the operation does NOT publish is anything the ROLE does
// not have — a count's plane vocabulary is one `include_infra` where a
// listing's is five parameters, and that narrowing is upstream's design rather
// than a wire gap. See counter.go.
func (s *Store) Counter() (issueops.Counter, error) {
return httpCounter{store: s}, nil
}
// Releaser serves releaseIssue (POST /v0/beads/issues/{id}:release) — the
// TWENTY-THIRD wire-backed accessor, and the claim's inverse.
//
// Its request maps member for member and nothing refuses on shape. What the port
// had to carry instead is a fact about the ANSWER: a release leaves an ANONYMOUS
// post-state — assignee cleared, status open, started_at gone — which is the same
// row whoever emptied it, so the role cannot report an idempotent no-op the way
// Claimer does and every shape that would not write is a REFUSAL. Those refusals
// are the whole value of this accessor to a caller, so they travel whole rather
// than being softened into a quiet false.
//
// ONE OF THEM IS FLATTENED BY THE WIRE and is ledgered: `not_releasable` covers
// both "holds no claim" and "status will not accept a release", with no member
// telling them apart, so this client answers the wider of the two
// (L-release-notclaimed). See releaser.go.
func (s *Store) Releaser() (issueops.Releaser, error) {
w, err := s.roleWire("Releaser")
if err != nil {
return nil, err
}
return &httpReleaser{store: s, wire: w}, nil
}
// Commenter serves addComment (POST /v0/beads/issues/{id}/comments) — the
// TWENTY-FOURTH wire-backed accessor, and the only write here whose path names a
// SUB-RESOURCE collection rather than the issue.
//
// Three request members, one of them the path, and one result member: the
// smallest total mapping on this surface. What is worth knowing is what the role
// declines rather than what it carries — there is no comment READ here, because
// a comment page is a paging question with a cursor of its own and the wire
// publishes no such operation. The thread is read through getIssue's
// `include_comments`. See commenter.go.
func (s *Store) Commenter() (issueops.Commenter, error) {
w, err := s.roleWire("Commenter")
if err != nil {
return nil, err
}
return &httpCommenter{store: s, wire: w}, nil
}
// IssueRelations serves listRelatedIssues (GET /v0/beads/issues/{id}/related) —
// the TWENTY-FIFTH wire-backed accessor, and the first read here anchored on one
// issue in the PATH.
//
// It is the SINGLE-ANCHOR member of the graph family, which is what makes its
// miss a 404 rather than the per-anchor Missing sentinel EdgeReader and
// GraphCounter carry: one request names one id, so there is nowhere to put a
// per-anchor flag and no need for one. Both halves of the walk are two-plane and
// a wisp id is a legal anchor, all of it decided server-side.
//
// `bd dep list` IS ITS FRONT DOOR, which is easy to miss because that command
// reads as an EDGE command: the multi-anchor default shape takes the EdgeReader
// batch, and every other shape — the single anchor, and any --direction up —
// takes this role, one call per anchor. So this accessor was the difference
// between a command that was classified served and failed at dispatch, and one
// that answers. See relations.go.
func (s *Store) IssueRelations() (issueops.Relations, error) {
return httpRelations{store: s}, nil
}
// IssueClaimer serves claimIssue (D8 row 3). See claimer.go.
func (s *Store) IssueClaimer() (issueops.Claimer, error) {
w, err := s.roleWire("IssueClaimer")
if err != nil {
return nil, err
}
return &httpClaimer{store: s, wire: w}, nil
}
// ReadyClaimer serves claimNext (POST /v0/beads/issues:claimNext).
//
// IT ADDS NO ORDINAL, and the absence is the point: every accessor before it in
// this file counts itself as the Nth wire-backed one because it CROSSED the
// matrix, moving off the refusing shell in the wave that wired it. This one did
// not cross — it has been in wireBackedAccessors since the first commit, served
// by a composition — so the matrix stays at twenty-five and calling this the
// twenty-sixth would be counting a row that never moved. What changed is what
// stands behind the accessor, which is what the rest of this leaf is about.
//
// "The wire has no claimNext" was true when this leaf was written and stopped
// being true with upstream #5510. What the operation buys is not a round trip:
// it is the one transaction the composition could never have — selection, the
// compare-and-set and the hydration together — which is what makes an ephemeral
// row claimable, a lease actually written, and the returned cardinalities a
// description of the state the claim produced rather than of a listing taken
// before it.
//
// IT NAMES NO ID BECAUSE IT NAMES NO ROW: the caller asks a question and the
// server picks the answer. The filter travels as the QUERY STRING GET
// /v0/beads/ready's own decode reads — one predicate, one spelling — and the
// actor is the whole body.
//
// THE COMPOSITION SURVIVES as the down-level leg, capability-gated the way
// BatchCloser's is, so `bd ready --claim` keeps working against a server older
// than the operation. L14 is now that leg's row and not the role's. See
// readyclaimer.go.
func (s *Store) ReadyClaimer() (issueops.ReadyClaimer, error) {
w, err := s.roleWire("ReadyClaimer")
if err != nil {
return nil, err
}
return &httpReadyClaimer{store: s, wire: w}, nil
}
// Querier serves queryIssues (D8 row 5).
func (s *Store) Querier() (issueops.Querier, error) {
return httpQuerier{store: s}, nil
}
// StatsReporter serves getStats (D8 row 6). See roles_aux.go.
func (s *Store) StatsReporter() (issueops.StatsReporter, error) {
return httpStatsReporter{store: s}, nil
}
// CycleDetector serves listDependencyCycles (D8 row 7). See roles_graph.go.
func (s *Store) CycleDetector() (issueops.CycleDetector, error) {
return httpCycleDetector{store: s}, nil
}
// TreeWalker serves getDependencyTree (D8 row 8). See roles_graph.go.
func (s *Store) TreeWalker() (issueops.TreeWalker, error) {
return httpTreeWalker{store: s}, nil
}
// GraphCounter serves countDependencyEdges (GET
// /v0/beads/dependencies:count) — the TWENTY-SECOND wire-backed accessor.
//
// It is the counting sibling of EdgeReader below, on the same collection and
// under the same anchor bound, plus the direction that read does not take. Its
// mapping is total: anchors, direction, edge types and the inbound-only status
// filter are all published, and the two facts it reads back — a 64-bit count and
// the Missing sentinel — are both required members, which is what keeps a typo
// from being indistinguishable from a real zero. See roles_graph.go.
func (s *Store) GraphCounter() (issueops.GraphCounter, error) {
return httpGraphCounter{store: s}, nil
}
// EdgeReader serves listDependencies (D8 row 9). See roles_graph.go.
func (s *Store) EdgeReader() (issueops.EdgeReader, error) {
return httpEdgeReader{store: s}, nil
}
// BlockingAnnotator serves listBlockingAnnotations (D8 row 10), which is what
// keeps `bd list`'s blocked and blocks marks working. See roles_graph.go.
func (s *Store) BlockingAnnotator() (issueops.BlockingAnnotator, error) {
return httpBlockingAnnotator{store: s}, nil
}
// WorkspaceConfig serves listSettings/getSetting/setSetting/unsetSetting (D8
// row 11, no longer partial). See roles_aux.go.
//
// Its two writes are the smallest mapping on this surface — a key in the path, a
// value in the body — and they carry no actor and no guard, because this plane
// records no history entry to attribute a write on and holds no row version to
// compare. Neither is a wire narrowing: no backend attributes a config write.
//
// WHAT THE PORT COST was a decision about the ANSWER, like every write in wave
// 2b before it. The operation PERMITS writing a credential-bearing key and then
// WITHHOLDS the value from its own answer — one projection serves the write and
// the read, so a PUT's body is the body of the GET after it — which leaves a
// successful write whose `value` member is absent and a result type with no
// spelling for "withheld". The client answers with the value it SENT, which is
// the operation's own promise rather than a guess about what redaction hid: the
// stored value equals the value sent for every key this plane accepts, because
// the one key with a normalization step is the one key the role refuses.
//
// The two EDGE BOUNDS the operation adds — a key past 255 characters on the
// write, a value past types.MaxTextBytes bytes — are the server's and are not
// restated here (L-config-bounds).
func (s *Store) WorkspaceConfig() (issueops.WorkspaceConfig, error) {
return httpWorkspaceConfig{store: s}, nil
}
// Sweeper serves sweepIssues (D8 row 12). See sweeper.go.
func (s *Store) Sweeper() (issueops.Sweeper, error) {
w, err := s.roleWire("Sweeper")
if err != nil {
return nil, err
}
return &httpSweeper{store: s, wire: w}, nil
}
// Deleter serves deleteIssues (D8 row 13). See deleter.go.
func (s *Store) Deleter() (issueops.Deleter, error) {
w, err := s.roleWire("Deleter")
if err != nil {
return nil, err
}
return &httpDeleter{store: s, wire: w}, nil
}
// BatchCreator serves batchCreateIssues (D8 row 14); the item members the wire
// cannot carry refuse per-item, per refuse-not-drop. See batchcreator.go.
func (s *Store) BatchCreator() (issueops.BatchCreator, error) {
w, err := s.roleWire("BatchCreator")
if err != nil {
return nil, err
}
return &httpBatchCreator{store: s, wire: w}, nil
}
// Memories serves the four memory operations (D8 row 15). See memories.go.
func (s *Store) Memories() (memoryops.Memories, error) {
w, err := s.roleWire("Memories")
if err != nil {
return nil, err
}
return &httpMemories{store: s, wire: w}, nil
}
// IssueLifecycle serves createIssue/updateIssue/closeIssue/reopenIssue (D8 row
// 16). It was PARTIAL until the create landed — POST /v0/beads/issues was
// deliberately left free on the wire, so there was nothing to dial — and
// upstream #5483 filled it. See lifecycle.go.
func (s *Store) IssueLifecycle() (issueops.Lifecycle, error) {
w, err := s.roleWire("IssueLifecycle")
if err != nil {
return nil, err
}
return &httpLifecycle{store: s, wire: w}, nil
}
// DependencyEditor serves addDependencies/removeDependency (D8 row 18). See
// dependencyeditor.go.
func (s *Store) DependencyEditor() (issueops.DependencyEditor, error) {
w, err := s.roleWire("DependencyEditor")
if err != nil {
return nil, err
}
return &httpDependencyEditor{store: s, wire: w}, nil
}
// BatchCloser serves the single-item, no-ClaimNext shape of CloseBatch by
// composing onto closeIssue, and refuses every other shape (the `bd close`
// decision, amending D8 row 17's PENDING-DECISION). See batchcloser.go.
//
// It is the EIGHTEENTH wire-backed accessor: the design's matrix recorded
// seventeen because row 17 was undecided when it was written, and the decision
// moved this one across.
func (s *Store) BatchCloser() (issueops.BatchCloser, error) {
w, err := s.roleWire("BatchCloser")
if err != nil {
return nil, err
}
return &httpBatchCloser{store: s, wire: w}, nil
}
// MetadataCAS serves compareAndSetMetadata (POST
// /v0/beads/issues/{id}:casMetadata) — the NINETEENTH wire-backed accessor.
//
// The operation's contract was the part that needed wiring rather than the
// transport, and it is the one place this seam's usual rule does not hold: a
// lost compare-and-set is a 200 carrying `swapped: false` and the current
// value, so the client reads the body of a SUCCESS to learn the swap did not
// happen, where every other write here learns that from a status code. See
// metadatacas.go.
func (s *Store) MetadataCAS() (issueops.MetadataCAS, error) {
w, err := s.roleWire("MetadataCAS")
if err != nil {
return nil, err
}
return &httpMetadataCAS{store: s, wire: w}, nil
}
// BatchApplier serves applyBatch (POST /v0/beads/issues:batchApply) — the
// TWENTIETH wire-backed accessor, and the widest write on the surface: one
// request carrying creates, updates, closes and edges that either all land or
// none do.
//
// Its key-binding half — a create item names a key that later items reference,
// and the response maps every key to the id it was bound to — has no analog in
// any other role here, and neither does the shape it forced on the refusal
// path: an all-or-nothing operation publishes no per-item outcomes, so the
// offender travels in the problem document's item_* members and this role
// rebuilds *issueops.ItemError and *issueops.RefError from them. See
// batchapplier.go.
func (s *Store) BatchApplier() (issueops.BatchApplier, error) {
w, err := s.roleWire("BatchApplier")
if err != nil {
return nil, err
}
return &httpBatchApplier{store: s, wire: w}, nil
}
// BatchGetter serves batchGetIssues (POST /v0/beads/issues:batchGet) — the
// TWENTY-SIXTH wire-backed accessor, and the newest: storage.DoltStorage grew
// this method when the rebase onto origin/main brought in upstream #7248's
// issueops.BatchGetter.
//
// It takes no roleWire: the operation writes nothing and carries no actor or
// version guard for a WriteWire method to wrap, so it dials through the
// store directly, the way Counter and Querier do. See batchgetter.go.
func (s *Store) BatchGetter() (issueops.BatchGetter, error) {
return &httpBatchGetter{store: s}, nil
}

View file

@ -32,7 +32,7 @@ func (fixtureBackendCredential) BackendCredential() {}
func TestResolveCredentialNilNotRequiredFallsBackToTheAmbientLadder(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "ambient-token")
t.Setenv(TokenEnv, "127.0.0.1=ambient-token")
base := mustParseURL(t, "http://127.0.0.1:8080")
cp, err := ResolveCredential(backends.OpenOptions{}, base, false)

View file

@ -0,0 +1,769 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/batchapplier.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"fmt"
"reflect"
"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"
)
// httpBatchApplier serves issueops.BatchApplier over issues:batchApply — the
// widest write on this surface, and the only one that is ALL OR NOTHING across
// several verbs at once.
//
// WHAT MAKES IT DIFFERENT FROM ITS NEIGHBORS HERE, and what the port had to
// carry:
//
// THE ITEM IS A TAGGED UNION AND THE WIRE CANNOT ENFORCE THE TAG. The document
// uses no composition keyword, so an item is one object with a required `kind`
// and four optional payloads: nothing in any generated type stops a request
// carrying two payloads, or a payload the kind does not name, or a kind this
// client has never heard of. All four disagreements are refused HERE, before
// the dial, because the role's own contract calls each of them ErrValidation
// and because a kind added upstream must FAIL CLOSED rather than be dropped
// into a request that silently does less than the caller asked.
//
// THERE ARE NO PER-ITEM OUTCOMES TO WALK. batchClose answers a refused item
// inside a 200 and the role reads the outcome array; here a refused item took
// the whole transaction down, so every other item's outcome would be a
// statement about work that rolled back. The offender travels in the problem
// document's `item_*` members instead, read off the role's own typed
// *issueops.ItemError inside the refusing transaction, and rebuilt here so a
// caller classifies a remote refusal with the errors.As arm it already has.
//
// THE RESULT IS POSITIONAL, which is the hazard this file guards hardest. The
// wire answers one entry per requested item in request order, and a client that
// trusted that without checking would attribute one item's `changed` and
// `revision` to a different item's row — a misattribution no assertion about
// the row would catch, because both rows exist and both were written.
// decodeApplyBatchResult checks the length AND the kind at every index.
//
// THE SNAPSHOT STOPS AT THE WIRE. issueops.ItemResult carries a post-item
// *Issue and ApplyItemResult does not, deliberately (the role's own leaf says
// so: hooks never fire on this surface, and a hundred hydrated issues would be
// a response an order of magnitude larger than the request). So Issue is nil on
// every item this role answers with — ledger row L-apply-snapshot.
type httpBatchApplier struct {
store *Store
wire WriteWire
}
var _ issueops.BatchApplier = (*httpBatchApplier)(nil)
// ApplyBatch dials POST /v0/beads/issues:batchApply.
func (b *httpBatchApplier) ApplyBatch(ctx context.Context, req issueops.ApplyBatchRequest) (result issueops.ApplyBatchResult, err error) {
// Write-side parity with reads: decorates a bare *encode.RefusedError —
// however deeply applyBatchBody/encodeApplyPatch nested it inside an
// "items[%d]..." or "Issue.%s:" prefix — into *InexpressibleError so
// errors.As(err, &unsupported) reaches *storage.ErrUnsupported, same as
// inexpressible does for a read role. The original composite message
// (including that prefix) is preserved in the decorated error's own text.
defer func() { err = b.store.inexpressible("BatchApplier.ApplyBatch", err) }()
if err := requireActor(req.Actor); err != nil {
return issueops.ApplyBatchResult{}, err
}
// The two bounds the ROLE states, applied before the dial for the reason
// every client-side validation here is applied before one: a request the
// role's own contract calls invalid must not consume a write slot to be
// told so. Neither is a wire divergence — the document publishes the same
// hundred — and the cap REFUSES rather than splitting, because a split plan
// is several transactions where the caller asked for one and the end gate
// only ever sees a single request.
if len(req.Items) == 0 {
return issueops.ApplyBatchResult{}, invalid("a batch apply names no items")
}
if len(req.Items) > issueops.MaxApplyBatchItems {
return issueops.ApplyBatchResult{}, invalid(
"a batch apply carries %d items; the limit is %d per request", len(req.Items), issueops.MaxApplyBatchItems)
}
body, err := applyBatchBody(req)
if err != nil {
return issueops.ApplyBatchResult{}, err
}
resp, err := b.wire.ApplyBatch(ctx, body)
if err != nil {
return issueops.ApplyBatchResult{}, applyBatchRefusal(err)
}
return decodeApplyBatchResult(req, resp)
}
// applyBatchBody projects the role's request onto the wire body.
func applyBatchBody(req issueops.ApplyBatchRequest) (wire.ApplyBatchRequest, error) {
items := make([]wire.ApplyItem, 0, len(req.Items))
for i, item := range req.Items {
encoded, err := applyItemBody(item, req.Actor)
if err != nil {
return wire.ApplyBatchRequest{}, fmt.Errorf("items[%d]: %w", i, err)
}
items = append(items, encoded)
}
body := wire.ApplyBatchRequest{Actor: req.Actor, Items: items}
setItemString(&body.Provenance, req.Provenance)
// The two booleans are sent only when TRUE, createBody's rule: each selects
// a bypass, so an explicit false is the default said twice.
setItemBool(&body.ForceIDPrefix, req.ForceIDPrefix)
setItemBool(&body.SkipPerEdgeCycleCheck, req.SkipPerEdgeCycleCheck)
return body, nil
}
// applyItemKinds is the tag vocabulary this client knows, paired with the
// payload each value names. It is a map rather than a switch so the closed set
// is ENUMERABLE, and so the agreement check below and the projection cannot
// drift into two opinions about which payload a kind reads.
var applyItemKinds = map[issueops.ItemKind]string{
issueops.ItemCreate: "create",
issueops.ItemUpdate: "update",
issueops.ItemClose: "close",
issueops.ItemDepAdd: "dep_add",
}
// applyItemBody projects one tagged item, refusing all four ways a tag and its
// payloads can disagree.
//
// IT FAILS CLOSED ON AN UNKNOWN KIND, and that is the arm worth stating out
// loud: ItemKind is a closed set today, and a fifth verb added to issueops
// tomorrow would arrive here as a value this map does not carry. Sending it
// anyway would put an item on the wire with a tag the server refuses — a round
// trip to be told what is knowable here — and, worse, sending it with NO
// payload would be a plan that silently did less than the caller composed.
// Refusing names the kind.
func applyItemBody(item issueops.ApplyItem, actor string) (wire.ApplyItem, error) {
named, known := applyItemKinds[item.Kind]
if !known {
return wire.ApplyItem{}, invalid("item kind %q is not one of create, update, close, dep_add", item.Kind)
}
// The tag and the payloads have to agree in BOTH directions, exactly as
// they do at the server's own door: a kind with no payload is an item that
// does nothing, a payload the kind does not name is an item whose two
// halves disagree, and two payloads is an item that cannot say which it
// meant. The role calls all three ErrValidation.
var carried []string
for _, present := range []struct {
member string
set bool
}{
{"create", item.Create != nil},
{"update", item.Update != nil},
{"close", item.Close != nil},
{"dep_add", item.DepAdd != nil},
} {
if present.set {
carried = append(carried, present.member)
}
}
switch {
case len(carried) == 0:
return wire.ApplyItem{}, invalid("an item of kind %q carries no %s payload", item.Kind, named)
case len(carried) > 1:
return wire.ApplyItem{}, invalid("an item carries exactly one payload; this one carries %v", carried)
case carried[0] != named:
return wire.ApplyItem{}, invalid("an item of kind %q carries the %q payload; the two must name the same verb",
item.Kind, carried[0])
}
out := wire.ApplyItem{Kind: named}
switch item.Kind {
case issueops.ItemCreate:
create, err := applyCreateItemBody(item.Create, actor)
if err != nil {
return wire.ApplyItem{}, err
}
out.Create = create
case issueops.ItemUpdate:
update, err := applyUpdateItemBody(item.Update)
if err != nil {
return wire.ApplyItem{}, err
}
out.Update = update
case issueops.ItemClose:
closeItem, err := applyCloseItemBody(item.Close)
if err != nil {
return wire.ApplyItem{}, err
}
out.Close = closeItem
case issueops.ItemDepAdd:
depAdd, err := applyDepAddItemBody(item.DepAdd)
if err != nil {
return wire.ApplyItem{}, err
}
out.DepAdd = depAdd
}
return out, nil
}
// applyCreateItemBody projects one create item.
//
// The wire's create vocabulary here is EXACTLY createIssue's twenty — the same
// members, spelled the same way — so the allowlist and the refusal sweep are
// the single create's, shared rather than copied. What is different is the
// ledger row the refusal cites: this is a different operation, and a reader
// auditing "why does my plan refuse?" must not be sent to a row about
// createIssue.
func applyCreateItemBody(item *issueops.CreateItem, actor string) (*apigen.ApplyCreateItem, error) {
if item == nil || item.Issue == nil {
return nil, invalid("a create item names no issue")
}
issue := item.Issue
if len(issue.Comments) > 0 || len(issue.Dependencies) > 0 {
// The ROLE's own rule rather than a wire divergence, and here it is
// stronger than it is on the single create: edges in this role are
// ITEMS, so a create item has nowhere to put one at all.
return nil, invalid("a create item's Issue carries comments or dependencies; edges are dep_add items")
}
if err := refuseUnwirableIssueMembers(issue, actor, encode.OpApplyBatch, "W-CreateItem.Issue"); err != nil {
return nil, err
}
// Priority is sent ALWAYS, createBody's reason: 0 is P0 and a real request,
// so an absent member — which the server reads as the workspace default —
// would silently reprioritize every critical issue a plan creates.
priority := issue.Priority
out := &apigen.ApplyCreateItem{Title: issue.Title, Priority: &priority}
setItemString(&out.Key, item.Key)
setItemString(&out.Id, issue.ID)
setItemString(&out.Description, issue.Description)
setItemString(&out.Design, issue.Design)
setItemString(&out.AcceptanceCriteria, issue.AcceptanceCriteria)
setItemString(&out.Notes, issue.Notes)
setItemString(&out.Status, string(issue.Status))
setItemString(&out.IssueType, string(issue.IssueType))
setItemString(&out.Assignee, issue.Assignee)
setItemString(&out.Owner, issue.Owner)
setItemString(&out.Sender, issue.Sender)
if issue.ExternalRef != nil {
ref := *issue.ExternalRef
out.ExternalRef = &ref
}
if issue.EstimatedMinutes != nil {
minutes := *issue.EstimatedMinutes
out.EstimatedMinutes = &minutes
}
out.DueAt = copyTime(issue.DueAt)
out.DeferUntil = copyTime(issue.DeferUntil)
if len(issue.Labels) > 0 {
labels := append([]string(nil), issue.Labels...)
out.Labels = &labels
}
if len(issue.Metadata) > 0 {
// The blob travels as the bytes the caller sent, and only its
// well-formedness is this layer's question. See requireJSON.
if err := requireJSON("Issue.Metadata", issue.Metadata); err != nil {
return nil, err
}
out.Metadata = append(apigen.MetadataValue(nil), issue.Metadata...)
}
setItemBool(&out.Ephemeral, issue.Ephemeral)
setItemBool(&out.NoHistory, issue.NoHistory)
if len(item.MetadataRefs) > 0 {
refs := make(map[string]apigen.Ref, len(item.MetadataRefs))
for key, ref := range item.MetadataRefs {
encoded, err := applyRefBody(ref)
if err != nil {
return nil, fmt.Errorf("metadata_refs[%q]: %w", key, err)
}
refs[key] = encoded
}
out.MetadataRefs = &refs
}
return out, nil
}
// applyUpdateItemBody projects one update item.
func applyUpdateItemBody(item *issueops.UpdateItem) (*wire.ApplyUpdateItem, error) {
if item == nil {
return nil, invalid("an update item carries no payload")
}
target, err := applyRefBody(item.Target)
if err != nil {
return nil, fmt.Errorf("target: %w", err)
}
patch, err := encodeApplyPatch(item.Patch)
if err != nil {
return nil, err
}
if len(patch) == 0 {
// The role and the server both refuse an empty patch; saying it here
// keeps a write that writes nothing off the wire entirely.
return nil, invalid("an update item names no field to write")
}
out := &wire.ApplyUpdateItem{
Target: target,
Patch: patch,
ExpectedVersion: revisionGuard(item.ExpectedVersion),
}
// The two string guards are pointers on both sides and the copy is a nil
// check, updateGuards' rule: an empty `expected_assignee` is the guard that
// says "only if nobody holds it", so absent has to stay absent.
if item.ExpectedStatus != nil {
status := string(*item.ExpectedStatus)
out.ExpectedStatus = &status
}
if item.ExpectedAssignee != nil {
assignee := *item.ExpectedAssignee
out.ExpectedAssignee = &assignee
}
// All three force flags ARE published on this operation, unlike
// updateIssue's body where they are still refused — so a plan can express
// what a single patch over this wire cannot. They are sent only when true.
setItemBool(&out.ForceClosePolicy, item.ForceClosePolicy)
setItemBool(&out.ForceAssigneeTransfer, item.ForceAssigneeTransfer)
setItemBool(&out.ForceNotesOverwrite, item.ForceNotesOverwrite)
return out, nil
}
// applyCloseItemBody projects one close item.
//
// THE MAPPING IS TOTAL: every member of the role's CloseItem has a wire member,
// including the row-version guard, so no W- row names one. There is deliberately
// no expected_status on either side — a close is idempotent, so a guard spelled
// to refuse an already-closed row asks for a refusal where the verb answers
// with a no-op.
func applyCloseItemBody(item *issueops.CloseItem) (*apigen.ApplyCloseItem, error) {
if item == nil {
return nil, invalid("a close item carries no payload")
}
target, err := applyRefBody(item.Target)
if err != nil {
return nil, fmt.Errorf("target: %w", err)
}
out := &apigen.ApplyCloseItem{Target: target, ExpectedVersion: revisionGuard(item.ExpectedVersion)}
setItemString(&out.Reason, item.Reason)
setItemString(&out.Session, item.Session)
setItemBool(&out.Force, item.Force)
return out, nil
}
// applyDepAddItemBody projects one edge item.
//
// The gate normalization a waits-for edge gets, and the refusal a bad gate
// earns, are the ROLE's and stay there: the blob travels as the caller's own
// bytes, and a second parse here would be a second definition of what the edge
// metadata plane accepts.
func applyDepAddItemBody(item *issueops.DepAddItem) (*apigen.ApplyDepAddItem, error) {
if item == nil {
return nil, invalid("a dep_add item carries no payload")
}
source, err := applyRefBody(item.Source)
if err != nil {
return nil, fmt.Errorf("source: %w", err)
}
target, err := applyRefBody(item.Target)
if err != nil {
return nil, fmt.Errorf("target: %w", err)
}
if item.Type == "" {
return nil, invalid("a dep_add item names no edge type")
}
// ApplyDepAddItem publishes neither member below, so each refuses where the
// role would store something the wire cannot say. The spawner flag only
// does that on a waits-for edge; the role ignores it on every other type.
switch {
case item.HasSpawner && item.Type == issueops.DepWaitsFor:
return nil, refuse(encode.OpApplyBatch, "W-DepAddItem.HasSpawner")
case item.ThreadID != "":
return nil, refuse(encode.OpApplyBatch, "W-DepAddItem.ThreadID")
}
out := &apigen.ApplyDepAddItem{Source: source, Target: target, Type: string(item.Type)}
// A BLANK blob is ABSENT, not malformed, and reading it any other way is a
// real bug rather than strictness: the role's own rule is that an absent,
// blank or `{}` metadata on a waits-for edge is stored as the all-children
// gate, so a client that refused whitespace would fail a normalization the
// role performs. Only a NON-blank blob is checked for being JSON at all,
// which is this layer's one question about it.
if blob := strings.TrimSpace(item.Metadata); blob != "" {
if err := requireJSON("DepAdd.Metadata", []byte(blob)); err != nil {
return nil, err
}
out.Metadata = apigen.MetadataValue(blob)
}
return out, nil
}
// applyRefBody projects one ref, applying the exactly-one rule the schema
// cannot state.
//
// Both members set is a caller that cannot say which it meant and neither is a
// reference to nothing; the role calls both ErrValidation before anything is
// written, so both are refused here rather than dialed. WHETHER a key RESOLVES,
// and whether it reaches backward far enough, is the role's question — only the
// server can see the whole request's key index — and comes back as a *RefError.
func applyRefBody(ref issueops.Ref) (apigen.Ref, error) {
switch {
case ref.Key == "" && ref.ID == "":
return apigen.Ref{}, invalid("a ref names neither a key nor an id")
case ref.Key != "" && ref.ID != "":
return apigen.Ref{}, invalid("a ref names a key and an id; it must name exactly one")
}
var out apigen.Ref
setItemString(&out.Key, ref.Key)
setItemString(&out.Id, ref.ID)
return out, nil
}
// applyPatchExcludedMembers is the refusal half of the apply patch's allowlist,
// in the order encodeApplyPatch decides them.
//
// THE ALLOWLIST IS NOT updateIssue's, and the two differences run in opposite
// directions, which is why this cannot share refuseExcludedPatchMembers:
//
// owner IS published here and refused there. ApplyPatchBody carries it;
// IssuePatchBody does not, which the document calls an accident of
// order rather than a decision.
// parent_id is published THERE and absent here, and that one is deliberate:
// a parent is a dep_add item of type parent-child, so the order of
// every edge in a plan stays total and there is one spelling for
// an edge.
//
// The other three — spec_id, await_id, closed_by_session — and persistence are
// absent from both bodies.
var applyPatchExcludedMembers = []struct {
member string
ledger string
set func(issueops.IssuePatch) bool
}{
// ParentID is this document's OWN exclusion and gets its own row; the other
// four are absent from both patch bodies, so they cite the rows that
// already refuse them rather than minting a second reason for one fact.
{"ParentID", "W-ApplyPatch.ParentID", func(p issueops.IssuePatch) bool { return p.ParentID.Set }},
{"SpecID", "W-IssuePatch.SpecID", func(p issueops.IssuePatch) bool { return p.SpecID.Set }},
{"AwaitID", "W-IssuePatch.AwaitID", func(p issueops.IssuePatch) bool { return p.AwaitID.Set }},
{"ClosedBySession", "W-IssuePatch.ClosedBySession", func(p issueops.IssuePatch) bool { return p.ClosedBySession.Set }},
{"Persistence", "W-IssuePatch.Persistence", func(p issueops.IssuePatch) bool { return p.Persistence.Set }},
}
// encodeApplyPatch turns the role's patch into an update item's patch document.
//
// It is a map for encodeIssuePatch's reason and no other: the four NULLABLE
// members wrap a POINTER, and a set nil pointer has to reach the server as a
// literal null — the clear — where an unset one has to be absent entirely.
// apigen.ApplyPatchBody spells them `omitempty`, which collapses the two.
//
// REFUSE FIRST, THEN ENCODE, so a patch that both names an excluded member and
// carries a malformed metadata blob reports the fact about the WIRE rather than
// whichever error the encoder happened to reach first.
//
// LABELS ARE THE FULL PATCH HERE, which is the one place this document is WIDER
// than PATCH /v0/beads/issues/{id}'s: a plan edits a label set it did not
// compose, so an incremental add or remove has to be expressible without
// reading the set back first. W-IssuePatch.Labels is updateIssue's row and does
// not reach this operation.
func encodeApplyPatch(patch issueops.IssuePatch) (map[string]any, error) {
for _, excluded := range applyPatchExcludedMembers {
if excluded.set(patch) {
return nil, refuse(encode.OpApplyBatch, excluded.ledger)
}
}
out := map[string]any{}
setString(out, "title", patch.Title)
setString(out, "description", patch.Description)
setString(out, "design", patch.Design)
setString(out, "acceptance_criteria", patch.AcceptanceCriteria)
setString(out, "notes", patch.Notes)
setString(out, "append_notes", patch.AppendNotes)
setString(out, "assignee", patch.Assignee)
setString(out, "owner", patch.Owner)
if patch.Priority.Set {
out["priority"] = patch.Priority.Value
}
if patch.IssueType.Set {
out["issue_type"] = string(patch.IssueType.Value)
}
if patch.Status.Set {
out["status"] = string(patch.Status.Value)
}
if metadataPatched(patch.Metadata) {
document, err := encodeMetadataPatch(patch.Metadata)
if err != nil {
return nil, err
}
out["metadata"] = document
}
// The nullable four. A set member always lands, and lands as null when its
// pointer is nil, because that is the clear.
setNullable(out, "estimated_minutes", patch.EstimatedMinutes)
setNullable(out, "external_ref", patch.ExternalRef)
setNullableTime(out, "due_at", patch.DueAt)
setNullableTime(out, "defer_until", patch.DeferUntil)
if labels := encodeApplyLabelPatch(patch.Labels); len(labels) > 0 {
out["labels"] = labels
}
return out, nil
}
// encodeApplyLabelPatch projects the ordered label edit whole.
//
// Replace is a Field rather than a plain slice on both sides, and that is the
// state a struct could not carry: a SET replacement holding no labels CLEARS
// every label, where an unset one leaves the current set as the starting point.
func encodeApplyLabelPatch(patch issueops.LabelPatch) map[string]any {
out := map[string]any{}
if patch.Replace.Set {
// The copy starts from an EMPTY SLICE rather than a nil one, and that is
// the clear rather than a style choice: a set Replace holding no labels
// is how a caller says "remove every label", and a nil []string marshals
// to JSON `null`, which this member does not accept. Starting from
// []string{} makes the clear travel as the empty ARRAY the document
// spells it with.
out["replace"] = append([]string{}, patch.Replace.Value...)
}
if len(patch.Add) > 0 {
out["add"] = append([]string(nil), patch.Add...)
}
if len(patch.Remove) > 0 {
out["remove"] = append([]string(nil), patch.Remove...)
}
return out
}
// refuseUnwirableIssueMembers is the other half of createCarriedIssueMembers'
// allowlist: it refuses the first populated member of an issue that the wire's
// create vocabulary does not carry, the role does not ignore, and the server
// does not stamp from the actor (actorStampedCreateMember).
//
// It answers the FIRST offender in declaration order, which is deterministic —
// a caller fixing one member at a time must not see the reported member depend
// on map iteration. It is generalized over the LEDGER ROW because two
// operations publish the identical twenty members — createIssue and
// batchApply's create item — and a caller must be sent to the row for the
// operation they actually called. The partition itself is one partition and is
// shared, so the two cannot disagree about what the wire carries or about what
// the role drops.
func refuseUnwirableIssueMembers(issue *issueops.Issue, actor string, op encode.Op, ledgerID string) error {
value := reflect.ValueOf(*issue)
shape := value.Type()
for i := range shape.NumField() {
field := shape.Field(i)
if !field.IsExported() {
continue
}
if _, carried := createCarriedIssueMembers[field.Name]; carried {
continue
}
if _, ignored := roleIgnoredCreateIssueMembers[field.Name]; ignored {
continue
}
if value.Field(i).IsZero() || actorStampedCreateMember(field.Name, issue, actor) {
continue
}
// The ledger row is the vocabulary; the member name is the fact the row
// cannot carry, because one row covers the whole population.
return fmt.Errorf("Issue.%s: %w", field.Name, refuse(op, ledgerID))
}
return nil
}
// applyBatchRefusal rebuilds the role's typed refusals from the problem
// document's item members.
//
// IT READS TYPED MEMBERS AND NEVER PROSE, which matters more on this operation
// than anywhere else on the surface: the request is all or nothing, so there is
// no per-item result array a caller could find the offender in, and `item_*`
// is the only place it exists.
//
// THE REF REFUSAL IS MATCHED FIRST, on `declared_later`'s PRESENCE. It is the
// one 400 that carries a discriminator — an ordering mistake reads differently
// from a typo — and it is emitted in both polarities precisely so absence can
// mean "this refusal was not about a key".
//
// A *RefError REPLACES the problem envelope rather than wrapping it, and that
// is the role type's shape rather than a choice here: RefError.Unwrap is
// hardcoded to ErrValidation and the type carries no member for a cause. Ledger
// row L-apply-ref records what that costs.
func applyBatchRefusal(err error) error {
var problem *wire.ProblemError
if !errors.As(err, &problem) {
return err
}
if problem.DeclaredLater != nil {
if problem.ItemIndex == nil {
// A key refusal that named no item. Unreachable against this
// server — the ref refusal is raised inside a request whose items
// are indexed — but RefError.Index has no absent state, so
// answering 0 would name the FIRST item as the offender on a
// refusal that named none. The problem travels unwrapped instead.
return err
}
return &issueops.RefError{
Index: *problem.ItemIndex,
Member: applyRefMember(problem.Param),
Key: derefStringPtr(problem.ItemKey),
DeclaredLater: *problem.DeclaredLater,
}
}
if problem.ItemIndex == nil {
// A refusal the role raised without naming an item — the request's own
// validation, or a transport-level answer. It travels unwrapped: an
// *ItemError naming index 0 would be a claim about an item this refusal
// says nothing about.
return err
}
return &issueops.ItemError{
Index: *problem.ItemIndex,
Kind: issueops.ItemKind(derefStringPtr(problem.ItemKind)),
Key: derefStringPtr(problem.ItemKey),
IssueID: derefStringPtr(problem.ItemIssueID),
// The whole ProblemError, so errors.Is still reaches the sentinel its
// code mapped to and the request id survives for a 5xx.
Err: err,
}
}
// applyRefMember maps the refusal's `param` back onto the role's Member, which
// is diagnostic prose rather than a vocabulary on either side.
//
// The wire names the MEMBER that held the bad ref — `items[3].create.metadata_refs`
// — where the role names the member and, for a metadata ref, the key inside it.
// The key is not recoverable from `param`, so this answers the member alone; see
// ledger row L-apply-ref.
func applyRefMember(param string) string {
switch {
case strings.HasSuffix(param, ".target"):
return "target"
case strings.HasSuffix(param, ".source"):
return "source"
default:
return "metadata_refs"
}
}
// decodeApplyBatchResult reads the wire response back into the role's result.
//
// THE ARRAY IS POSITIONAL AND IS CHECKED AS ONE, in the two ways the answer
// makes checkable. The wire promises one entry per requested item in request
// order, and a misattribution is the failure no assertion about a ROW would
// catch: both rows exist and both were written, so one item's `changed` and
// `revision` simply read as another's.
//
// length and kind a count that disagrees, or a kind that does not echo the
// item at its index, is caught by comparing the answer with
// the request the client itself composed.
// the key map `keys` binds each NAMED create to the id it was bound to,
// independently of the array's order, so a keyed create's
// result has a second source to agree with. This is what
// catches a SAME-KIND SWAP, which the kind comparison above
// cannot see at all: two transposed creates both answer
// "create" at both indexes. A key the request declared and
// the answer does not carry is refused for the same reason —
// the binding is the one fact the request cannot carry, so a
// missing one leaves a result that cannot be checked rather
// than one to pass along.
//
// WHAT REMAINS UNCHECKABLE, said plainly rather than left as an implication: an
// UNKEYED same-kind swap. Nothing in the response distinguishes two unnamed
// creates and nothing in the request could — naming them is exactly what makes
// them distinguishable — so a transposition between two unnamed items of one
// kind passes. It sits in the same trust class as a server that answered about
// a row the request never named, and the served assembly is provably in item
// order (internal/httpapi/batch_apply.go's applyBatchResponse walks
// result.Items). A caller that needs the guarantee names its items.
//
// Every refusal here is the METHOD's rather than a per-item one, because a
// broken answer says nothing trustworthy about any single item.
func decodeApplyBatchResult(req issueops.ApplyBatchRequest, resp *apigen.ApplyBatchResponse) (issueops.ApplyBatchResult, error) {
if resp == nil {
return issueops.ApplyBatchResult{}, fmt.Errorf("bd serve returned no batch-apply result")
}
if len(resp.Items) != len(req.Items) {
return issueops.ApplyBatchResult{}, fmt.Errorf(
"bd serve returned %d batch-apply results for %d items", len(resp.Items), len(req.Items))
}
items := make([]issueops.ItemResult, len(resp.Items))
for i, item := range resp.Items {
kind := issueops.ItemKind(item.Kind)
if kind != req.Items[i].Kind {
return issueops.ApplyBatchResult{}, fmt.Errorf(
"bd serve returned a %q result at index %d for a %q item; the results are positional",
kind, i, req.Items[i].Kind)
}
if err := checkApplyKeyBinding(req.Items[i], i, item, resp.Keys); err != nil {
return issueops.ApplyBatchResult{}, err
}
// The token is a decimal string on the wire (types.RevisionToken) and
// an int64 on the Go contract; parseRevision is the one place it is
// read back, and a token the server spelled in a way this client
// cannot read refuses the whole result rather than stitching a 0 that
// would only surface as a precondition failure on the NEXT request.
revision, err := parseRevision(fmt.Sprintf("batchApply item %d", i), item.Revision)
if err != nil {
return issueops.ApplyBatchResult{}, err
}
items[i] = issueops.ItemResult{
Kind: kind,
IssueID: item.IssueId,
Changed: item.Changed,
RowVersion: revision,
// Issue stays nil. The wire result is lean by design and the role's
// own leaf says why; L-apply-snapshot records it.
Issue: nil,
}
if item.DependsOnId != nil {
items[i].DependsOnID = *item.DependsOnId
}
}
// Allocated rather than passed through, so nothing downstream holds a
// window onto a decoded response body — and so a request whose creates
// named nothing answers with an empty map rather than a nil one.
keys := make(map[string]string, len(resp.Keys))
for key, id := range resp.Keys {
keys[key] = id
}
return issueops.ApplyBatchResult{Keys: keys, Items: items}, nil
}
// checkApplyKeyBinding cross-checks one item's result against the key map.
//
// It applies to KEYED CREATES and to nothing else, which is the whole of what
// the answer makes checkable: `keys` carries only the keys the request NAMED,
// an unnamed create item is in `items` and not there, and an update or a close
// resolves a ref the caller already knew the id of.
func checkApplyKeyBinding(item issueops.ApplyItem, index int, result apigen.ApplyItemResult, keys map[string]string) error {
if item.Kind != issueops.ItemCreate || item.Create == nil || item.Create.Key == "" {
return nil
}
key := item.Create.Key
bound, named := keys[key]
if !named {
return fmt.Errorf(
"bd serve bound no id to key %q, which items[%d] declares; the key binding is the one fact the request cannot carry",
key, index)
}
if bound != result.IssueId {
return fmt.Errorf(
"bd serve bound key %q to %s and answered items[%d] with %s; the results are positional and this pair disagrees",
key, bound, index, result.IssueId)
}
return nil
}
func derefInt(v *int) int {
if v == nil {
return 0
}
return *v
}
func derefStringPtr(v *string) string {
if v == nil {
return ""
}
return *v
}

View file

@ -0,0 +1,999 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/batchapplier_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"encoding/json"
"errors"
"reflect"
"slices"
"strings"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The batch-apply role's unit gates: what the client DECIDES before the dial,
// and what it refuses to believe about the answer.
//
// Everything about what a plan MEANS is the server's and is asserted end to end
// by served_batch_apply_test.go. What is here is the half a live server cannot
// show — the request the client built, the refusals it raised without dialing,
// and the answers it will not accept.
func applyRole(t *testing.T, w *stubWire) issueops.BatchApplier {
t.Helper()
applier, err := stubStore(t, w).BatchApplier()
if err != nil {
t.Fatalf("BatchApplier(): %v", err)
}
return applier
}
// applyOneCreate is the smallest plan that lands: one create item, nothing
// named, nothing guarded.
func applyOneCreate() issueops.ApplyBatchRequest {
return issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemCreate,
Create: &issueops.CreateItem{Issue: &issueops.Issue{Title: "t"}},
}},
}
}
// TestApplyBatchRefusesEveryMemberTheWireExcludes is the refuse-not-drop gate
// for this operation, and it is the pin every W- row of the batch-apply
// population cites.
//
// The create item's issue vocabulary is EXACTLY the single create's, so the
// partition tables are shared rather than copied and this drives the same sweep
// against a different operation and a different ledger row. The patch's own
// excluded member — parent_id — is the second half, and the edge item's two —
// the spawner flag and the thread — are the third.
func TestApplyBatchRefusesEveryMemberTheWireExcludes(t *testing.T) {
t.Run("the create item's carried members are the wire's own", func(t *testing.T) {
published := bodyMembers(t, reflect.TypeOf(apigen.ApplyCreateItem{}))
for field, wireMember := range createCarriedIssueMembers {
if !published[wireMember] {
t.Errorf("Issue.%s claims wire member %q, which ApplyCreateItem does not publish", field, wireMember)
}
}
})
refused := createWireRefusedIssueMembers(t)
t.Run("every wire-refused issue member fails without dialing", func(t *testing.T) {
if len(refused) == 0 {
t.Fatal("no member is wire-refused; the shared partition tables have swallowed this population")
}
for _, name := range refused {
t.Run(name, func(t *testing.T) {
issue := &issueops.Issue{Title: "t"}
setNonZero(t, reflect.ValueOf(issue).Elem().FieldByName(name))
w := &stubWire{}
req := applyOneCreate()
req.Items[0].Create.Issue = issue
_, err := applyRole(t, w).ApplyBatch(t.Context(), req)
assertRefusedBy(t, err, "W-CreateItem.Issue")
if !strings.Contains(err.Error(), name) {
t.Errorf("the refusal does not name the member: %v", err)
}
if !strings.Contains(err.Error(), "items[0]") {
t.Errorf("the refusal does not name the item: %v", err)
}
if len(w.calls) != 0 {
t.Errorf("the refused member reached the wire: %v", w.calls)
}
})
}
})
t.Run("a CreatedBy naming the actor rides the server's stamp", func(t *testing.T) {
// The server stamps every create item's created_by from the actor, so
// that one value is carried by the stamp; the sweep above refuses any
// other.
w := &stubWire{}
req := applyOneCreate()
req.Items[0].Create.Issue.CreatedBy = req.Actor
if _, err := applyRole(t, w).ApplyBatch(t.Context(), req); err != nil {
t.Fatalf("ApplyBatch with CreatedBy == Actor = %v, want it carried by the server's stamp", err)
}
if w.lastApply.Actor != req.Actor {
t.Errorf("sent actor = %q, want the creator the stamp will write", w.lastApply.Actor)
}
})
t.Run("the role's own two are ErrValidation, and here they have nowhere to go at all", func(t *testing.T) {
for name := range createRoleRefusedIssueMembers {
issue := &issueops.Issue{Title: "t"}
setNonZero(t, reflect.ValueOf(issue).Elem().FieldByName(name))
w := &stubWire{}
req := applyOneCreate()
req.Items[0].Create.Issue = issue
_, err := applyRole(t, w).ApplyBatch(t.Context(), req)
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Issue.%s error = %v, want ErrValidation", name, err)
}
if len(w.calls) != 0 {
t.Errorf("Issue.%s reached the wire: %v", name, w.calls)
}
}
})
t.Run("the patch's own excluded member refuses, and the four shared ones cite their existing rows", func(t *testing.T) {
for _, test := range []struct {
member string
row string
patch issueops.IssuePatch
}{
{"ParentID", "W-ApplyPatch.ParentID", issueops.IssuePatch{
ParentID: issueops.Field[string]{Set: true, Value: "bd-parent"},
}},
{"SpecID", "W-IssuePatch.SpecID", issueops.IssuePatch{
SpecID: issueops.Field[string]{Set: true, Value: "spec-1"},
}},
{"AwaitID", "W-IssuePatch.AwaitID", issueops.IssuePatch{
AwaitID: issueops.Field[string]{Set: true, Value: "await-1"},
}},
{"ClosedBySession", "W-IssuePatch.ClosedBySession", issueops.IssuePatch{
ClosedBySession: issueops.Field[string]{Set: true, Value: "sess-1"},
}},
{"Persistence", "W-IssuePatch.Persistence", issueops.IssuePatch{
Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: types.PersistenceModeEphemeral},
}},
} {
t.Run(test.member, func(t *testing.T) {
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{Target: issueops.Ref{ID: "bd-1"}, Patch: test.patch},
}},
})
assertRefusedBy(t, err, test.row)
if len(w.calls) != 0 {
t.Errorf("the refused member reached the wire: %v", w.calls)
}
})
}
})
t.Run("the edge item's two unpublished members refuse", func(t *testing.T) {
for _, test := range []struct {
member string
row string
set func(*issueops.DepAddItem)
}{
{"HasSpawner", "W-DepAddItem.HasSpawner", func(item *issueops.DepAddItem) { item.HasSpawner = true }},
{"ThreadID", "W-DepAddItem.ThreadID", func(item *issueops.DepAddItem) { item.ThreadID = "th-1" }},
} {
t.Run(test.member, func(t *testing.T) {
item := &issueops.DepAddItem{
Source: issueops.Ref{ID: "bd-1"}, Target: issueops.Ref{ID: "bd-2"}, Type: issueops.DepWaitsFor,
}
test.set(item)
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{Kind: issueops.ItemDepAdd, DepAdd: item}},
})
assertRefusedBy(t, err, test.row)
if len(w.calls) != 0 {
t.Errorf("the refused member reached the wire: %v", w.calls)
}
})
}
})
t.Run("a spawner flag on any other edge type is the role's no-op, and is not refused", func(t *testing.T) {
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{Kind: issueops.ItemDepAdd, DepAdd: &issueops.DepAddItem{
Source: issueops.Ref{ID: "bd-1"}, Target: issueops.Ref{ID: "bd-2"}, Type: issueops.DepBlocks, HasSpawner: true,
}}},
})
if err != nil {
t.Fatalf("a spawner flag on a blocks edge refused: %v", err)
}
if got := w.lastApply.Items[0].DepAdd; got == nil || got.Type != string(issueops.DepBlocks) {
t.Errorf("the encoded edge = %+v, want the caller's blocks edge", got)
}
})
t.Run("owner is CARRIED here, which is where the two patch documents part company", func(t *testing.T) {
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{
Target: issueops.Ref{ID: "bd-1"},
Patch: issueops.IssuePatch{Owner: issueops.Field[string]{Set: true, Value: "ada"}},
},
}},
})
if err != nil {
t.Fatalf("an owner edit inside a plan refused: %v", err)
}
if got := w.lastApply.Items[0].Update.Patch["owner"]; got != "ada" {
t.Errorf("the encoded patch carries owner = %v, want the caller's value", got)
}
})
}
// TestApplyBatchFailsClosedOnAnItemTheClientCannotSpell is the tagged union's
// whole risk, driven in all four directions.
//
// The document carries a required tag and four OPTIONAL payloads because it
// uses no composition keyword, so nothing in any generated type stops a
// disagreement. The dangerous one is the unknown KIND: a fifth verb added to
// issueops would arrive here as a value the client's table does not carry, and
// a client that sent the item anyway would put a plan on the wire that did less
// than the caller composed.
func TestApplyBatchFailsClosedOnAnItemTheClientCannotSpell(t *testing.T) {
create := &issueops.CreateItem{Issue: &issueops.Issue{Title: "t"}}
update := &issueops.UpdateItem{
Target: issueops.Ref{ID: "bd-1"},
Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: "x"}},
}
for _, test := range []struct {
name string
item issueops.ApplyItem
says string
}{
{
// The fail-closed arm, and the DIAGNOSIS is what it pins rather than
// the refusal. "reopen" is a verb the ROLE deliberately excludes
// today, so it stands in for the fifth kind nobody has invented yet
// — and an implementation that passed an unknown kind through to
// the tag/payload agreement check would still refuse this item,
// while telling the caller its PAYLOAD was wrong. That sends
// someone reading the message to fix a payload that is correct,
// so the refusal has to name the VOCABULARY.
name: "a kind this client does not know",
item: issueops.ApplyItem{Kind: issueops.ItemKind("reopen"), Create: create},
says: `item kind "reopen" is not one of create, update, close, dep_add`,
},
{
// The same kind carrying nothing, which under a pass-through would
// be reported as a missing `reopen` payload — a member the document
// does not publish at all.
name: "a kind this client does not know, carrying nothing",
item: issueops.ApplyItem{Kind: issueops.ItemKind("reopen")},
says: `item kind "reopen" is not one of create, update, close, dep_add`,
},
{
name: "a kind with no payload",
item: issueops.ApplyItem{Kind: issueops.ItemCreate},
says: "no create payload",
},
{
name: "a payload the kind does not name",
item: issueops.ApplyItem{Kind: issueops.ItemUpdate, Create: create},
says: "must name the same verb",
},
{
name: "two payloads",
item: issueops.ApplyItem{Kind: issueops.ItemCreate, Create: create, Update: update},
says: "exactly one payload",
},
{
// The empty kind is the zero value of the field, which is what an
// item built by a caller that forgot the tag looks like.
name: "the empty kind",
item: issueops.ApplyItem{Create: create},
says: `item kind "" is not one of create, update, close, dep_add`,
},
} {
t.Run(test.name, func(t *testing.T) {
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner", Items: []issueops.ApplyItem{test.item},
})
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("error = %v, want ErrValidation", err)
}
if !strings.Contains(err.Error(), test.says) {
t.Errorf("the refusal does not say what was wrong (%q): %v", test.says, err)
}
if len(w.calls) != 0 {
t.Errorf("the item reached the wire: %v", w.calls)
}
})
}
}
// TestApplyBatchRefusesTheRequestShapesTheRoleCallsInvalid covers the bounds and
// the ref rule, all of them raised before the dial.
func TestApplyBatchRefusesTheRequestShapesTheRoleCallsInvalid(t *testing.T) {
oversized := issueops.ApplyBatchRequest{Actor: "planner"}
for range issueops.MaxApplyBatchItems + 1 {
oversized.Items = append(oversized.Items, issueops.ApplyItem{
Kind: issueops.ItemCreate,
Create: &issueops.CreateItem{Issue: &issueops.Issue{Title: "t"}},
})
}
refTarget := func(ref issueops.Ref) issueops.ApplyBatchRequest {
return issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{
Target: ref,
Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: "x"}},
},
}},
}
}
for _, test := range []struct {
name string
req issueops.ApplyBatchRequest
}{
{"no actor", issueops.ApplyBatchRequest{Items: applyOneCreate().Items}},
{"no items", issueops.ApplyBatchRequest{Actor: "planner"}},
{"one item past the cap", oversized},
{"a ref naming neither member", refTarget(issueops.Ref{})},
{"a ref naming both members", refTarget(issueops.Ref{Key: "k", ID: "bd-1"})},
{"an update that writes nothing", issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{Target: issueops.Ref{ID: "bd-1"}},
}},
}},
{"an edge with no type", issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemDepAdd,
DepAdd: &issueops.DepAddItem{Source: issueops.Ref{ID: "bd-1"}, Target: issueops.Ref{ID: "bd-2"}},
}},
}},
{"a metadata blob that is not JSON", issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemCreate,
Create: &issueops.CreateItem{Issue: &issueops.Issue{
Title: "t", Metadata: json.RawMessage(`{"broken":`),
}},
}},
}},
} {
t.Run(test.name, func(t *testing.T) {
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), test.req)
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("error = %v, want ErrValidation", err)
}
if len(w.calls) != 0 {
t.Errorf("the request reached the wire: %v", w.calls)
}
})
}
// The cap refuses rather than SPLITTING, which is the half a refusal test
// alone would not say: a split plan is several transactions where the
// caller asked for one, and the end gate only ever sees one request.
w := &stubWire{}
_, _ = applyRole(t, w).ApplyBatch(t.Context(), oversized)
if len(w.calls) != 0 {
t.Errorf("the oversized plan was chunked onto the wire: %v", w.calls)
}
}
// TestApplyBatchSendsTheGuardsAndTheLiteralsIntact is the encoding round trip.
//
// TWO CORRUPTIONS ARE THE POINT and neither is visible in a result. The row
// version is int64 END TO END: live tokens run past 5e17, where an IEEE-754
// double's ulp is already 64, so a float anywhere on this path hands the server
// a number NEAR the token that is not it — and the answer would be a
// precondition failure a caller cannot explain. And a metadata value travels as
// the caller's SOURCE LITERAL: the role compares metadata by literal, so 1 and
// 1.0 are not equal and 9007199254740993 is not 9007199254740992 — a float
// round trip changes the VERDICT of a later compare-and-set rather than a
// spelling.
func TestApplyBatchSendsTheGuardsAndTheLiteralsIntact(t *testing.T) {
const token = int64(576460752303423489) // 2^59 + 1: a float64 cannot hold it
const bigInt = `9007199254740993` // 2^53 + 1
version := token
status := issueops.Status("in_progress")
assignee := ""
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Provenance: "wave 1c",
ForceIDPrefix: true,
SkipPerEdgeCycleCheck: true,
Items: []issueops.ApplyItem{
{
Kind: issueops.ItemCreate,
Create: &issueops.CreateItem{
Key: "root",
Issue: &issueops.Issue{
Title: "t",
Metadata: json.RawMessage(`{"exact":` + bigInt + `,"one":1.0}`),
},
MetadataRefs: map[string]issueops.Ref{"spawned": {Key: "child"}},
},
},
{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{
Target: issueops.Ref{Key: "root"},
Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: "x"}},
ExpectedVersion: &version,
ExpectedStatus: &status,
ExpectedAssignee: &assignee,
},
},
{
Kind: issueops.ItemClose,
Close: &issueops.CloseItem{Target: issueops.Ref{ID: "bd-1"}, ExpectedVersion: &version},
},
{
Kind: issueops.ItemDepAdd,
DepAdd: &issueops.DepAddItem{
Source: issueops.Ref{Key: "root"},
Target: issueops.Ref{ID: "bd-1"},
Type: "waits-for",
Metadata: `{"gate":"any-children","seq":` + bigInt + `}`,
},
},
},
})
if err != nil {
t.Fatalf("ApplyBatch: %v", err)
}
body := w.lastApply
if body.Actor != "planner" {
t.Errorf("actor = %q", body.Actor)
}
for member, got := range map[string]*bool{
"force_id_prefix": body.ForceIDPrefix, "skip_per_edge_cycle_check": body.SkipPerEdgeCycleCheck,
} {
if got == nil || !*got {
t.Errorf("%s = %v, want true", member, got)
}
}
if body.Provenance == nil || *body.Provenance != "wave 1c" {
t.Errorf("provenance = %v, want the caller's label", body.Provenance)
}
if len(body.Items) != 4 {
t.Fatalf("the body carries %d items, want 4", len(body.Items))
}
// The guards, on both members that publish one.
// The version guards reach the wire as the token's decimal STRING
// (types.RevisionToken): a JSON number on this member is a 400, and a
// float64 anywhere on the path would answer a number NEAR the token.
update := body.Items[1].Update
if update.ExpectedVersion == nil || *update.ExpectedVersion != types.RevisionToken(token) {
t.Errorf("update expected_version = %v, want %q", update.ExpectedVersion, types.RevisionToken(token))
}
if update.ExpectedStatus == nil || *update.ExpectedStatus != "in_progress" {
t.Errorf("update expected_status = %v", update.ExpectedStatus)
}
// The EMPTY assignee guard is "only if nobody holds it" and is a request,
// not an absence.
if update.ExpectedAssignee == nil {
t.Error("update expected_assignee is absent; the empty string is a real guard")
} else if *update.ExpectedAssignee != "" {
t.Errorf("update expected_assignee = %q, want the empty guard", *update.ExpectedAssignee)
}
if got := body.Items[2].Close.ExpectedVersion; got == nil || *got != types.RevisionToken(token) {
t.Errorf("close expected_version = %v, want %q", got, types.RevisionToken(token))
}
// The literals, on both paths that carry a blob.
for name, raw := range map[string]json.RawMessage{
"create.metadata": json.RawMessage(body.Items[0].Create.Metadata),
"dep_add.metadata": json.RawMessage(body.Items[3].DepAdd.Metadata),
} {
if !strings.Contains(string(raw), bigInt) {
t.Errorf("%s = %s; the source literal %s did not survive — a float64 round trip answers %s",
name, raw, bigInt, "9007199254740992")
}
}
if got := string(body.Items[0].Create.Metadata); !strings.Contains(got, "1.0") {
t.Errorf("create.metadata = %s; the literal 1.0 became 1, which the role compares as a different value", got)
}
// The refs, exactly one member each, and the forward metadata ref carried.
if got := body.Items[1].Update.Target; got.Key == nil || *got.Key != "root" || got.Id != nil {
t.Errorf("update target = %+v, want a key ref naming root and no id", got)
}
refs := body.Items[0].Create.MetadataRefs
if refs == nil {
t.Fatal("the create item dropped its metadata_refs")
}
if got := (*refs)["spawned"]; got.Key == nil || *got.Key != "child" {
t.Errorf("metadata_refs[spawned] = %+v, want a key ref naming child", got)
}
}
// TestApplyBatchAbsentGuardsStayAbsent is the other polarity, and it is the one
// a sentinel would break: 0 is a LEGAL row version — the migration-0054
// backfill wrote it — so encoding "no guard" as 0 would arm a guard on every
// unguarded item, and encoding it as -1 would arm one that can never match.
func TestApplyBatchAbsentGuardsStayAbsent(t *testing.T) {
zero := int64(0)
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{
{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{
Target: issueops.Ref{ID: "bd-1"},
Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: "x"}},
},
},
{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{
Target: issueops.Ref{ID: "bd-2"},
Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: "y"}},
ExpectedVersion: &zero,
},
},
{Kind: issueops.ItemClose, Close: &issueops.CloseItem{Target: issueops.Ref{ID: "bd-3"}}},
},
})
if err != nil {
t.Fatalf("ApplyBatch: %v", err)
}
unguarded := w.lastApply.Items[0].Update
if unguarded.ExpectedVersion != nil {
t.Errorf("an unguarded update sent expected_version = %q; absent is not zero", *unguarded.ExpectedVersion)
}
for member, got := range map[string]*string{
"expected_status": unguarded.ExpectedStatus, "expected_assignee": unguarded.ExpectedAssignee,
} {
if got != nil {
t.Errorf("an unguarded update sent %s = %q", member, *got)
}
}
if got := w.lastApply.Items[1].Update.ExpectedVersion; got == nil || *got != "0" {
t.Errorf("a guard ON ZERO came out as %v; 0 is a token a row really holds and it is spelled \"0\"", got)
}
if got := w.lastApply.Items[2].Close.ExpectedVersion; got != nil {
t.Errorf("an unguarded close sent expected_version = %q", *got)
}
// The two force flags, absent rather than explicitly false.
if w.lastApply.Items[0].Update.ForceClosePolicy != nil || w.lastApply.Items[0].Update.ForceAssigneeTransfer != nil {
t.Error("an update that asked for no bypass sent one explicitly false")
}
if w.lastApply.ForceIDPrefix != nil || w.lastApply.SkipPerEdgeCycleCheck != nil || w.lastApply.Provenance != nil {
t.Error("a request that asked for none of the three optional members sent one anyway")
}
}
// TestApplyBatchRefusesAMisattributedResult is the positional-array guard, and
// it is the one failure on this operation that no assertion about a ROW would
// catch: both rows exist and both were written, so a result read at the wrong
// index reports one item's `changed` and `revision` as another's, and every
// row-level check still passes.
func TestApplyBatchRefusesAMisattributedResult(t *testing.T) {
req := issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Issue: &issueops.Issue{Title: "t"}}},
{Kind: issueops.ItemClose, Close: &issueops.CloseItem{Target: issueops.Ref{ID: "bd-1"}}},
},
}
for _, test := range []struct {
name string
items []apigen.ApplyItemResult
says string
}{
{
name: "one result short",
items: []apigen.ApplyItemResult{{Kind: "create", IssueId: "bd-9"}},
says: "1 batch-apply results for 2 items",
},
{
name: "one result too many",
items: []apigen.ApplyItemResult{
{Kind: "create", IssueId: "bd-9"}, {Kind: "close", IssueId: "bd-1"}, {Kind: "close", IssueId: "bd-2"},
},
says: "3 batch-apply results for 2 items",
},
{
name: "the kinds transposed",
items: []apigen.ApplyItemResult{
{Kind: "close", IssueId: "bd-1"}, {Kind: "create", IssueId: "bd-9"},
},
says: "the results are positional",
},
} {
t.Run(test.name, func(t *testing.T) {
w := &stubWire{applied: &apigen.ApplyBatchResponse{Keys: map[string]string{}, Items: test.items}}
_, err := applyRole(t, w).ApplyBatch(t.Context(), req)
if err == nil {
t.Fatal("a misattributed result was accepted")
}
if !strings.Contains(err.Error(), test.says) {
t.Errorf("error = %v, want it to say %q", err, test.says)
}
})
}
}
// TestApplyBatchCrossChecksKeyedCreatesAgainstTheKeyMap closes the half the kind
// check above cannot see.
//
// A SAME-KIND SWAP IS INVISIBLE TO A KIND COMPARISON: two create items
// transposed still answer "create" at both indexes, so the length agrees, the
// kinds agree, and one row's id, `changed` and `revision` are read as the
// other's. The response carries the bytes that catch it — `keys` maps each
// NAMED create to the id it was bound to, independently of the array's order —
// so a keyed create's result must agree with its own key, and a key the request
// declared that the answer does not carry is a result that cannot be checked at
// all rather than one to pass along.
//
// THE RESIDUAL IS STATED RATHER THAN HIDDEN: an UNKEYED same-kind swap stays
// unverifiable from here. Nothing in the response distinguishes two unnamed
// creates, and nothing in the request could — that is what naming them is for.
// It sits in the same trust class as a server that answered the wrong row
// entirely, and the served assembly is provably in item order.
func TestApplyBatchCrossChecksKeyedCreatesAgainstTheKeyMap(t *testing.T) {
keyed := issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Key: "a", Issue: &issueops.Issue{Title: "a"}}},
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Key: "b", Issue: &issueops.Issue{Title: "b"}}},
},
}
t.Run("two keyed creates with transposed results", func(t *testing.T) {
w := &stubWire{applied: &apigen.ApplyBatchResponse{
Keys: map[string]string{"a": "bd-1", "b": "bd-2"},
Items: []apigen.ApplyItemResult{
{Kind: "create", IssueId: "bd-2", Changed: true, Revision: "7"},
{Kind: "create", IssueId: "bd-1", Changed: true, Revision: "9"},
},
}}
_, err := applyRole(t, w).ApplyBatch(t.Context(), keyed)
if err == nil {
t.Fatal("a same-kind transposition was accepted; the key map says which id each named create was bound to")
}
if !strings.Contains(err.Error(), `key "a"`) || !strings.Contains(err.Error(), "bd-1") {
t.Errorf("error = %v, want it to name the key and the id it was bound to", err)
}
})
t.Run("a key the request declared and the answer does not carry", func(t *testing.T) {
w := &stubWire{applied: &apigen.ApplyBatchResponse{
Keys: map[string]string{"a": "bd-1"},
Items: []apigen.ApplyItemResult{
{Kind: "create", IssueId: "bd-1", Changed: true, Revision: "0"},
{Kind: "create", IssueId: "bd-2", Changed: true, Revision: "0"},
},
}}
_, err := applyRole(t, w).ApplyBatch(t.Context(), keyed)
if err == nil {
t.Fatal("a missing key was passed along; the binding is the one fact the request cannot carry")
}
// The DIAGNOSIS, not just the refusal — M8's lesson applied here. A
// decode that ignored the map's presence bit reads the missing key as
// the empty id and refuses as a DISAGREEMENT, which names the same key
// while telling the caller the server answered the wrong row. It did
// not: it answered with no binding at all.
if !strings.Contains(err.Error(), `bound no id to key "b"`) {
t.Errorf("error = %v, want it to say the key was left UNBOUND rather than bound to something else", err)
}
})
t.Run("the agreeing answer passes, and an UNKEYED create is not checked", func(t *testing.T) {
w := &stubWire{applied: &apigen.ApplyBatchResponse{
Keys: map[string]string{"a": "bd-1", "b": "bd-2"},
Items: []apigen.ApplyItemResult{
{Kind: "create", IssueId: "bd-1", Changed: true, Revision: "0"},
{Kind: "create", IssueId: "bd-2", Changed: true, Revision: "0"},
},
}}
if _, err := applyRole(t, w).ApplyBatch(t.Context(), keyed); err != nil {
t.Fatalf("an agreeing answer was refused: %v", err)
}
// The residual, asserted so it is a documented limit rather than an
// assumption: two UNNAMED creates carry nothing to cross-check, so a
// transposition between them passes. Naming them is what makes it
// checkable, which is the sentence the doc comment ends on.
unkeyed := issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Issue: &issueops.Issue{Title: "a"}}},
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Issue: &issueops.Issue{Title: "b"}}},
},
}
w = &stubWire{applied: &apigen.ApplyBatchResponse{
Keys: map[string]string{},
Items: []apigen.ApplyItemResult{
{Kind: "create", IssueId: "bd-2", Revision: "0"}, {Kind: "create", IssueId: "bd-1", Revision: "0"},
},
}}
if _, err := applyRole(t, w).ApplyBatch(t.Context(), unkeyed); err != nil {
t.Fatalf("an unkeyed pair was refused: %v — nothing in either side distinguishes them", err)
}
})
}
// TestApplyBatchReadsTheAnswerBackWhole is the result decode's positive half.
func TestApplyBatchReadsTheAnswerBackWhole(t *testing.T) {
const token = int64(576460752303423489)
dependsOn := "bd-2"
w := &stubWire{applied: &apigen.ApplyBatchResponse{
Keys: map[string]string{"root": "bd-9"},
Items: []apigen.ApplyItemResult{
{Kind: "create", IssueId: "bd-9", Changed: true, Revision: types.RevisionToken(token)},
{Kind: "dep_add", IssueId: "bd-9", DependsOnId: &dependsOn, Changed: false, Revision: "0"},
},
}}
result, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Key: "root", Issue: &issueops.Issue{Title: "t"}}},
{Kind: issueops.ItemDepAdd, DepAdd: &issueops.DepAddItem{
Source: issueops.Ref{Key: "root"}, Target: issueops.Ref{ID: "bd-2"}, Type: "blocks",
}},
},
})
if err != nil {
t.Fatalf("ApplyBatch: %v", err)
}
if got := result.Keys["root"]; got != "bd-9" {
t.Errorf("Keys[root] = %q, want the minted id", got)
}
if len(result.Items) != 2 {
t.Fatalf("the result carries %d items, want 2", len(result.Items))
}
if result.Items[0].RowVersion != token {
t.Errorf("RowVersion = %d, want %d — the wire's decimal token parsed back losslessly",
result.Items[0].RowVersion, token)
}
if !result.Items[0].Changed {
t.Error("the create's Changed was dropped")
}
if result.Items[1].DependsOnID != "bd-2" {
t.Errorf("the edge's DependsOnID = %q, want bd-2", result.Items[1].DependsOnID)
}
if result.Items[1].Changed {
t.Error("an idempotent re-add was reported as Changed")
}
// The snapshot stops at the wire — ledger row L-apply-snapshot — and the
// role's own leaf says why. It is asserted rather than assumed so a future
// wave that starts hydrating has to come here and say so.
for i, item := range result.Items {
if item.Issue != nil {
t.Errorf("items[%d] carries a snapshot; the wire result is lean (L-apply-snapshot)", i)
}
}
}
// TestApplyBatchRebuildsTheItemAndRefRefusals is the refusal decode.
//
// The request is all or nothing, so `item_*` is the ONLY place the offender
// exists — and the two shapes are told apart by `declared_later`'s PRESENCE,
// which is why the server emits it in both polarities.
func TestApplyBatchRebuildsTheItemAndRefRefusals(t *testing.T) {
req := issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Issue: &issueops.Issue{Title: "t"}}},
{Kind: issueops.ItemClose, Close: &issueops.CloseItem{Target: issueops.Ref{ID: "bd-1"}}},
},
}
t.Run("an item refusal names the item and keeps its sentinel", func(t *testing.T) {
index := 1
kind, key, id := "close", "", "bd-1"
w := &stubWire{errs: []error{&wire.ProblemError{
Status: 409, Code: "not_closable", Err: issueops.ErrCloseBlocked,
ItemIndex: &index, ItemKind: &kind, ItemKey: &key, ItemIssueID: &id,
}}}
_, err := applyRole(t, w).ApplyBatch(t.Context(), req)
var itemErr *issueops.ItemError
if !errors.As(err, &itemErr) {
t.Fatalf("error = %v (%T), want an *ItemError naming the item that refused", err, err)
}
if itemErr.Index != 1 || itemErr.Kind != issueops.ItemClose || itemErr.IssueID != "bd-1" {
t.Errorf("ItemError = %#v, want Index 1, Kind close, IssueID bd-1", itemErr)
}
if !errors.Is(err, issueops.ErrCloseBlocked) {
t.Errorf("the sentinel did not survive the wrapper: %v", err)
}
})
t.Run("a ref refusal is a RefError in both polarities", func(t *testing.T) {
for _, test := range []struct {
later bool
param string
member string
}{
{true, "items[1].close.target", "target"},
{false, "items[1].dep_add.source", "source"},
{false, "items[1].create.metadata_refs", "metadata_refs"},
} {
index, key, later := 1, "child", test.later
w := &stubWire{errs: []error{&wire.ProblemError{
Status: 400, Code: "invalid_argument", Param: test.param, Err: issueops.ErrValidation,
ItemIndex: &index, ItemKey: &key, DeclaredLater: &later,
}}}
_, err := applyRole(t, w).ApplyBatch(t.Context(), req)
var refErr *issueops.RefError
if !errors.As(err, &refErr) {
t.Fatalf("error = %v (%T), want a *RefError", err, err)
}
if refErr.DeclaredLater != test.later {
t.Errorf("RefError.DeclaredLater = %v, want %v: the two diagnoses are what a caller acts on",
refErr.DeclaredLater, test.later)
}
if refErr.Index != 1 || refErr.Key != "child" {
t.Errorf("RefError = %#v, want Index 1 and Key child", refErr)
}
if refErr.Member != test.member {
t.Errorf("RefError.Member = %q, want %q", refErr.Member, test.member)
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("the RefError does not match ErrValidation: %v", err)
}
}
})
t.Run("a key refusal that names no item does not blame the first one", func(t *testing.T) {
// Unreachable against this server, and hardened anyway because
// RefError.Index has no absent state: answering 0 would name the FIRST
// item as the offender on a refusal that named none.
later := true
w := &stubWire{errs: []error{&wire.ProblemError{
Status: 400, Code: "invalid_argument", Err: issueops.ErrValidation, DeclaredLater: &later,
}}}
_, err := applyRole(t, w).ApplyBatch(t.Context(), req)
var refErr *issueops.RefError
if errors.As(err, &refErr) {
t.Errorf("a key refusal naming no item was rebuilt as %#v; index 0 is the first item, not 'unknown'", refErr)
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("error = %v, want the sentinel through", err)
}
})
t.Run("a refusal that names no item travels unwrapped", func(t *testing.T) {
w := &stubWire{errs: []error{&wire.ProblemError{
Status: 400, Code: "invalid_argument", Param: "items", Err: issueops.ErrValidation,
}}}
_, err := applyRole(t, w).ApplyBatch(t.Context(), req)
var itemErr *issueops.ItemError
if errors.As(err, &itemErr) {
t.Errorf("a refusal naming no item was wrapped as %#v; index 0 would be a claim about an item "+
"this refusal says nothing about", itemErr)
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("error = %v, want the sentinel through", err)
}
})
}
// TestTheEncodedApplyPatchDocumentUsesOnlyPublishedMembers is
// TestTheEncodedPatchDocumentUsesOnlyPublishedMembers for the plan's own patch,
// and it is a separate gate because the two documents' allowlists differ in
// BOTH directions: this one publishes owner and not parent_id.
func TestTheEncodedApplyPatchDocumentUsesOnlyPublishedMembers(t *testing.T) {
published := bodyMembers(t, reflect.TypeOf(apigen.ApplyPatchBody{}))
patch := issueops.IssuePatch{}
setEvery := reflect.ValueOf(&patch).Elem()
var wantMembers []string
for name, how := range shapeNamed(t, "applyBatch/update/patch").carried {
setPatchField(t, setEvery.FieldByName(name))
wantMembers = append(wantMembers, how.member)
}
document, err := encodeApplyPatch(patch)
if err != nil {
t.Fatalf("a patch setting every carried member refused: %v", err)
}
for name := range document {
if !published[name] {
t.Errorf("the encoded apply patch carries %q, which ApplyPatchBody does not publish: %v",
name, sortedKeys(published))
}
}
slices.Sort(wantMembers)
got := sortedKeys(toSet(document))
if strings.Join(got, ",") != strings.Join(wantMembers, ",") {
t.Errorf("the encoded apply patch carries\n %v\nwant the table's carried members\n %v", got, wantMembers)
}
}
// TestTheApplyLabelPatchIsTheWholeEdit pins the one place this document is
// WIDER than PATCH /v0/beads/issues/{id}'s: a plan edits a label set it did not
// compose, so a REMOVAL has to be expressible without reading the set back.
func TestTheApplyLabelPatchIsTheWholeEdit(t *testing.T) {
w := &stubWire{}
_, err := applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{
Target: issueops.Ref{ID: "bd-1"},
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{
Replace: issueops.Field[[]string]{Set: true, Value: []string{"base"}},
Add: []string{"added"},
Remove: []string{"gone"},
}},
},
}},
})
if err != nil {
t.Fatalf("a full label patch refused: %v", err)
}
labels, ok := w.lastApply.Items[0].Update.Patch["labels"].(map[string]any)
if !ok {
t.Fatalf("the encoded patch carries labels = %#v, want the ordered edit", w.lastApply.Items[0].Update.Patch["labels"])
}
for member, want := range map[string][]string{
"replace": {"base"}, "add": {"added"}, "remove": {"gone"},
} {
got, ok := labels[member].([]string)
if !ok || !slices.Equal(got, want) {
t.Errorf("labels.%s = %#v, want %v", member, labels[member], want)
}
}
// A SET replacement holding no labels CLEARS every label, which is the
// state a plain slice could not carry.
w = &stubWire{}
_, err = applyRole(t, w).ApplyBatch(t.Context(), issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{
Target: issueops.Ref{ID: "bd-1"},
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{
Replace: issueops.Field[[]string]{Set: true},
}},
},
}},
})
if err != nil {
t.Fatalf("a label clear refused: %v", err)
}
labels = w.lastApply.Items[0].Update.Patch["labels"].(map[string]any)
got, ok := labels["replace"].([]string)
if !ok || len(got) != 0 {
t.Errorf("the clear encoded replace = %#v, want an empty array", labels["replace"])
}
// AND IT HAS TO MARSHAL AS ONE. A nil []string is len 0 and satisfies every
// assertion above while serializing to JSON `null`, which this member does
// not accept — so the clear is checked at the byte level, which is the level
// the server reads it at.
encoded, err := json.Marshal(labels["replace"])
if err != nil {
t.Fatalf("marshaling the label clear: %v", err)
}
if string(encoded) != "[]" {
t.Errorf("the clear marshals as %s, want []; a JSON null on this member is not a clear", encoded)
}
if _, present := labels["add"]; present {
t.Error("the clear invented an add member")
}
}

View file

@ -0,0 +1,370 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/batchcloser.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"unicode"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/issueops"
)
// readySortPolicies names the only three sort policies a ClaimNext filter
// accepts, mirroring internal/workapi.BuildReadyFilter's vocabulary. It is
// redeclared here rather than imported for the reason list_walk.go, order.go
// and releaser.go each give: depguard denies internal/workapi to this package.
//
// A value outside this list is a deterministic request-validation failure —
// RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure — and that
// holds REGARDLESS of whether the v0 wire can carry a ClaimNext at all: a bad
// sort policy is caught before the capability question is even asked, the same
// way an empty actor or a blank item id is.
var readySortPolicies = []string{"hybrid", "oldest", "priority"}
// validateReadySortPolicy refuses a ClaimNext filter's sort policy if it names
// anything outside readySortPolicies. An empty policy is the caller leaving it
// to the default and is always legal here.
func validateReadySortPolicy(policy string) error {
if policy == "" || slices.Contains(readySortPolicies, policy) {
return nil
}
return invalid("invalid sort policy '%s'. Valid values: hybrid, priority, oldest", policy)
}
// maxWireBatchCloseItems is the wire's cap on one batch close: maxBatchCloseItems
// in internal/httpapi/batch_close.go, redeclared here because importing the
// server would drag the storage engine into a client. A batch over the bound
// REFUSES rather than chunking — see ledger row L-close-cap and CloseBatch below.
const maxWireBatchCloseItems = 100
// httpBatchCloser serves issueops.BatchCloser over the v0 wire.
//
// WHERE THE WIRE CARRIES issues.batchClose, the whole CloseBatchRequest is one
// wire call: many items, per-item outcomes, and the atomic ClaimNext included.
// That is the operation this role was always waiting for — `bd close a b c` is
// one transaction with at most one history entry, and only a single wire call
// preserves that where a loop of closeIssue could not.
//
// WHERE IT DOES NOT — a server too old to advertise the capability — the role
// falls back to the ONE shape a bare closeIssue can honestly compose: a single
// item with no ClaimNext, which is the shape `bd close <id>` issues for the
// common case. Every other shape refuses in that leg rather than looping, because
// N sequential closes are N transactions and N history entries where the contract
// promises one, and ClaimNext runs INSIDE the closes' transaction and can see an
// unblocking the batch itself produced. See refuseUnservedCloseShape.
//
// CLIENT-SIDE VALIDATION happens first on both legs: the role contract calls an
// empty actor, an empty batch or a blank item id invalid, so they must not
// consume a write slot to be told so. The item cap is enforced here too, and it
// refuses — never chunks — for the reason L16's dependency-add cap does.
type httpBatchCloser struct {
store *Store
wire WriteWire
}
var _ issueops.BatchCloser = (*httpBatchCloser)(nil)
// CloseBatch closes the batch, on the wire's batchClose operation where the
// server advertises it and by composing a single closeIssue where it does not.
func (b *httpBatchCloser) CloseBatch(ctx context.Context, req issueops.CloseBatchRequest) (result issueops.CloseBatchResult, err error) {
// 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.
defer func() { err = b.store.inexpressible("BatchCloser.CloseBatch", err) }()
// Request validation first, and all of it client-side. A non-nil error here
// carries no outcomes, which the method's contract requires.
if err := requireActor(req.Actor); err != nil {
return issueops.CloseBatchResult{}, err
}
if len(req.Items) == 0 {
return issueops.CloseBatchResult{}, invalid("a batch close names no items")
}
for i, item := range req.Items {
if item.IssueID == "" {
return issueops.CloseBatchResult{}, invalid("items[%d].issue_id is required", i)
}
}
// ClaimNext's OWN request rules run before the capability question is asked,
// the same ordering ReadyClaimer.ClaimNext uses: a filter that is invalid on
// every backend (a limit, an offset, a brief projection, or an unknown sort
// policy) is ErrValidation here, not a refusal of a capability the wire
// might have had. RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure
// pins this — the item is real and closeable, so a backend that ran the
// batch before discovering the bad filter would still have to undo it.
if req.ClaimNext != nil {
if err := storageops.ValidateClaimNextRequest(issueops.ClaimNextRequest{Actor: req.Actor, Filter: *req.ClaimNext}); err != nil {
return issueops.CloseBatchResult{}, err
}
if err := validateReadySortPolicy(req.ClaimNext.Sort); err != nil {
return issueops.CloseBatchResult{}, err
}
// Past its own validation, ClaimNext still refuses unconditionally: OSS's
// apigen.BatchCloseRequest and BatchCloseResponse publish no
// claim_next/claimed_next member at all, so there is no shape — valid or
// not — for this field to encode into. See ledger row
// W-CloseBatchRequest.ClaimNext.
return issueops.CloseBatchResult{}, refuse(encode.OpBatchCloseIssues, "W-CloseBatchRequest.ClaimNext")
}
// The wire's item cap, enforced before the dial and NEVER by chunking: a
// split batch is N transactions where the caller asked for one. L-close-cap.
if len(req.Items) > maxWireBatchCloseItems {
return issueops.CloseBatchResult{}, refuse(encode.OpBatchCloseIssues, "L-close-cap")
}
served, err := b.servesBatchClose(ctx)
if err != nil {
return issueops.CloseBatchResult{}, err
}
if served {
return b.serveBatch(ctx, req)
}
return b.serveComposedSingle(ctx, req)
}
// servesBatchClose reports whether the server advertises issues.batchClose. It
// forces the one lazy handshake the store already owns and reads the cached
// capability list, so the check costs at most one round trip and none once the
// handshake has run.
//
// IT RETURNS THE HANDSHAKE'S ERROR, and servesListSort (list_walk.go) — the
// same probe against the same snapshot — deliberately swallows its own and
// reports false. The asymmetry is the design, and neither should be "fixed"
// into the other: this is a WRITE whose only legs both dial, so a handshake
// that cannot be obtained means the close cannot be attempted at all and
// hiding that would turn a transport failure into a silent down-level route.
// listIssues is a baseline READ whose fallback leg needs no handshake and
// worked before the capability existed, so propagating there would newly fail
// a `bd list` that succeeds today.
func (b *httpBatchCloser) servesBatchClose(ctx context.Context) (bool, error) {
snap, err := b.store.snapshot(ctx)
if err != nil {
return false, err
}
if snap == nil {
return false, nil
}
token, _ := wire.CapabilityFor(wire.OpBatchCloseIssues)
return slices.Contains(snap.Capabilities, token), nil
}
// serveBatch sends the whole request on one issues:batchClose call and reads the
// per-item outcomes back.
func (b *httpBatchCloser) serveBatch(ctx context.Context, req issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) {
body := batchCloseBody(req)
resp, err := b.wire.BatchCloseIssues(ctx, body)
if err != nil {
return issueops.CloseBatchResult{}, err
}
return decodeBatchCloseResult(req, resp)
}
// serveComposedSingle is the down-level fallback: the single-item, no-ClaimNext
// shape composed onto closeIssue, with every other shape refused citing the
// missing capability. It is TODAY's serve, reached only when issues.batchClose
// is absent.
func (b *httpBatchCloser) serveComposedSingle(ctx context.Context, req issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) {
if err := b.store.refuseUnservedCloseShape(req); err != nil {
return issueops.CloseBatchResult{}, err
}
item := req.Items[0]
res, err := b.wire.CloseIssue(ctx, item.IssueID, closeBody(req.Actor, item.Reason, req.Session, req.Force))
if err != nil {
if outcome, ok := perItemCloseRefusal(item.IssueID, err); ok {
// A per-item refusal is a RESULT and never the method's error. The
// batch of one has nothing left to commit, but the caller still reads
// its answer out of Outcomes like any other batch.
return issueops.CloseBatchResult{Outcomes: []issueops.CloseOutcome{outcome}}, nil
}
return issueops.CloseBatchResult{}, err
}
issue := res.Issue
return issueops.CloseBatchResult{Outcomes: []issueops.CloseOutcome{{
IssueID: item.IssueID,
Issue: &issue,
Changed: !res.AlreadyClosed,
OpenChildren: res.OpenChildren,
}}}, nil
}
// batchCloseBody projects the role request onto the wire body. Reasons ride per
// item, and session and force are request-wide. ClaimNext has no member to
// project onto — CloseBatch refuses it unconditionally before this body is
// ever built (W-CloseBatchRequest.ClaimNext), so req.ClaimNext is always nil
// here.
func batchCloseBody(req issueops.CloseBatchRequest) apigen.BatchCloseRequest {
items := make([]apigen.BatchCloseItem, len(req.Items))
for i, item := range req.Items {
items[i] = apigen.BatchCloseItem{Id: item.IssueID}
if item.Reason != "" {
reason := item.Reason
items[i].Reason = &reason
}
}
body := apigen.BatchCloseRequest{Actor: req.Actor, Items: items}
if req.Session != "" {
session := req.Session
body.Session = &session
}
if req.Force {
force := true
body.Force = &force
}
return body
}
// decodeBatchCloseResult reads the wire response back into the role's result.
//
// The server's contract is one outcome per item in request order; a length that
// disagrees is a broken server, which is the METHOD's failure and carries no
// outcomes rather than a per-item one the caller might trust.
//
// The result's ClaimedNext always stays nil: OSS's apigen.BatchCloseResponse
// publishes no claimed_next member for this client to decode, and CloseBatch
// refuses any request that asked for one before a body is ever sent (see
// ledger row W-CloseBatchRequest.ClaimNext), so there is nothing a server
// could answer here that this client would read.
func decodeBatchCloseResult(req issueops.CloseBatchRequest, resp *apigen.BatchCloseResponse) (issueops.CloseBatchResult, error) {
if len(resp.Outcomes) != len(req.Items) {
return issueops.CloseBatchResult{}, fmt.Errorf(
"bd serve returned %d batch-close outcomes for %d items", len(resp.Outcomes), len(req.Items))
}
outcomes := make([]issueops.CloseOutcome, len(resp.Outcomes))
for i := range resp.Outcomes {
outcomes[i] = decodeBatchCloseOutcome(resp.Outcomes[i])
}
return issueops.CloseBatchResult{Outcomes: outcomes}, nil
}
// decodeBatchCloseOutcome reads ONE wire outcome.
//
// `code` IS THE DISCRIMINATOR, which is the wire's own rule: present means the
// item refused and nothing was written for it; absent means it succeeded and
// the snapshot, `already_closed` and `open_children` are all present. The
// members are FLAT on the outcome rather than nested under an error object, so
// `open_children` is read from the same field in both branches and means two
// different things depending on which one — see the schema.
func decodeBatchCloseOutcome(item apigen.CloseOutcome) issueops.CloseOutcome {
out := issueops.CloseOutcome{IssueID: item.IssueId}
if item.Code != nil {
out.Err = perItemCloseError(item.IssueId, item)
return out
}
// A successful outcome carries the snapshot; already_closed is the idempotent
// re-close (Changed false), and open_children is what a forced close observed.
out.Issue = item.Issue
if item.OpenChildren != nil {
out.OpenChildren = *item.OpenChildren
}
out.Changed = item.AlreadyClosed == nil || !*item.AlreadyClosed
return out
}
// perItemCloseError is the shared code -> error table that turns a refused wire
// outcome into the canonical close vocabulary a local batch would have
// returned, so a caller classifies a remote per-item refusal with the same
// errors.Is/errors.As arms it already has:
//
// not_found -> issueops.ErrNotFound
// not_closable + open_children -> *issueops.CloseOpenChildrenError
// not_closable -> issueops.ErrCloseBlocked
// an unknown code -> *wire.UnknownItemCodeError (the generic
// typed per-item error, so version skew lands
// as a typed refusal rather than a silent gap)
//
// The member-presence discriminator on not_closable is the same one the single
// close's 409 uses, and it comes from the typed field, never from parsing prose.
//
// It is only ever called with a refused outcome — Code non-nil — which the one
// caller above guarantees.
func perItemCloseError(issueID string, item apigen.CloseOutcome) error {
var code string
if item.Code != nil {
code = *item.Code
}
switch code {
case codeNotFound:
return issueops.ErrNotFound
case codeNotClosable:
if item.OpenChildren != nil {
return &issueops.CloseOpenChildrenError{IssueID: issueID, OpenChildren: *item.OpenChildren}
}
return issueops.ErrCloseBlocked
default:
var detail string
if item.Detail != nil {
detail = stripItemControlRunes(*item.Detail)
}
return &wire.UnknownItemCodeError{
IssueID: issueID,
Code: stripItemControlRunes(code),
Detail: detail,
}
}
}
// The two per-item refusal codes this outcome can carry. They are the
// `Problem.code` spellings, restated here rather than imported because
// importing the server package would drag the storage engine into a client.
const (
codeNotFound = "not_found"
codeNotClosable = "not_closable"
)
// stripItemControlRunes removes control runes from a server-controlled per-item
// string before it becomes a typed error, mirroring the wire problem mapper's
// own source-layer strip: the unknown-code carrier reaches the same per-id
// stderr sinks a decoded ProblemError does.
func stripItemControlRunes(s string) string {
return strings.Map(func(r rune) rune {
if unicode.IsControl(r) || r == '
' || r == '
' {
return -1
}
return r
}, s)
}
// refuseUnservedCloseShape names the shape that refused in the DOWN-LEVEL leg, so
// the refusal says which of the two reasons it is rather than "batch close is
// unsupported". It survives only in that leg: where issues.batchClose is
// advertised, every shape is served on one wire call and nothing reaches here.
//
// ClaimNext is not checked here: CloseBatch refuses it unconditionally, on
// both legs, before either serving method is called (see ledger row
// W-CloseBatchRequest.ClaimNext), so req.ClaimNext is always nil by the time
// a request reaches this leg.
func (s *Store) refuseUnservedCloseShape(req issueops.CloseBatchRequest) error {
if len(req.Items) > 1 {
return s.unsupported("BatchCloser.CloseBatch(multi-item)")
}
return nil
}
// perItemCloseRefusal separates the close vocabulary an ITEM answers with from
// the failures the METHOD answers with, for the composed single-item leg.
//
// The three it recognizes are exactly what Lifecycle.Close returns, and exactly
// what the wire's problem mapper reconstructs: not_found becomes ErrNotFound,
// not_closable carrying open_children becomes *CloseOpenChildrenError, and
// not_closable without it becomes ErrCloseBlocked. Everything else — a transport
// failure, a 503, an unknown 4xx — is the method's, because it says nothing about
// this item and would be a lie as a per-item outcome.
func perItemCloseRefusal(issueID string, err error) (issueops.CloseOutcome, bool) {
var openChildren *issueops.CloseOpenChildrenError
switch {
case errors.As(err, &openChildren):
case errors.Is(err, issueops.ErrNotFound):
case errors.Is(err, issueops.ErrCloseBlocked):
default:
return issueops.CloseOutcome{}, false
}
return issueops.CloseOutcome{IssueID: issueID, Err: err}, true
}

View file

@ -0,0 +1,296 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/batchcreator.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"reflect"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/issueops"
)
// maxBatchCreateItems mirrors the wire's own bound (internal/httpapi's
// batch_create.go, and the document's maxItems). It is checked here for
// maxDeleteIDs' reason: the request IS the transaction, so splitting a longer
// plan into two requests would turn one atomic create into two — and half a
// file is the outcome the role's all-or-nothing promise exists to make
// impossible. A caller that really has more than a hundred issues splits the
// plan deliberately, which is the document's own advice.
const maxBatchCreateItems = 100
// batchCreateCarriedIssueMembers is the wire's item vocabulary: the eight
// members of apigen.BatchCreateItem that describe the issue itself, keyed by the
// types.Issue field each one carries.
//
// It is the ALLOWLIST half of refuse-not-drop for this operation. What it does
// not name is refused, and there is no third arm — see refuseUnwirableIssue.
//
// Status and CreatedBy are deliberately absent, each for its own reason, and
// neither belongs in roleIgnoredCreateIssueMembers below: both are genuinely
// ACCEPTED by the role's canonical create rules (CreateRequest.Issue's doc,
// which BatchCreateItem.Issue inherits without exception), so silently
// dropping either would be exactly the data loss refuse-not-drop exists to
// prevent.
// - Status: apigen.BatchCreateItem publishes no status member at all, unlike
// single create's apigen.CreateIssueRequest (which does, see
// createCarriedIssueMembers). A populated value is correctly refused. The
// common case is not lost: PreparePublicCreateRequest defaults an empty
// Status to StatusOpen on every backend, so a caller that only ever wants
// the default (cmd/bd/markdown.go's `bd create --file`) leaves it unset
// rather than spelling out "open" and tripping this refusal. That removes
// ONE refusal from `bd create --file`, not all of them: its request still
// always names a Provenance (W-CreateBatchRequest.Provenance) and usually
// an Owner from git config (W-BatchCreateItem.Issue), so it still refuses
// over this wire.
// - CreatedBy: apigen.BatchCreateItem has no member for it either, but the
// batch server stamps every item's created_by from the request's actor
// (internal/httpapi/batch_create.go), as single create does. A CreatedBy
// naming the actor is therefore carried BY the actor
// (actorStampedCreateMember below), and any other value is refused rather
// than silently replaced by the stamp.
var batchCreateCarriedIssueMembers = map[string]string{
"Title": "title",
"Description": "description",
"Design": "design",
"AcceptanceCriteria": "acceptance_criteria",
"Priority": "priority",
"IssueType": "issue_type",
"Assignee": "assignee",
"Labels": "labels",
}
// roleIgnoredCreateIssueMembers are the members the ROLE ITSELF ignores on a
// create, each with the reason, taken from issueops.CreateRequest.Issue's own
// list: "It ignores ContentHash, RowVersion, lease state, compaction state,
// routing overrides, hydration flags, and derived fields."
//
// They are not divergences and must not be refused. A local create drops them
// too, so refusing here would make an http workspace REJECT a request every
// other backend accepts — the opposite failure from the one refuse-not-drop
// guards, and just as wrong.
var roleIgnoredCreateIssueMembers = map[string]string{
"ContentHash": "derived: recomputed from the stored content",
"RowVersion": "derived: the engine stamps its own row lock",
"LeaseExpiresAt": "lease state: a create grants no lease",
"HeartbeatAt": "lease state: a create grants no lease",
"LeaseGrantedNode": "lease state: a create grants no lease",
"CompactionLevel": "compaction state: nothing is compacted at create",
"CompactedAt": "compaction state: nothing is compacted at create",
"CompactedAtCommit": "compaction state: nothing is compacted at create",
"OriginalSize": "compaction state: nothing is compacted at create",
"SourceRepo": "routing override: which local database owns the row",
"IDPrefix": "routing override: id generation is the server's",
"PrefixOverride": "routing override: id generation is the server's",
"WispPlaneOverride": "routing override: import's explicit plane marker",
"IsLitePartial": "hydration flag: describes a READ, not a create",
}
// actorStampedCreateMember reports whether a populated issue member is one the
// server writes from the request's actor rather than reads from the body, and
// already holds the value that stamp will write.
//
// CreatedBy is the one such member: every create shape stamps created_by from
// the actor (internal/httpapi's create.go, batch_create.go and batch_apply.go).
// It is neither carried nor role-ignored — a local create stores whatever the
// issue names — so it is carried BY THE ACTOR: a CreatedBy that names the actor,
// which is what `bd create`, `bd create --file` and the graph apply send,
// arrives as written, and any other value would be silently replaced by the
// stamp and is refused.
func actorStampedCreateMember(member string, issue *issueops.Issue, actor string) bool {
return member == "CreatedBy" && issue.CreatedBy == actor
}
// httpBatchCreator serves issueops.BatchCreator from the batchCreateIssues
// custom method (design D8 row 14) — the write side of `bd create --file`.
//
// THE REQUEST IS THE TRANSACTION on both sides, and that is the whole reason
// this composes at all: the wire's operation is itself all-or-nothing, so one
// role call is one request is one server-side transaction with at most one
// history entry. Nothing here loops, and nothing here chunks.
//
// WHAT THE WIRE'S ITEM CANNOT SAY is where the work is. apigen.BatchCreateItem
// publishes eight content members and a dependency list; issueops reads a whole
// types.Issue, and the role accepts far more of it than that — an explicit id,
// the wisp flags, metadata, the gate and molecule fields, every timestamp.
// Every one of those is refused rather than dropped (ledger row
// W-BatchCreateItem.Issue): a create that reported success having silently
// planted an issue in the durable tier that the caller asked to be ephemeral is
// data loss the caller has no way to learn about.
//
// The refusal is decided by REFLECTION over the two tables above rather than by
// a hand-written switch, so a member added to types.Issue tomorrow is refused
// the day it lands instead of dropped until someone notices.
type httpBatchCreator struct {
store *Store
wire WriteWire
}
var _ issueops.BatchCreator = (*httpBatchCreator)(nil)
// CreateBatch dials POST /v0/beads/issues:batchCreate.
func (b *httpBatchCreator) CreateBatch(ctx context.Context, req issueops.CreateBatchRequest) (result issueops.CreateBatchResult, err error) {
// Write-side parity with reads: decorates a bare *encode.RefusedError —
// however deeply batchCreateItem/batchCreateEdge/refuseUnwirableIssue
// nested it inside an "items[%d]..." prefix — into *InexpressibleError so
// errors.As(err, &unsupported) reaches *storage.ErrUnsupported, same as
// inexpressible does for a read role. The original composite message
// (including that prefix) is preserved in the decorated error's own text.
defer func() { err = b.store.inexpressible("BatchCreator.CreateBatch", err) }()
if err := requireActor(req.Actor); err != nil {
return issueops.CreateBatchResult{}, err
}
if len(req.Items) == 0 {
return issueops.CreateBatchResult{}, invalid("a batch create names no items")
}
if len(req.Items) > maxBatchCreateItems {
return issueops.CreateBatchResult{}, refuse(encode.OpBatchCreateIssues, "L-batchcreate-bound")
}
if req.Provenance != "" {
return issueops.CreateBatchResult{}, refuse(encode.OpBatchCreateIssues, "W-CreateBatchRequest.Provenance")
}
if req.ForceIDPrefix {
return issueops.CreateBatchResult{}, refuse(encode.OpBatchCreateIssues, "W-CreateBatchRequest.ForceIDPrefix")
}
items := make([]apigen.BatchCreateItem, 0, len(req.Items))
for i, item := range req.Items {
wireItem, err := batchCreateItem(i, item, req.Actor)
if err != nil {
return issueops.CreateBatchResult{}, err
}
items = append(items, wireItem)
}
res, err := b.wire.BatchCreateIssues(ctx, apigen.BatchCreateRequest{Actor: req.Actor, Items: items})
if err != nil {
return issueops.CreateBatchResult{}, err
}
// One entry per requested item, in request order, never nil. The response is
// read back rather than the request echoed because the GENERATED IDS are the
// one fact the request cannot carry — and a server that answered a different
// length would be caught here rather than by an index panic upstream.
if len(res.Items) != len(req.Items) {
return issueops.CreateBatchResult{}, fmt.Errorf(
"batchCreateIssues answered %d issues for %d items; the operation is all-or-nothing and has no partial outcome",
len(res.Items), len(req.Items))
}
issues := make([]*issueops.Issue, len(res.Items))
for i := range res.Items {
issue := res.Items[i]
issues[i] = &issue
}
return issueops.CreateBatchResult{Issues: issues}, nil
}
// batchCreateItem projects one role item onto the wire's item.
func batchCreateItem(index int, item issueops.BatchCreateItem, actor string) (apigen.BatchCreateItem, error) {
if item.Issue == nil {
return apigen.BatchCreateItem{}, invalid("items[%d] carries no issue", index)
}
if len(item.Issue.Comments) > 0 || len(item.Issue.Dependencies) > 0 {
// The ROLE's own rule, not a wire divergence: edges are supplied through
// the item's own Dependencies, and a create batch has no way to supply
// comments at all. A local backend refuses this too.
return apigen.BatchCreateItem{}, invalid(
"items[%d].Issue carries comments or dependencies; supply edges through the item's own Dependencies", index)
}
if err := refuseUnwirableIssue(index, item.Issue, actor); err != nil {
return apigen.BatchCreateItem{}, err
}
// Priority is sent ALWAYS, unlike the five optional strings: 0 is P0 and a
// real request, so an absent member — which the server reads as "the
// workspace default" — would silently reprioritize every critical issue in a
// plan. The pointer addresses a local copy, never the caller's field.
priority := item.Issue.Priority
wireItem := apigen.BatchCreateItem{Title: item.Issue.Title, Priority: &priority}
setItemString(&wireItem.Description, item.Issue.Description)
setItemString(&wireItem.Design, item.Issue.Design)
setItemString(&wireItem.AcceptanceCriteria, item.Issue.AcceptanceCriteria)
setItemString(&wireItem.Assignee, item.Issue.Assignee)
setItemString(&wireItem.IssueType, string(item.Issue.IssueType))
if len(item.Issue.Labels) > 0 {
labels := append([]string(nil), item.Issue.Labels...)
wireItem.Labels = &labels
}
if len(item.Dependencies) > 0 {
edges := make([]apigen.BatchCreateDependency, 0, len(item.Dependencies))
for j, dep := range item.Dependencies {
edge, err := batchCreateEdge(index, j, dep)
if err != nil {
return apigen.BatchCreateItem{}, err
}
edges = append(edges, edge)
}
wireItem.Dependencies = &edges
}
return wireItem, nil
}
// batchCreateEdge projects one requested edge. The wire's edge carries a target
// and a type and nothing else, so the three members issueops.CreateDependency
// adds refuse.
func batchCreateEdge(index, j int, dep issueops.CreateDependency) (apigen.BatchCreateDependency, error) {
where := func(err error) error { return fmt.Errorf("items[%d].dependencies[%d]: %w", index, j, err) }
switch {
case dep.TargetID == "":
return apigen.BatchCreateDependency{}, where(invalid("target_id is required"))
case dep.Type == "":
return apigen.BatchCreateDependency{}, where(invalid("type is required"))
case dep.Reverse:
return apigen.BatchCreateDependency{}, where(refuse(encode.OpBatchCreateIssues, "W-CreateDependency.Reverse"))
case dep.Metadata != "":
return apigen.BatchCreateDependency{}, where(refuse(encode.OpBatchCreateIssues, "W-CreateDependency.Metadata"))
case dep.ThreadID != "":
return apigen.BatchCreateDependency{}, where(refuse(encode.OpBatchCreateIssues, "W-CreateDependency.ThreadID"))
}
return apigen.BatchCreateDependency{TargetId: dep.TargetID, Type: string(dep.Type)}, nil
}
// refuseUnwirableIssue is the other half of the allowlist: every populated
// member of the issue that is neither carried by the wire, nor ignored by the
// role, nor stamped from the actor (actorStampedCreateMember).
//
// It answers the FIRST offender in declaration order, which is deterministic —
// a caller fixing one member at a time must not see the reported member depend
// on map iteration.
func refuseUnwirableIssue(index int, issue *issueops.Issue, actor string) error {
value := reflect.ValueOf(*issue)
shape := value.Type()
for i := range shape.NumField() {
field := shape.Field(i)
if !field.IsExported() {
continue
}
if _, carried := batchCreateCarriedIssueMembers[field.Name]; carried {
continue
}
if _, ignored := roleIgnoredCreateIssueMembers[field.Name]; ignored {
continue
}
if value.Field(i).IsZero() || actorStampedCreateMember(field.Name, issue, actor) {
continue
}
// The ledger row is the vocabulary; the member name is the fact the row
// cannot carry, because one row covers the whole population.
return fmt.Errorf("items[%d].Issue.%s: %w",
index, field.Name, refuse(encode.OpBatchCreateIssues, "W-BatchCreateItem.Issue"))
}
return nil
}
// setItemString writes an optional wire member, leaving it absent when the role
// carried nothing. An empty string and an omitted member mean the same thing on
// every one of these five, so absent is the honest encoding.
func setItemString(dest **string, value string) {
if value == "" {
return
}
v := value
*dest = &v
}

View file

@ -0,0 +1,130 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/batchgetter.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"net/http"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/issueops"
)
// httpBatchGetter serves batchGetIssues (POST /v0/beads/issues:batchGet) —
// the role behind gc's ready veto and the CLI's own id-resolution passes,
// once they move off one Get per id.
//
// IT IS A READ, DIALED AS A POST: the request carries an `ids` array no GET
// query string can hold cleanly at the operation's own cap (MaxGetManyIDs),
// the same reason queryIssues dials POST rather than GET. Nothing about that
// changes the role's nature — it writes nothing, takes no actor and no
// version guard — so this goes through dispatch directly, the way Counter
// and Querier do, rather than through roleWire: there is no write envelope
// here for a WriteWire method to carry.
//
// THE CAP AND THE BLANK-ID CHECK ARE DONE HERE, BEFORE THE DIAL, and that is
// a deliberate divergence from how every other validation on this surface
// works: everywhere else, the role's own ErrValidation reaches the wire
// through the server's failure translation and this client decodes it back.
// batch_get.go's failBatchGetErr does not do that — it collapses EVERY
// validation failure, the cap included, into one generic
// InvalidArgument/invalid_value problem with no distinguishing code, so a
// server round trip can never hand this client the exact
// *issueops.TooManyIDsError{Requested, Cap} the role's own contract and the
// conformance suite's errors.As checks require. checkGetManyIDs reproduces
// internal/storage/issueops.ValidateGetManyRequest's exact two checks, in
// its exact order (the cap, counted before deduplication; then the first
// blank entry) — not by importing that package, which is the storage
// engine's shared body and does not belong in a transport client, but by
// restating its two rules against the same public issueops types the role
// itself is spelled in.
type httpBatchGetter struct{ store *Store }
var _ issueops.BatchGetter = (*httpBatchGetter)(nil)
// GetMany dials POST /v0/beads/issues:batchGet.
//
// The ids are sent VERBATIM — not trimmed, not deduplicated, not reordered —
// checkDeleteIDs' sibling reason: the wire's own `ids` member document says
// duplicates collapse and the answer comes back in first-mention order,
// which is exactly the normalization ValidateGetManyRequest's callers
// (ExecuteGetMany, via DedupeGetManyIDs and FinishGetMany) apply server-side.
// Redoing it here would be a second implementation of a rule that already
// has one, on the operation where a disagreement about which id was "first"
// would reorder the answer rather than merely duplicate work.
func (g *httpBatchGetter) GetMany(ctx context.Context, req issueops.GetManyRequest) (issueops.GetManyResult, error) {
if err := checkGetManyIDs(req.IDs); err != nil {
return issueops.GetManyResult{}, err
}
if len(req.IDs) == 0 {
// Answered locally rather than dialed: an empty request is legal and
// the role promises an empty, non-nil answer, so there is nothing a
// round trip could add — the same early return ExecuteGetMany itself
// takes after deduplication.
return issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}, nil
}
var body apigen.BatchGetIssuesResult
if err := g.store.dispatch(ctx, wire.Request{
Op: wire.OpBatchGetIssues,
Method: http.MethodPost,
Path: wire.PathIssuesBatchGet,
Body: apigen.BatchGetIssuesRequest{
Ids: append([]string(nil), req.IDs...),
},
}, &body); err != nil {
return issueops.GetManyResult{}, err
}
issues := make([]*issueops.Issue, 0, len(body.Issues))
for i := range body.Issues {
entry := body.Issues[i]
// BatchGetIssue.Revision is this operation's only wire spelling of the
// row's token — Issue.RowVersion is json:"-", the same stitch
// getIssuesByExactID and role_reader.go's getIssue make for their own
// responses. Without it, every resolved issue would carry a RowVersion
// of 0, and a caller that fed one into a guarded write would get a
// spurious precondition_failed instead of none.
version, err := parseRevision("BatchGetter.GetMany", entry.Revision)
if err != nil {
return issueops.GetManyResult{}, err
}
issue := entry.Issue
issue.RowVersion = version
issues = append(issues, &issue)
}
missing := make([]string, len(body.Missing))
copy(missing, body.Missing)
return issueops.GetManyResult{
Issues: issues,
Missing: missing,
}, nil
}
// checkGetManyIDs applies the request-intrinsic refusals before the dial,
// in the SAME ORDER internal/storage/issueops.ValidateGetManyRequest applies
// them server-side (batch_get.go's batchGetRequest comment says so
// explicitly): the cap first, counted on the request as sent, before any
// deduplication; then the first blank entry.
//
// The blank check is a LITERAL id == "", not a trimmed one: GetManyRequest.IDs
// are exact ids, and DedupeGetManyIDs' own doc says this role does not trim
// whitespace the way DeleteRequest.IDs does, because a caller that padded an
// id is naming a genuinely different, unresolvable id rather than making a
// typo this role should forgive. checkDeleteIDs' TrimSpace check does not
// apply here for that reason.
func checkGetManyIDs(ids []string) error {
if len(ids) > issueops.MaxGetManyIDs {
return &issueops.TooManyIDsError{Requested: len(ids), Cap: issueops.MaxGetManyIDs}
}
for i, id := range ids {
if id == "" {
return fmt.Errorf("%w: get many id at position %d is empty", issueops.ErrValidation, i)
}
}
return nil
}

View file

@ -0,0 +1,197 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/bridge.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"net/http"
"net/url"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The off-role ready bridge, and the raw issue read the `--parent` walk probes
// with.
//
// The bridge exists because `bd ready`'s listing is still raw at tip
// (cmd/bd/ready.go:172 and :211): the front door has not moved onto
// issueops.Reader, so a reverse types.WorkFilter mapper is required until it
// does. D8 calls it deliberately throwaway and it is — what is not throwaway is
// the rule it holds to: every field it cannot express REFUSES, because a dropped
// filter widens a result set invisibly and the server can only reject the
// parameters it receives (L12).
//
// The SEARCH bridge is not here. Its two shapes are id resolution's (resolve.go)
// and the descendant walk's, and both live beside the surfaces that own them.
// GetReadyWork serves `bd ready`'s text listing.
//
// It is the projection and GetReadyWorkWithCounts is the primitive, not the
// other way round: the wire hydrates the three cardinalities either way, because
// the page element IS types.IssueWithCounts.
func (s *Store) GetReadyWork(ctx context.Context, filter types.WorkFilter) ([]*types.Issue, error) {
rows, err := s.GetReadyWorkWithCounts(ctx, filter)
if err != nil {
return nil, err
}
out := make([]*types.Issue, 0, len(rows))
for _, row := range rows {
out = append(out, row.Issue)
}
return out, nil
}
// GetReadyWorkWithCounts is the same listing with the counts `bd ready --json`
// prints.
//
// ONE REQUEST, NO PAGING. listReadyWork publishes no cursor — its sort policies
// admit no keyset predicate — so `limit` and the server's own has_more ARE the
// page contract, exactly as they are for the Reader.Ready role this bridge dies
// in favor of. The request is built by the same encoder and dialed through the
// same door, so the two spellings of "list ready work" cannot drift apart.
func (s *Store) GetReadyWorkWithCounts(ctx context.Context, filter types.WorkFilter) ([]*types.IssueWithCounts, error) {
rows, _, err := s.readyBridgePage(ctx, "GetReadyWorkWithCounts", filter)
return rows, err
}
// GetReadyWorkWithCountsAndTotal is GetReadyWorkWithCounts plus the size of the
// whole ready set, which `bd ready --json` prints as its pagination total.
//
// AT MOST TWO REQUESTS. listReadyWork's ReadyPage carries items and has_more
// but no total, so the total cannot ride the page the way it does in a SQL
// backend's single transaction. When the server says the page is the whole set
// (has_more false — always the case for an unlimited listing) the total IS the
// page length and no second request is made. Only a truncated page pays one
// countReadyWork round trip, encoded from the same filter by
// encode.ReadyBridgeCountParams, which is the round trip the text path's
// ReadyCounter role already makes.
//
// The two requests are two server transactions, not one snapshot: a write
// landing between them can make the total disagree with the page by that
// write. The total is clamped to at least the page length so the envelope
// never reports fewer items than it carries.
//
// Every refusal the listing makes is made before either request (the count
// encoder runs the listing's encoder), so a filter the wire cannot express —
// ExcludeIDs included — fails here exactly as it fails GetReadyWorkWithCounts.
func (s *Store) GetReadyWorkWithCountsAndTotal(ctx context.Context, filter types.WorkFilter) ([]*types.IssueWithCounts, int, error) {
const op = "GetReadyWorkWithCountsAndTotal"
countParams, err := encode.ReadyBridgeCountParams(filter)
if err != nil {
return nil, 0, s.inexpressible(op, err)
}
rows, hasMore, err := s.readyBridgePage(ctx, op, filter)
if err != nil {
return nil, 0, err
}
if !hasMore {
return rows, len(rows), nil
}
var body apigen.ReadyCount
if err := s.dispatch(ctx, wire.Request{
Op: wire.OpCountReadyWork,
Method: http.MethodGet,
Path: wire.PathReadyCount,
Query: countParams,
}, &body); err != nil {
return nil, 0, err
}
total := int(body.Total)
if total < len(rows) {
total = len(rows)
}
return rows, total, nil
}
// readyBridgePage is the one listReadyWork request both bridge listings make,
// returning the rows and the server's has_more.
func (s *Store) readyBridgePage(ctx context.Context, op string, filter types.WorkFilter) ([]*types.IssueWithCounts, bool, error) {
params, err := encode.ReadyBridgeParams(filter)
if err != nil {
return nil, false, s.inexpressible(op, err)
}
var body apigen.ReadyPage
if err := s.dispatch(ctx, wire.Request{
Op: wire.OpListReadyWork,
Method: http.MethodGet,
Path: wire.PathReady,
Query: params,
}, &body); err != nil {
return nil, false, err
}
// filter.Lite IS ReadyRequest.Brief — internal/workapi assigns one to the
// other — so the two doors have to stamp the same marker or the same request
// answers differently depending on which one it came in. That agreement is
// the whole of E-WorkFilter.Lite's retirement note.
rows := wireRows(body.Items, filter.Lite)
// The cap bounds the rows this client accepted off the wire, which for a
// cursorless operation is one page. It still fires: a caller whose page is
// wider than their cap gets exit 2 rather than a silently oversized answer.
if filter.MaxRows > 0 && len(rows) > filter.MaxRows {
return nil, false, &storageops.ErrTooManyRows{
Found: len(rows),
Cap: filter.MaxRows,
Source: filter.MaxRowsSource,
}
}
return rows, body.HasMore, nil
}
// GetIssue serves getIssue. It is the `bd list --parent` walk's
// parent-existence probe and the molecule loader's read half.
//
// A MISS IS (nil, nil), NOT AN ERROR. That is the raw method's own contract and
// the walk depends on it: getHierarchicalChildren reads a nil result as "parent
// issue not found" and prints that, where an error would print the transport's
// vocabulary instead.
func (s *Store) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
if id == "" {
return nil, nil
}
path, err := wire.IssuePath(id)
if err != nil {
return nil, err
}
// Neither row list: this is the existence probe and the loader's read, and
// both discard everything but the row. Asking for dependents and comments
// would buy two joins nobody reads.
var details types.IssueDetails
err = s.dispatch(ctx, wire.Request{
Op: wire.OpGetIssue,
Method: http.MethodGet,
Path: path,
Query: url.Values{},
IssueID: id,
}, &details)
if errors.Is(err, issueops.ErrNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
// The detail view carries labels in a field of its OWN rather than on the
// embedded issue, and the local GetIssue hydrates them onto the issue.
// Lifting them across is what makes the two answers the same value — the
// same correction getIssuesByExactID makes for the resolver's fast path.
issue := details.Issue
if len(issue.Labels) == 0 && len(details.Labels) > 0 {
issue.Labels = append([]string(nil), details.Labels...)
}
// Issue.RowVersion is json:"-", so the decode above left it at 0 and
// Revision — getIssue's only wire spelling of the token — carries the real
// value. A molecule loader (or any other caller of this read) that then
// guards a write off issue.RowVersion must see the row's actual token, not
// every row's as though none had ever been written.
version, err := parseRevision("getIssue", details.Revision)
if err != nil {
return nil, err
}
issue.RowVersion = version
return &issue, nil
}

View file

@ -0,0 +1,157 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/brief_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// THE BRIEF DOOR: the projection marker, stamped client-side.
//
// `brief` is a request parameter on GET /v0/beads/issues and GET
// /v0/beads/ready (#5586) and this client sends it on both pages plus the ready
// bridge, so the server leaves the six heavy text columns unselected and the
// rows come back with them zero-valued. What does NOT come back is the fact that
// they were projected: types.Issue.IsLitePartial is `json:"-"`, so it never
// crosses, and a projected row is byte-identical to a genuinely textless one.
//
// THE ROW SAYS SO IN PROCESS AND THE WIRE SAYS SO BY HAVING BEEN ASKED, which is
// upstream's own resolution of the ambiguity (issueops/reader.go, ListRequest.
// Brief: "a wire consumer distinguishes them by having asked"). This client IS
// the consumer that asked, so it is the layer that can stamp — and it is the
// only one: the server cannot send a member the type does not marshal, and a
// caller above this seam has no way to know which of its rows came from a
// projected page.
//
// WHY IT IS NOT OPTIONAL. backend/conformance/reader_contract.go's
// assertReaderBriefRow hard-fails a projected row carrying IsLitePartial=false —
// "a blank body and a genuinely textless one are indistinguishable without it" —
// so the three Brief contracts cannot be adopted by any leg that does not stamp.
// That is why deferring the marker to this wave was safe: the contract forces
// it, loudly, at the moment the contract is wired.
// briefWire answers each page with one row whose heavy text is EMPTY, which is
// what a `brief` page really looks like on the wire — and is exactly why the
// marker cannot be inferred from the payload.
type briefWire struct {
recordingWire
lastQuery string
}
func (b *briefWire) Do(ctx context.Context, req wire.Request, out any) error {
b.lastQuery = req.Query.Get("brief")
row := apigen.IssueWithCounts{Issue: &types.Issue{ID: "http-brief-1", Title: "t"}}
switch body := out.(type) {
case *apigen.ReadyPage:
*body = apigen.ReadyPage{Items: []apigen.IssueWithCounts{row}}
return nil
case *apigen.IssuesPage:
*body = apigen.IssuesPage{Items: []apigen.IssueWithCounts{row}}
return nil
}
return b.recordingWire.Do(ctx, req, out)
}
func briefStore(t *testing.T) (*Store, *briefWire) {
t.Helper()
w := &briefWire{}
return New(testTarget(t), w, &apigen.ContextResponse{}), w
}
// TestBriefListingsStampTheProjectionMarker covers all THREE doors the parameter
// reaches: the listing, the ready page, and the off-role ready bridge whose
// legacy WorkFilter.Lite IS ReadyRequest.Brief under another name.
//
// The three are checked together rather than one per case because the bug this
// pins is asymmetric wiring: a client that stamped the listing and not the ready
// page would answer the same request two ways depending on which door it came
// in, which is the exact disagreement E-WorkFilter.Lite's ledger row warns about.
func TestBriefListingsStampTheProjectionMarker(t *testing.T) {
ctx := context.Background()
for _, tc := range []struct {
name string
brief bool
}{
{"projected", true},
{"hydrated", false},
} {
t.Run(tc.name, func(t *testing.T) {
store, w := briefStore(t)
reader, err := store.IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
list, err := reader.List(ctx, issueops.ListRequest{Brief: tc.brief})
if err != nil {
t.Fatalf("List(): %v", err)
}
assertBriefMarker(t, "Reader.List", list.Items, tc.brief)
assertBriefParam(t, "Reader.List", w.lastQuery, tc.brief)
ready, err := reader.Ready(ctx, issueops.ReadyRequest{Brief: tc.brief})
if err != nil {
t.Fatalf("Ready(): %v", err)
}
assertBriefMarker(t, "Reader.Ready", ready.Items, tc.brief)
assertBriefParam(t, "Reader.Ready", w.lastQuery, tc.brief)
// StatusOpen is not decoration: the bridge's derived-default
// inversion refuses any other status, because listReadyWork
// publishes none and the server re-derives exactly this one. Every
// real `bd ready` filter carries it for the same reason.
bridged, err := store.GetReadyWorkWithCounts(ctx, types.WorkFilter{
Status: types.StatusOpen,
Lite: tc.brief,
})
if err != nil {
t.Fatalf("GetReadyWorkWithCounts(): %v", err)
}
assertBriefMarker(t, "the ready bridge", bridged, tc.brief)
assertBriefParam(t, "the ready bridge", w.lastQuery, tc.brief)
})
}
}
// assertBriefMarker holds one page's rows to the marker the request earned.
//
// BOTH DIRECTIONS ARE ASSERTED, and the false one is not filler: a client that
// stamped unconditionally would tell every caller of an ordinary `bd list` that
// its rows are partial, which sends a consumer to refetch a body it already has
// — the same cost as the missing stamp, pointed the other way.
func assertBriefMarker(t *testing.T, what string, rows []*types.IssueWithCounts, want bool) {
t.Helper()
if len(rows) == 0 {
t.Fatalf("%s answered no rows; this case cannot assert the marker on an empty page", what)
}
for _, row := range rows {
if row == nil || row.Issue == nil {
t.Fatalf("%s answered a row with no issue", what)
}
if row.IsLitePartial != want {
t.Errorf("%s returned IsLitePartial = %v on %s, want %v: a projected row and a genuinely textless one are indistinguishable without it",
what, row.IsLitePartial, row.ID, want)
}
}
}
// assertBriefParam is the other half of the same statement: the marker must
// describe a projection that was actually REQUESTED. Stamping a row the server
// hydrated in full would be this client inventing the fact rather than reporting
// it.
func assertBriefParam(t *testing.T, what, got string, want bool) {
t.Helper()
if want && got != "true" {
t.Errorf("%s sent brief=%q, want %q — the marker has to describe a projection the request asked for", what, got, "true")
}
if !want && got != "" {
t.Errorf("%s sent brief=%q on a hydrated read, want it absent", what, got)
}
}

View file

@ -0,0 +1,872 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/bulk_roles_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"encoding/json"
"errors"
"reflect"
"slices"
"sort"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The three BULK writes — sweepIssues, deleteIssues, batchCreateIssues — at the
// role boundary, with no server in sight.
//
// What is provable here and nowhere else is the REQUEST: which members reached
// the wire, which refused before the dial, and which never reached it at all.
// The served tier (served_bulk_test.go) answers the other half — what the
// server does with them — and cannot see a dropped member, because a server
// only rejects the parameters it receives.
func bulkSweeper(t *testing.T, w *stubWire) issueops.Sweeper {
t.Helper()
sweeper, err := stubStore(t, w).Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
return sweeper
}
func bulkDeleter(t *testing.T, w *stubWire) issueops.Deleter {
t.Helper()
deleter, err := stubStore(t, w).Deleter()
if err != nil {
t.Fatalf("Deleter(): %v", err)
}
return deleter
}
func bulkCreator(t *testing.T, w *stubWire) issueops.BatchCreator {
t.Helper()
creator, err := stubStore(t, w).BatchCreator()
if err != nil {
t.Fatalf("BatchCreator(): %v", err)
}
return creator
}
// TestSweepSendsEveryNarrowingMemberExplicitly is the sweep's whole request
// mapping in one assertion, and the two BOOLEANS are why it exists.
//
// protect_referenced DEFAULTS ON over the wire — an unauthenticated surface is
// where a default must be the guarded one — while the role's zero value is off.
// A client that omitted a false one would silently turn `bd prune
// --ignore-references` into a protected sweep and report skips the caller never
// asked for: a NARROWER answer than the request, which is refuse-not-drop's
// failure class in the other direction.
func TestSweepSendsEveryNarrowingMemberExplicitly(t *testing.T) {
cutoff := time.Date(2026, 4, 1, 12, 0, 0, 0, time.UTC)
w := &stubWire{}
if _, err := bulkSweeper(t, w).Sweep(t.Context(), issueops.SweepRequest{
Actor: "sweeper",
Tier: issueops.SweepDurable,
ClosedBefore: &cutoff,
IDPattern: "bd-*",
ProtectReferenced: false,
DryRun: true,
}); err != nil {
t.Fatalf("Sweep(): %v", err)
}
got := w.lastSweep
if got.Tier != apigen.Durable {
t.Errorf("tier = %q, want %q", got.Tier, apigen.Durable)
}
if got.Actor == nil || *got.Actor != "sweeper" {
t.Errorf("actor = %v, want \"sweeper\"", got.Actor)
}
if got.Pattern == nil || *got.Pattern != "bd-*" {
t.Errorf("pattern = %v, want \"bd-*\"", got.Pattern)
}
if got.ClosedBefore == nil || !got.ClosedBefore.Equal(cutoff) {
t.Errorf("closed_before = %v, want %v", got.ClosedBefore, cutoff)
}
if got.ProtectReferenced == nil {
t.Fatal("protect_referenced was omitted; the wire defaults it ON, so an omitted false is a protection the caller declined")
}
if *got.ProtectReferenced {
t.Error("protect_referenced = true for a request that asked for false")
}
if got.DryRun == nil || !*got.DryRun {
t.Errorf("dry_run = %v, want true", got.DryRun)
}
}
// TestTheBulkWritesOmitABlankActorRatherThanSendingOne pins the one member
// whose EMPTY spelling the two sides disagree about.
//
// The role accepts an empty Actor — a deleted row leaves nothing to attribute
// the deletion on — and the server refuses an actor that is empty AFTER
// TRIMMING. So the test is the TRIM, not `!= ""`: a tab-and-space Actor is an
// accepted request against every local backend, and forwarding it would turn
// that request into a 400 on this backend alone.
func TestTheBulkWritesOmitABlankActorRatherThanSendingOne(t *testing.T) {
for _, actor := range []string{"", " ", "\t \n"} {
w := &stubWire{}
if _, err := bulkSweeper(t, w).Sweep(t.Context(), issueops.SweepRequest{
Tier: issueops.SweepEphemeral, Actor: actor,
}); err != nil {
t.Fatalf("Sweep(actor=%q): %v", actor, err)
}
if w.lastSweep.Actor != nil {
t.Errorf("sweep actor = %q for a blank Actor %q; the server refuses one that is empty after trimming",
*w.lastSweep.Actor, actor)
}
w = &stubWire{}
if _, err := bulkDeleter(t, w).Delete(t.Context(), issueops.DeleteRequest{
IDs: []string{"bd-1"}, Force: true, Actor: actor,
}); err != nil {
t.Fatalf("Delete(actor=%q): %v", actor, err)
}
if w.lastDelete.Actor != nil {
t.Errorf("delete actor = %q for a blank Actor %q", *w.lastDelete.Actor, actor)
}
}
// A blank Actor on the batch create is a REFUSAL rather than an omission:
// batchCreateIssues publishes actor as required, and the role's own contract
// says a create batch must name its creator.
w := &stubWire{}
_, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: " ", Items: []issueops.BatchCreateItem{{Issue: &issueops.Issue{Title: "t"}}},
})
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("CreateBatch(blank actor) = %v, want ErrValidation", err)
}
if len(w.calls) != 0 {
t.Errorf("a blank-actor batch create dialed %v", w.calls)
}
// The pattern rides along: absent matches every bead in the tier, and
// sending an empty string would be a second spelling of the same request.
w = &stubWire{}
if _, err := bulkSweeper(t, w).Sweep(t.Context(), issueops.SweepRequest{Tier: issueops.SweepEphemeral}); err != nil {
t.Fatalf("Sweep(): %v", err)
}
if w.lastSweep.Pattern != nil {
t.Errorf("pattern = %q for a request that named none", *w.lastSweep.Pattern)
}
}
// TestSweepRefusesATierTheWireDoesNotPublish is the ONE refusal this role
// decides for itself, and it decides it because the tier is an ENUM the client
// has to map. Everything else the role's contract calls invalid — the
// require-a-filter gate, the glob — is refused by the server's own copy of the
// role, so re-deciding it here would be a second definition of the rule that
// keeps a workspace's history from being erased by an omission.
func TestSweepRefusesATierTheWireDoesNotPublish(t *testing.T) {
for _, tier := range []issueops.SweepTier{"", "wisps"} {
w := &stubWire{}
_, err := bulkSweeper(t, w).Sweep(t.Context(), issueops.SweepRequest{Tier: tier, IDPattern: "*"})
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Sweep(tier=%q) error = %v, want ErrValidation", tier, err)
}
if len(w.calls) != 0 {
t.Errorf("Sweep(tier=%q) dialed %v; a request the role calls invalid must not reach a shared server", tier, w.calls)
}
}
}
// TestSweepDoesNotWriteThroughTheCallersCutoff pins the pointer the role
// promises never to write through. A marshaler is a read today; the copy is
// what keeps it a read after the next helper is added.
func TestSweepDoesNotWriteThroughTheCallersCutoff(t *testing.T) {
cutoff := time.Date(2026, 4, 1, 12, 0, 0, 0, time.UTC)
w := &stubWire{}
if _, err := bulkSweeper(t, w).Sweep(t.Context(), issueops.SweepRequest{
Tier: issueops.SweepDurable, ClosedBefore: &cutoff,
}); err != nil {
t.Fatalf("Sweep(): %v", err)
}
if w.lastSweep.ClosedBefore == &cutoff {
t.Error("the request body aliases the caller's cutoff pointer rather than copying it")
}
}
// TestSweepResultCarriesEveryWireMember is the RESPONSE half of the sweep's
// mapping. SweepResult is deliberately not x-go-type-pinned, so the projection
// 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) {
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,
},
ReferencedIds: &[]string{"bd-1"},
}}
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")
if !reflect.DeepEqual(result.ReferencedIDs, []string{"bd-1"}) {
t.Errorf("ReferencedIDs = %v, want [bd-1]", result.ReferencedIDs)
}
}
// TestDeleteResultCarriesEveryWireMember is the same guard on the delete, whose
// result is likewise unpinned.
func TestDeleteResultCarriesEveryWireMember(t *testing.T) {
w := &stubWire{deleted: &apigen.DeleteIssuesResult{
DryRun: true, Deleted: 2, Dependencies: 3, Labels: 4, Events: 5,
ReferencesUpdated: 6, Orphaned: &[]string{"bd-9"},
}}
result, err := bulkDeleter(t, w).Delete(t.Context(), issueops.DeleteRequest{IDs: []string{"bd-1"}, Force: true})
if err != nil {
t.Fatalf("Delete(): %v", err)
}
assertEveryFieldPopulated(t, "DeleteResult", reflect.ValueOf(result))
if !reflect.DeepEqual(result.Orphaned, []string{"bd-9"}) {
t.Errorf("Orphaned = %v, want [bd-9]", result.Orphaned)
}
}
// TestDeleteSendsTheIDsVerbatim pins that the client normalizes NOTHING.
//
// The role collapses duplicates and trims, and so does the server's copy of it.
// Doing it again here would be a second implementation of "which ids were
// named" on the one operation where a disagreement deletes the wrong rows — and
// normalizing in place would hand the caller back a shorter, reordered version
// of the list a CLI then echoes.
func TestDeleteSendsTheIDsVerbatim(t *testing.T) {
ids := []string{" bd-1 ", "bd-1", "bd-2"}
snapshot := append([]string(nil), ids...)
w := &stubWire{}
if _, err := bulkDeleter(t, w).Delete(t.Context(), issueops.DeleteRequest{
IDs: ids, Actor: "deleter", Cascade: true, Force: true, DryRun: true,
}); err != nil {
t.Fatalf("Delete(): %v", err)
}
if !reflect.DeepEqual(w.lastDelete.Ids, snapshot) {
t.Errorf("ids = %v, want the caller's list verbatim %v", w.lastDelete.Ids, snapshot)
}
if !reflect.DeepEqual(ids, snapshot) {
t.Errorf("the caller's slice changed across the call: %v", ids)
}
for name, got := range map[string]*bool{
"cascade": w.lastDelete.Cascade, "force": w.lastDelete.Force, "dry_run": w.lastDelete.DryRun,
} {
if got == nil || !*got {
t.Errorf("%s = %v, want true", name, got)
}
}
if w.lastDelete.Actor == nil || *w.lastDelete.Actor != "deleter" {
t.Errorf("actor = %v, want \"deleter\"", w.lastDelete.Actor)
}
// The body must not alias the caller's slice: a marshaler reads it, but a
// shared backing array is one helper away from a write.
if len(w.lastDelete.Ids) > 0 && &w.lastDelete.Ids[0] == &ids[0] {
t.Error("the request body aliases the caller's id slice rather than copying it")
}
}
// TestDeleteRefusesAnUnusableIDList pins the refusals the role's own contract
// states, all of them decidable from the request alone. The empty case is the
// dangerous one: answering it as a cheerful "deleted 0" is how a caller whose
// id list came out empty concludes the workspace was already clean.
func TestDeleteRefusesAnUnusableIDList(t *testing.T) {
for _, ids := range [][]string{nil, {}, {" "}, {"bd-1", ""}} {
w := &stubWire{}
_, err := bulkDeleter(t, w).Delete(t.Context(), issueops.DeleteRequest{IDs: ids, Force: true})
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Delete(%v) error = %v, want ErrValidation", ids, err)
}
if len(w.calls) != 0 {
t.Errorf("Delete(%v) dialed %v; a request the role calls invalid must not reach a shared server", ids, w.calls)
}
}
}
// TestDeleteRefusesMoreIDsThanTheWireCarries is ledger row L-delete-bound's
// pin, and it asserts the boundary from BOTH sides: exactly the bound serves,
// one more refuses, and the refusal never dials.
//
// "Never dials" is the assertion that matters. What this row forbids is
// SPLITTING: two requests are two transactions and two history entries where
// the contract promises one, and the dependents guard — which can only see the
// ids in front of it — would refuse a pair the caller deliberately listed
// together.
func TestDeleteRefusesMoreIDsThanTheWireCarries(t *testing.T) {
ids := make([]string, maxDeleteIDs)
for i := range ids {
ids[i] = "bd-" + strings.Repeat("0", 4) + string(rune('a'+i%26))
}
w := &stubWire{}
if _, err := bulkDeleter(t, w).Delete(t.Context(), issueops.DeleteRequest{IDs: ids, Force: true}); err != nil {
t.Fatalf("Delete(%d ids) at the bound: %v", maxDeleteIDs, err)
}
if len(w.calls) != 1 {
t.Errorf("a delete at the bound dialed %v, want one request", w.calls)
}
w = &stubWire{}
_, err := bulkDeleter(t, w).Delete(t.Context(), issueops.DeleteRequest{IDs: append(ids, "bd-over"), Force: true})
assertRefusedBy(t, err, "L-delete-bound")
if len(w.calls) != 0 {
t.Errorf("a delete over the bound dialed %v; it must refuse rather than split", w.calls)
}
}
// TestDeleteSendsTheRowVersionPrecondition is the compare-and-delete guard's
// round trip, and it is the operation where getting the encoding wrong is worst:
// the close it mirrors leaves a row behind to compare afterwards and this leaves
// nothing at all.
//
// The absent leg is the one that matters. `expected_version` 0 is a legal token
// — the migration-0054 backfill left rows holding it — so a client that encoded
// "no guard" as 0 would arm a guard on every unguarded delete, and the requests
// it then refused would be exactly the ones aimed at never-written rows.
//
// The MULTI-ID refusal is deliberately NOT anticipated here. The wire refuses a
// guard beside more than one DISTINCT id, and distinctness is measured after
// trimming and collapsing duplicates — the same normalization this role sends
// its ids verbatim to avoid re-implementing, on the operation where a
// disagreement about which ids were named deletes the wrong rows. So that
// refusal is the server's, and the served tier asserts it end to end.
func TestDeleteSendsTheRowVersionPrecondition(t *testing.T) {
version := int64(9)
for _, tc := range []struct {
name string
want *int64
req issueops.DeleteRequest
}{
{name: "guarded", want: &version, req: issueops.DeleteRequest{ExpectedVersion: &version}},
{name: "zero is a real token", want: new(int64), req: issueops.DeleteRequest{ExpectedVersion: new(int64)}},
{name: "unguarded", want: nil, req: issueops.DeleteRequest{}},
} {
t.Run(tc.name, func(t *testing.T) {
w := &stubWire{}
req := tc.req
req.IDs = []string{"bd-1"}
if _, err := bulkDeleter(t, w).Delete(t.Context(), req); err != nil {
t.Fatalf("Delete: %v", err)
}
assertExpectedVersion(t, "deleteIssues", w.lastDelete.ExpectedVersion, tc.want)
})
}
}
// TestBatchCreateRefusesMoreItemsThanTheWireCarries is L-batchcreate-bound's
// pin, on the same argument: the request IS the transaction.
func TestBatchCreateRefusesMoreItemsThanTheWireCarries(t *testing.T) {
items := make([]issueops.BatchCreateItem, maxBatchCreateItems)
for i := range items {
items[i] = issueops.BatchCreateItem{Issue: &issueops.Issue{Title: "t"}}
}
w := &stubWire{}
if _, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{Actor: "w", Items: items}); err != nil {
t.Fatalf("CreateBatch(%d items) at the bound: %v", maxBatchCreateItems, err)
}
if len(w.calls) != 1 {
t.Errorf("a batch at the bound dialed %v, want one request", w.calls)
}
w = &stubWire{}
over := append(items, issueops.BatchCreateItem{Issue: &issueops.Issue{Title: "over"}})
_, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{Actor: "w", Items: over})
assertRefusedBy(t, err, "L-batchcreate-bound")
if len(w.calls) != 0 {
t.Errorf("a batch over the bound dialed %v; it must refuse rather than split", w.calls)
}
}
// TestBatchCreateSendsTheItemMembersTheWireCarries is the item mapping, member
// by member. PRIORITY is the one to read twice: 0 is P0/critical and a real
// request, so it is sent always — an absent member is the workspace default,
// which would silently reprioritize every critical issue in a plan.
func TestBatchCreateSendsTheItemMembersTheWireCarries(t *testing.T) {
w := &stubWire{}
if _, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{{
Issue: &issueops.Issue{
Title: "the title", Description: "d", Design: "des", AcceptanceCriteria: "ac",
Priority: 0, IssueType: types.TypeBug, Assignee: "a", Labels: []string{"alpha"},
},
Dependencies: []issueops.CreateDependency{{TargetID: "bd-9", Type: types.DepBlocks}},
}},
}); err != nil {
t.Fatalf("CreateBatch(): %v", err)
}
body := w.lastBatchCreate
if body.Actor != "planner" {
t.Errorf("actor = %q, want \"planner\"", body.Actor)
}
if len(body.Items) != 1 {
t.Fatalf("items = %d, want 1", len(body.Items))
}
item := body.Items[0]
if item.Title != "the title" {
t.Errorf("title = %q", item.Title)
}
if item.Priority == nil || *item.Priority != 0 {
t.Errorf("priority = %v, want an explicit 0: absent means the workspace default", item.Priority)
}
for name, got := range map[string]*string{
"description": item.Description, "design": item.Design,
"acceptance_criteria": item.AcceptanceCriteria, "assignee": item.Assignee,
"issue_type": item.IssueType,
} {
if got == nil {
t.Errorf("%s was omitted for a populated field", name)
}
}
if item.Labels == nil || !reflect.DeepEqual(*item.Labels, []string{"alpha"}) {
t.Errorf("labels = %v, want [alpha]", item.Labels)
}
if item.Dependencies == nil || len(*item.Dependencies) != 1 {
t.Fatalf("dependencies = %v, want one edge", item.Dependencies)
}
if edge := (*item.Dependencies)[0]; edge.TargetId != "bd-9" || edge.Type != string(types.DepBlocks) {
t.Errorf("edge = %+v, want {bd-9 blocks}", edge)
}
}
// TestBatchCreateReadsTheGeneratedIDsBackOffTheResponse pins the one fact the
// request cannot carry and every front door needs.
func TestBatchCreateReadsTheGeneratedIDsBackOffTheResponse(t *testing.T) {
w := &stubWire{created: &apigen.BatchCreateResponse{Items: []apigen.Issue{
{ID: "bd-11", Title: "one", Labels: []string{"alpha"}},
{ID: "bd-12", Title: "two"},
}}}
result, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{
{Issue: &issueops.Issue{Title: "one"}},
{Issue: &issueops.Issue{Title: "two"}},
},
})
if err != nil {
t.Fatalf("CreateBatch(): %v", err)
}
if len(result.Issues) != 2 {
t.Fatalf("Issues = %d, want 2", len(result.Issues))
}
for i, want := range []string{"bd-11", "bd-12"} {
if result.Issues[i] == nil || result.Issues[i].ID != want {
t.Errorf("Issues[%d] = %v, want id %q in request order", i, result.Issues[i], want)
}
}
if labels := result.Issues[0].Labels; !reflect.DeepEqual(labels, []string{"alpha"}) {
t.Errorf("Issues[0].Labels = %v, want [alpha]: the snapshot is promised hydrated", labels)
}
if result.Issues[0] == result.Issues[1] {
t.Error("the result entries alias one issue")
}
}
// TestBatchCreateDoesNotWriteThroughTheCallersItems pins the no-mutation
// promise, and the ID is the field that matters: the role assigns one and it
// must land on the RESULT, never on the caller's issue — an implementation that
// wrote it back would leave the caller's next create refusing its own struct as
// an occupied id.
//
// The whole request is compared, not just the id, because CreateBatchRequest
// travels by value: Items and the issues it points at are what a body could
// otherwise write through, and a label slice handed straight to a marshaler is
// one helper away from being written through too.
func TestBatchCreateDoesNotWriteThroughTheCallersItems(t *testing.T) {
issue := &issueops.Issue{
Title: "caller owned", Priority: 2, IssueType: types.TypeTask, Labels: []string{"kept"},
}
request := issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{{
Issue: issue,
Dependencies: []issueops.CreateDependency{{TargetID: "bd-9", Type: types.DepBlocks}},
}},
}
snapshot := issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{{
Issue: &issueops.Issue{
Title: "caller owned", Priority: 2, IssueType: types.TypeTask, Labels: []string{"kept"},
},
Dependencies: []issueops.CreateDependency{{TargetID: "bd-9", Type: types.DepBlocks}},
}},
}
w := &stubWire{created: &apigen.BatchCreateResponse{Items: []apigen.Issue{
{ID: "bd-assigned", Title: "caller owned", Labels: []string{"kept", "server-added"}},
}}}
result, err := bulkCreator(t, w).CreateBatch(t.Context(), request)
if err != nil {
t.Fatalf("CreateBatch(): %v", err)
}
if result.Issues[0].ID != "bd-assigned" {
t.Errorf("the assigned id is %q on the result, want bd-assigned", result.Issues[0].ID)
}
if issue.ID != "" {
t.Errorf("the caller's issue was stamped with id %q; the assigned id belongs to the result", issue.ID)
}
if !reflect.DeepEqual(request, snapshot) {
t.Errorf("CreateBatch mutated the caller's request:\n got %+v\nwant %+v", *request.Items[0].Issue, *snapshot.Items[0].Issue)
}
// The labels on the wire are a COPY: the request body outlives this call
// inside a marshaler, and a shared backing array would let it grow through
// the caller's slice.
if body := w.lastBatchCreate.Items[0].Labels; body == nil || &(*body)[0] == &issue.Labels[0] {
t.Error("the request body aliases the caller's label slice rather than copying it")
}
}
// TestBatchCreateRefusesAShortAnswer pins the all-or-nothing read-back. A
// server answering a different length has no partial outcome to describe, so
// the client reports it rather than indexing into it.
func TestBatchCreateRefusesAShortAnswer(t *testing.T) {
w := &stubWire{created: &apigen.BatchCreateResponse{Items: []apigen.Issue{{ID: "bd-11"}}}}
_, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{
{Issue: &issueops.Issue{Title: "one"}},
{Issue: &issueops.Issue{Title: "two"}},
},
})
if err == nil {
t.Fatal("a two-item batch answered with one issue was accepted")
}
}
// batchCreateRoleRefusedIssueMembers are the two members the ROLE refuses in
// its own right, before the wire is consulted: "Issue.Comments and
// Issue.Dependencies must be empty because edges are supplied through the
// item's own Dependencies". They earn ErrValidation rather than a ledger row,
// because a local backend refuses them too — this is not a divergence.
var batchCreateRoleRefusedIssueMembers = map[string]string{
"Comments": "a create batch has no way to supply comments at all",
"Dependencies": "edges are supplied through the item's own Dependencies",
}
// TestBatchCreateRefusesEveryMemberTheWireExcludes is the refuse-not-drop gate
// for this operation, and the pin behind every one of its ledger rows.
//
// It runs three ways, and each catches a different staleness:
//
// carried -> wire the eight members the client claims to carry are
// exactly the ones apigen.BatchCreateItem publishes for
// the issue itself.
// source -> partition every populatable field of types.Issue is carried,
// ignored by the role, refused by the role, or refused by
// the wire. There is no fifth arm, so a member added
// upstream cannot arrive unclassified.
// behavior every wire-refused member really fails, citing its
// ledger row, WITHOUT dialing.
func TestBatchCreateRefusesEveryMemberTheWireExcludes(t *testing.T) {
t.Run("carried members are the wire's own", func(t *testing.T) {
published := bodyMembers(t, reflect.TypeOf(apigen.BatchCreateItem{}))
// `dependencies` is driven by the ITEM's own field, not by the issue.
delete(published, "dependencies")
var claimed []string
for field, wireMember := range batchCreateCarriedIssueMembers {
if _, ok := reflect.TypeOf(issueops.Issue{}).FieldByName(field); !ok {
t.Errorf("the carried table names Issue.%s, which does not exist", field)
}
if !published[wireMember] {
t.Errorf("Issue.%s claims wire member %q, which BatchCreateItem does not publish", field, wireMember)
}
claimed = append(claimed, wireMember)
}
sort.Strings(claimed)
if want := sortedKeys(published); !reflect.DeepEqual(claimed, want) {
t.Errorf("the client carries\n %v\nthe wire's item publishes\n %v", claimed, want)
}
})
t.Run("the item container has exactly two halves", func(t *testing.T) {
// The CONTAINER above types.Issue, which no other gate can see.
//
// issueops.BatchCreateItem is not a wire body — its Issue half FLATTENS
// onto eight members of apigen.BatchCreateItem while its Dependencies
// half is one — so it cannot be a writeShape: a shape row claims one
// member per field, and the wire -> source direction would read the
// eight as undriven. The two halves are therefore classified by
// different mechanisms, and this is what says there are only two.
//
// It is not hypothetical. BatchCreateItem is "the per-item HALF of
// CreateRequest", and CreateRequest carries ParentID,
// InheritLabelsFromParent and WaitsFor; the day one of those is pulled
// down onto the item, every gate below would stay green while the client
// dropped it.
got := populatableFields(reflect.TypeOf(issueops.BatchCreateItem{}))
sort.Strings(got)
want := []string{"Dependencies", "Issue"}
if !reflect.DeepEqual(got, want) {
t.Errorf("BatchCreateItem carries %v, want %v.\n"+
"A new member reaches no wire member and no refusal: carry it in batchCreateItem, or refuse it with a ledger row.", got, want)
}
})
refused := wireRefusedIssueMembers(t)
t.Run("the partition covers every member", func(t *testing.T) {
if len(refused) == 0 {
t.Fatal("no member is wire-refused; the partition tables have swallowed the population this gate exists for")
}
for _, name := range []string{"ID", "Status", "Ephemeral", "Metadata", "Pinned"} {
if !slices.Contains(refused, name) {
t.Errorf("Issue.%s is not in the refused population; a create that dropped it is data loss", name)
}
}
for field := range roleIgnoredCreateIssueMembers {
if _, ok := reflect.TypeOf(issueops.Issue{}).FieldByName(field); !ok {
t.Errorf("the ignored table names Issue.%s, which does not exist", field)
}
if _, dup := batchCreateCarriedIssueMembers[field]; dup {
t.Errorf("Issue.%s is both carried and ignored", field)
}
}
})
t.Run("every refused member fails without dialing", func(t *testing.T) {
for _, name := range refused {
t.Run(name, func(t *testing.T) {
issue := &issueops.Issue{Title: "t"}
setNonZero(t, reflect.ValueOf(issue).Elem().FieldByName(name))
w := &stubWire{}
_, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{{Issue: issue}},
})
assertRefusedBy(t, err, "W-BatchCreateItem.Issue")
if !strings.Contains(err.Error(), name) {
t.Errorf("the refusal does not name the member: %v", err)
}
if len(w.calls) != 0 {
t.Errorf("the refused member reached the wire: %v", w.calls)
}
})
}
})
t.Run("a CreatedBy naming the actor rides the server's stamp", func(t *testing.T) {
// The server stamps every item's created_by from the actor, so that one
// value is carried by the stamp; the sweep above refuses any other.
w := &stubWire{}
if _, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{{Issue: &issueops.Issue{Title: "t", CreatedBy: "planner"}}},
}); err != nil {
t.Fatalf("CreateBatch with CreatedBy == Actor = %v, want it carried by the server's stamp", err)
}
if w.lastBatchCreate.Actor != "planner" {
t.Errorf("sent actor = %q, want the creator the stamp will write", w.lastBatchCreate.Actor)
}
})
t.Run("the role's own two are ErrValidation", func(t *testing.T) {
for name := range batchCreateRoleRefusedIssueMembers {
issue := &issueops.Issue{Title: "t"}
setNonZero(t, reflect.ValueOf(issue).Elem().FieldByName(name))
w := &stubWire{}
_, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{{Issue: issue}},
})
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Issue.%s error = %v, want ErrValidation — a local backend refuses it too", name, err)
}
if len(w.calls) != 0 {
t.Errorf("Issue.%s reached the wire: %v", name, w.calls)
}
}
})
t.Run("the request's own two", func(t *testing.T) {
for _, tc := range []struct {
row string
request issueops.CreateBatchRequest
}{
{"W-CreateBatchRequest.Provenance", issueops.CreateBatchRequest{Provenance: "bd: create from plan.md"}},
{"W-CreateBatchRequest.ForceIDPrefix", issueops.CreateBatchRequest{ForceIDPrefix: true}},
} {
req := tc.request
req.Actor = "planner"
req.Items = []issueops.BatchCreateItem{{Issue: &issueops.Issue{Title: "t"}}}
w := &stubWire{}
_, err := bulkCreator(t, w).CreateBatch(t.Context(), req)
assertRefusedBy(t, err, tc.row)
if len(w.calls) != 0 {
t.Errorf("%s reached the wire: %v", tc.row, w.calls)
}
}
})
t.Run("the edge's three", func(t *testing.T) {
for _, tc := range []struct {
row string
edge issueops.CreateDependency
}{
{"W-CreateDependency.Reverse", issueops.CreateDependency{TargetID: "bd-9", Type: types.DepBlocks, Reverse: true}},
{"W-CreateDependency.Metadata", issueops.CreateDependency{TargetID: "bd-9", Type: types.DepBlocks, Metadata: `{"gate":"x"}`}},
{"W-CreateDependency.ThreadID", issueops.CreateDependency{TargetID: "bd-9", Type: types.DepBlocks, ThreadID: "th-1"}},
} {
w := &stubWire{}
_, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{{
Issue: &issueops.Issue{Title: "t"},
Dependencies: []issueops.CreateDependency{tc.edge},
}},
})
assertRefusedBy(t, err, tc.row)
if len(w.calls) != 0 {
t.Errorf("%s reached the wire: %v", tc.row, w.calls)
}
}
})
}
// TestBatchCreateCannotNameAnItemOfItsOwnBatch is ledger row
// L-batchcreate-inbatch's pin.
//
// The role's headline capability — an edge onto an item created EARLIER in the
// same request — needs that earlier item to have named an id for itself, and
// the wire's item publishes no id member. The gap is in the SCHEMA rather than
// the handler: `target_id`'s own description names this case, so it is worth
// asserting structurally as well as behaviorally.
func TestBatchCreateCannotNameAnItemOfItsOwnBatch(t *testing.T) {
published := bodyMembers(t, reflect.TypeOf(apigen.BatchCreateItem{}))
if published["id"] {
t.Fatal("BatchCreateItem publishes an id member; an in-batch edge is expressible and L-batchcreate-inbatch retires")
}
w := &stubWire{}
_, err := bulkCreator(t, w).CreateBatch(t.Context(), issueops.CreateBatchRequest{
Actor: "planner",
Items: []issueops.BatchCreateItem{
{Issue: &issueops.Issue{ID: "bd-first", Title: "the blocker"}},
{
Issue: &issueops.Issue{Title: "the blocked"},
Dependencies: []issueops.CreateDependency{{TargetID: "bd-first", Type: types.DepBlocks}},
},
},
})
assertRefusedBy(t, err, "W-BatchCreateItem.Issue")
if len(w.calls) != 0 {
t.Errorf("the explicit id reached the wire: %v", w.calls)
}
}
// wireRefusedIssueMembers is the complement the gate above drives: every
// populatable field of types.Issue that is neither carried by the wire, nor
// ignored by the role, nor refused by the role in its own right.
func wireRefusedIssueMembers(t *testing.T) []string {
t.Helper()
var out []string
for _, name := range populatableFields(reflect.TypeOf(issueops.Issue{})) {
if _, ok := batchCreateCarriedIssueMembers[name]; ok {
continue
}
if _, ok := roleIgnoredCreateIssueMembers[name]; ok {
continue
}
if _, ok := batchCreateRoleRefusedIssueMembers[name]; ok {
continue
}
out = append(out, name)
}
return out
}
// assertRefusedBy checks a refusal is the TYPED one and cites the row it
// should. A refusal that merely matched ErrRefused would pass while citing the
// wrong divergence, which is how a ledger row stops describing anything.
func assertRefusedBy(t *testing.T, err error, row string) {
t.Helper()
var refusal *encode.RefusedError
if !errors.As(err, &refusal) {
t.Fatalf("error = %v, want *encode.RefusedError citing %s", err, row)
}
if refusal.Row.ID != row {
t.Errorf("refusal cites ledger row %s, want %s", refusal.Row.ID, row)
}
}
// assertEveryFieldPopulated fails on any zero-valued field of a projected
// result, which is how a dropped member of an unpinned wire body shows up.
//
// skip names fields with no wire-side counterpart AT ALL — not a member this
// projection dropped, but one the wire body never published in the first
// place, so a fully populated wire body can never make the field non-zero no
// matter what the projection does. Each one must be backed by its own
// divergence-ledger row on the REQUEST side (the member the server would need
// to be ASKED to produce this answer), or this exemption is just a quieter way
// to drop it.
func assertEveryFieldPopulated(t *testing.T, name string, value reflect.Value, skip ...string) {
t.Helper()
shape := value.Type()
for i := range shape.NumField() {
field := shape.Field(i)
if !field.IsExported() {
continue
}
if slices.Contains(skip, field.Name) {
continue
}
if value.Field(i).IsZero() {
t.Errorf("%s.%s is zero after projecting a fully populated wire body; the member was dropped",
name, field.Name)
}
}
}
// setNonZero populates one field with a value distinguishable from its zero, so
// the refusal sweep can ask "was this member honored?" of any shape the struct
// grows. It fails rather than skipping on a kind it does not know: a silently
// unset field would make its subtest assert nothing.
func setNonZero(t *testing.T, v reflect.Value) {
t.Helper()
if !v.CanSet() {
t.Fatalf("cannot set a %s", v.Type())
}
switch v.Kind() {
case reflect.String:
v.SetString("sentinel")
case reflect.Bool:
v.SetBool(true)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v.SetInt(1)
case reflect.Pointer:
v.Set(reflect.New(v.Type().Elem()))
case reflect.Slice:
if v.Type() == reflect.TypeOf(json.RawMessage(nil)) {
v.Set(reflect.ValueOf(json.RawMessage(`{"k":"v"}`)))
return
}
v.Set(reflect.MakeSlice(v.Type(), 1, 1))
case reflect.Struct:
if v.Type() == reflect.TypeOf(time.Time{}) {
v.Set(reflect.ValueOf(time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)))
return
}
t.Fatalf("no non-zero value for struct %s", v.Type())
default:
t.Fatalf("no non-zero value for kind %s (%s)", v.Kind(), v.Type())
}
}

View file

@ -205,9 +205,14 @@ func forceIPv4Loopback(t *testing.T, rt http.RoundTripper) {
// caContextHandler answers the handshake like contextServer, and additionally
// records the SNI name and Host header the request actually carried, so a test
// can prove TransportFor never overrides either.
// can prove TransportFor never overrides either. Some callers (e.g. the
// MaxIdleConnsPerHost burst test) drive this handler with several concurrent
// requests, so every field is behind mu: both the writes in handler() and the
// reads in the accessor methods below.
type caContextHandler struct {
body apigen.ContextResponse
body apigen.ContextResponse
mu sync.Mutex
sni string
host string
requestSeen bool
@ -215,16 +220,39 @@ type caContextHandler struct {
func (h *caContextHandler) handler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
h.requestSeen = true
h.host = r.Host
if r.TLS != nil {
h.sni = r.TLS.ServerName
}
h.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(h.body)
}
}
// sawRequest reports whether the handler has observed at least one request.
func (h *caContextHandler) sawRequest() bool {
h.mu.Lock()
defer h.mu.Unlock()
return h.requestSeen
}
// seenHost returns the Host header the most recent request carried.
func (h *caContextHandler) seenHost() string {
h.mu.Lock()
defer h.mu.Unlock()
return h.host
}
// seenSNI returns the TLS ServerName the most recent request carried.
func (h *caContextHandler) seenSNI() string {
h.mu.Lock()
defer h.mu.Unlock()
return h.sni
}
func TestTransportForNoCAConfiguredIsUnchanged(t *testing.T) {
clearCAEnvironment(t)
rt, err := TransportFor(Target{})

View file

@ -0,0 +1,48 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/claimer.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
)
// httpClaimer serves issueops.Claimer from the claimIssue operation (design D8
// row 3). The role is a single guarded compare-and-set and the wire operation is
// the same one, so this is the thinnest mapping on the whole client: a body
// carrying the actor, and a response whose already_claimed flag is the role's
// Changed inverted.
type httpClaimer struct {
store *Store
wire WriteWire
}
var _ issueops.Claimer = (*httpClaimer)(nil)
// Claim dials claimIssue.
//
// The 409 vocabulary reaches the caller as *issueops.ClaimConflictError with the
// holder and status the refusing transaction read, reconstructed from the
// problem body's assignee/issue_status extension members — the wire's mapper
// owns that, and the issue id it needs comes from the request rather than the
// response because the server does not echo what the caller already said.
func (c *httpClaimer) Claim(ctx context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) {
if err := requireActor(req.Actor); err != nil {
return issueops.ClaimResult{}, err
}
if err := requireID("issue id", req.IssueID); err != nil {
return issueops.ClaimResult{}, err
}
res, err := c.wire.ClaimIssue(ctx, req.IssueID, apigen.ClaimRequest{Actor: req.Actor})
if err != nil {
return issueops.ClaimResult{}, err
}
// The role's snapshot is the bare issue ROW — no labels, no edges, no
// comments — which is exactly what the wire's ClaimResponse carries, so
// there is nothing to hydrate and nothing to strip.
issue := res.Issue
return issueops.ClaimResult{Issue: &issue, Changed: !res.AlreadyClaimed}, nil
}

View file

@ -0,0 +1,110 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/commenter.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/httpapi/apigen"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/issueops"
)
// httpCommenter is issueops.Commenter over addComment (POST
// /v0/beads/issues/{id}/comments) — the TWENTY-FOURTH wire-backed accessor, and
// the only write on this surface whose path names a SUB-RESOURCE.
//
// THE MAPPING IS TOTAL and unusually small: three request members, of which one
// is the path, and one result member. There is no ledger row for this operation
// and no member refuses.
//
// THE AUTHOR IS CALLER-ASSERTED, and it is spelled `author` rather than `actor`
// because it is not the same thing. Every other write here names the principal a
// mutation is ATTRIBUTED to; this value is part of what the write STORED — it
// lands in the row and is read back by everyone who sees the thread. It is also
// not the authenticated principal even where a bearer is required, because the
// token a deployment configures is shared and admits a client to the whole
// surface. So THIS CLIENT sends it verbatim: no default, no fallback to a
// configured actor, no normalization.
//
// THE SERVER'S RULE IS A DIFFERENT MATTER, and the difference is ledgered rather
// than described away (L-comment-author). The operation applies the `actor`
// rules to this member — trim, then refuse a control rune — and passes the
// TRIMMED value on, while the role itself only checks the field is non-empty and
// stores what it was given. So a padded author is stored trimmed here and
// verbatim on a local leg, and one carrying a C1 introducer is refused here and
// stored there. Anticipating either half on this side would be worse than the
// divergence: trimming would silently rewrite a caller's request, and refusing
// would be a second copy of a server rule that is free to move. The value goes
// as it was written and the server's answer comes back unchanged, which is what
// keeps the difference visible.
//
// THE TEXT IS SHAPE-ONLY, and that is the column rather than an omission. It is
// a LONGTEXT the caller may fill with a stack trace or a diff, so there is no
// length bound to apply and no control rule — a comment is written in newlines.
// The only cap is the 1 MiB every body on this surface shares, and BOTH PLANES
// agree about that number only because migration 0065 widened
// `wisp_comments.text` from TEXT's 65535 bytes to match the durable column. That
// is worth a sentence here rather than only upstream: this operation resolves
// its anchor across both planes, so before 0065 the bound a caller was subject
// to depended on which plane its id happened to name, and nothing above the
// storage seam could have told it which.
//
// A COMMENT ON A WISP LANDS AND LEAVES NO DURABLE TRACE. The wisp tables are
// dolt-ignored, so an ephemeral thread records no history entry — none, not one
// — while the comment itself is stored and reads back. Nothing here decides
// that: the role resolves the plane inside the transaction it writes in, which
// is what stops a comment landing on a row an earlier read saw.
//
// THERE IS NO READ HERE, and its absence is the role's ruling rather than a
// wave's backlog. A comment page is a paging question with a cursor of its own,
// the wire publishes no such operation, and the thread is read through
// `GET /v0/beads/issues/{id}?include_comments=true`. A client that invented one
// — a filtered getIssue, a fan-out — would be answering a question no role asked
// and no server serves.
type httpCommenter struct {
store *Store
wire WriteWire
}
var _ issueops.Commenter = (*httpCommenter)(nil)
// AddComment appends one comment and answers the row as stored.
func (c *httpCommenter) AddComment(ctx context.Context, req issueops.AddCommentRequest) (issueops.AddCommentResult, error) {
// The role's own request rules, taken from the one place every Commenter
// shares them rather than restated here — readyclaimer.go's lesson, applied
// before it can be learned twice. All three refusals are ErrValidation and
// all three are raised BEFORE the dial: an empty author and an empty id would
// otherwise cost a round trip to be told what the contract already says, and
// a blank body would be refused by the server with the role's own sentence
// anyway, which is the same sentence this raises.
if err := storageops.ValidateAddCommentRequest(req); err != nil {
return issueops.AddCommentResult{}, err
}
comment, err := c.wire.AddComment(ctx, req.IssueID, apigen.AddCommentRequest{
Author: req.Author,
Text: req.Text,
})
if err != nil {
return issueops.AddCommentResult{}, err
}
// PRESENCE IS CHECKED RATHER THAN TRUSTED, for decodeCountGroups' reason and
// with a sharper consequence: the result's whole payload is this pointer, and
// the role promises the stored id and the stored created_at — the value a
// caller may use directly as a comment-page cursor. A nil here would be a
// server that answered 200 with no body at all, and returning it would move
// the panic to whichever caller dereferenced it first.
if comment == nil {
return issueops.AddCommentResult{}, fmt.Errorf(
"bd serve answered an appended comment with no body: the operation returns the stored row, " +
"and an absent one carries neither the id the insert minted nor the created_at a caller pages from")
}
// A COPY, so nothing downstream holds a window onto a decoded response body.
// apigen.Comment IS types.Comment — a Go type alias the document pins — so
// this is an assignment rather than a conversion, and there is no second wire
// struct to fall out of step.
stored := *comment
return issueops.AddCommentResult{Comment: &stored}, nil
}

View file

@ -0,0 +1,552 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/completeness_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"errors"
"os"
"reflect"
"regexp"
"slices"
"sort"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/storage"
)
// legitimatelyUnsupported is the EXPLICIT denominator of every
// storage.DoltStorage method the http client deliberately does not implement —
// design D8's unsupported-allowlist v1 — each with a reason.
//
// TestInterfaceCompleteness asserts the generated shell (unsupported_gen.go)
// contains EXACTLY these methods, no more and no less, so a method cannot
// silently fall into the refusing base; TestUnsupportedContract asserts each one
// really returns the typed sentinel when called. Together they close the loop.
//
// The rule for adding an entry: a method belongs here when no v0 operation can
// answer it. A method that a wire operation CAN answer belongs in accessors.go
// or offrole.go instead, refusing until its bead lands — putting it here would
// bake a refusal into the structural gate and let the flip land silently.
var legitimatelyUnsupported = map[string]string{
// Version control and history. The commit graph belongs to the server's own
// storage; a client of an HTTP API has no working set to branch or diff, and
// v0 publishes no history surface. Note the commit FAMILY is a no-op rather
// than unsupported (D3) and is deliberately absent from this map.
"AsOf": "VC: point-in-time read",
"Branch": "VC: Dolt branch",
"Checkout": "VC: Dolt checkout",
"CommitExists": "VC: commit graph",
"CurrentBranch": "VC: Dolt branch",
"DeleteBranch": "VC: Dolt branch",
"Diff": "VC: Dolt diff",
"GetConflicts": "VC: merge conflicts",
"GetCurrentCommit": "VC: commit graph",
"History": "history: issue revision log",
"ListBranches": "VC: Dolt branch",
"Log": "history: commit log",
"Merge": "VC: Dolt merge",
"ResolveConflicts": "VC: merge conflicts",
"Status": "VC: working-set status",
// Remotes and sync. `bd serve` is the sync boundary: the server pushes and
// pulls its own database, and a client that did so too would be a second
// writer nobody designed.
"AddRemote": "remote",
"AddRemoteWithRef": "remote",
"Fetch": "remote",
"ForcePush": "remote",
"HasRemote": "remote",
"ListRemotes": "remote",
"Pull": "remote",
"PullFrom": "remote",
"PullRemote": "remote",
"Push": "remote",
"PushRemote": "remote",
"PushTo": "remote",
"RemoveRemote": "remote",
"Sync": "sync: server-side concern",
"SyncStatus": "sync: server-side concern",
// Federation, compaction, provenance and the merge slot: whole subsystems
// with no v0 route table entry.
"AddFederationPeer": "federation",
"GetFederationPeer": "federation",
"ListFederationPeers": "federation",
"RemoveFederationPeer": "federation",
"ApplyCompaction": "compaction",
"CheckEligibility": "compaction",
"GetCompactionSnapshot": "compaction",
"GetTier1Candidates": "compaction",
"GetTier2Candidates": "compaction",
"RestoreFromSnapshot": "compaction",
"SnapshotIssue": "compaction",
"GetProvenanceByRef": "provenance log",
"GetProvenanceEvents": "provenance log",
"RecordProvenanceEvent": "provenance log",
"MergeSlotAcquire": "merge slot",
"MergeSlotCheck": "merge slot",
"MergeSlotCreate": "merge slot",
"MergeSlotRelease": "merge slot",
// The THREE role accessors of D8's matrix with no wire operation behind
// them. The other twenty-five are wire-backed and live in accessors.go.
// BatchCloser left this list with the `bd close` decision: the wire has no
// closeBatch, but the single-item no-ClaimNext shape composes onto
// closeIssue, and the CLI's close front door routes every id through this
// role.
//
// Releaser, Commenter and IssueRelations left it with client wave 2b
// (ga-f352s), and all three left for the same reason the rule at the top
// states: the wire publishes releaseIssue (#5507), addComment (#5594) and
// listRelatedIssues (#5540), so "no v0 operation can answer it" stopped
// being true of any of them. What is left here is the residue that is not
// waiting on anything — three acts a client of an HTTP API cannot perform at
// all, because each is about a database this process does not have.
"Bootstrapper": "issue role: workspace bootstrap is a server-side act",
"InitVerifier": "issue role: init verification is a server-side act",
"VersionReconciler": "issue role: clone-local version markers, meaningless for a client",
// Raw issue writes. The served writes reach the wire through their roles
// (Lifecycle, BatchCreator, DependencyEditor, Sweeper, Deleter); these legacy
// front doors have no operation of their own and must not be silently
// re-routed, since their request shapes carry members the wire excludes.
// The two raw comment appends. The wire HAS addComment (#5594) and the
// COMMENTER ROLE now dials it (commenter.go); these stay unwired for
// CreateIssue's rule, and the difference between them is worth keeping: one
// of the two cannot express the operation's answer at all.
"AddComment": "write: raw comment append returning NOTHING; addComment answers with the stored row — the id the insert minted and created_at at the column's precision — and a front door that discarded it would make the role's cursor promise unobservable (role: Commenter)",
"AddIssueComment": "write: raw comment append (role: Commenter). It has the same shape as the role's request and the same answer, which is exactly why re-routing it would be a second spelling of one write — with no actor rule and no plane story of its own",
"AddDependency": "write: raw edge add (role: DependencyEditor)",
"AddDependencyWithOptions": "write: raw edge add (role: DependencyEditor)",
"AddLabel": "write: raw incremental label add (role: Lifecycle, via IssuePatch.Labels.Add). The wire CARRIES it — upstream #5510 published add_labels and client wave ga-jpywb emits it — so this stays on the allowlist for CreateIssue's rule and not for a wire gap: re-routing it would put a second spelling of the edit beside the role's, with no actor, no guard and no ordered-edit algebra",
"ClaimIssue": "write: raw claim (role: Claimer)",
"ClaimReadyIssue": "write: raw ready-claim (role: ReadyClaimer)",
"CloseIssueChecked": "write: raw checked close (role: Lifecycle)",
"CreateIssue": "write: raw create. The wire has createIssue (upstream #5483) and the LIFECYCLE ROLE now dials it (lifecycle.go, D8 row 16); this raw front door stays unwired deliberately, because re-routing it would put a second spelling of the create beside the role's — with a different request shape, since this one takes a bare *types.Issue and no edges",
"CreateIssues": "write: raw batch create; createIssue is single-item and batchCreateIssues is the batch operation, both of which the roles own (role: BatchCreator)",
"CreateIssuesWithFullOptions": "write: raw batch create with options the wire's item body does not publish (role: BatchCreator; see W-BatchCreateItem.Issue)",
"DeleteIssue": "write: raw delete (role: Deleter)",
"DeleteIssues": "write: raw delete (role: Deleter)",
"DeleteIssuesBySourceRepo": "write: no source-repo delete operation",
"ImportIssueComment": "write: no comment-IMPORT operation. It is not AddIssueComment with a flag — it takes the created_at the comment is to be STORED with, and addComment publishes no such member deliberately (a stored time the caller supplied makes the row disagree with the entry that records it, which is createIssue's own argument about the creation stamp)",
"PromoteFromEphemeral": "write: no wisp-promotion operation",
"RemoveDependency": "write: raw edge remove (role: DependencyEditor)",
"RemoveDependencyWithOptions": "write: raw edge remove (role: DependencyEditor)",
"RemoveLabel": "write: raw incremental label remove (role: Lifecycle, via IssuePatch.Labels.Remove); AddLabel's reason exactly, on the other half of the same published pair",
"RenameLabel": "write: no wire operation renames a label across every carrier; v0 publishes no bulk label-rename route, and IssuePatch.Labels is a per-issue add/remove pair with no rename-and-report-merges shape",
"ReopenIssue": "write: raw reopen (role: Lifecycle)",
"UpdateIssue": "write: raw update (role: Lifecycle)",
"UpdateIssueChecked": "write: raw checked update (role: Lifecycle)",
"UpdateIssueID": "write: no id-rewrite operation",
"UpdateIssueType": "write: raw type rewrite (role: Lifecycle, via IssuePatch.IssueType). It said \"no type-rewrite operation\", and the wire has one: updateIssue publishes patch.issue_type (internal/httpapi/update.go) and this client EMITS it (lifecycle.go). So this is AddLabel's reason and not a wire gap — a raw front door beside a served role, kept unwired because re-routing it would put a second spelling of the edit beside the role's, with no actor and none of the patch algebra",
// Leases. ClaimRequest carries only an actor; there is no lease vocabulary
// on the wire at all.
//
// THE TWO UNCLAIMS ARE NO LONGER PART OF THAT SENTENCE, and the split
// matters because it is the reason `bd unclaim` still refuses. The wire
// publishes releaseIssue (#5507) and the RELEASER ROLE dials it
// (releaser.go), including the compare-and-set on the holder that is exactly
// UnclaimIssueIfAssignee's question — so these are ordinary raw front doors
// now, kept unwired for CreateIssue's rule rather than for the absence of an
// operation. What has not moved is the LEASE row the release deletes: the
// role owns that as part of its post-state, and neither of these front doors
// can say anything about it, which is why the heartbeat and the reaper above
// keep the original reason.
"HeartbeatIssue": "lease: no wire vocabulary",
"ReclaimExpiredLeases": "lease: no wire vocabulary",
"UnclaimIssue": "write: raw release, force flag and all (role: Releaser). Re-routing it would put a second spelling of the transition beside the role's, with a bare error where the role answers the post-state row and its reminted version",
"UnclaimIssueIfAssignee": "write: raw conditional release (role: Releaser, via ReleaseRequest.ExpectedAssignee). Its expectation is a STRING where the role's is a POINTER, so it cannot express the one distinction the role's guard is built on — absent means 'do not check' and empty is a refusal, and this signature spells both as \"\"",
// Config and metadata writes.
//
// SETTINGS ARE NO LONGER READ-ONLY over v0 — #5596 published both write
// operations and client wave ga-jpywb dials them — so these two entries keep
// their place for the reason UnclaimIssue and MergeMetadata keep theirs
// rather than for the reason they were written: they are the RAW front doors
// beside a served role. Re-routing them here would put a second spelling of
// the edit beside issueops.WorkspaceConfig's, with a different signature and
// none of the role's guards — SetConfig takes any key, the protected one
// included, and DeleteConfig reports nothing about what it removed.
//
// The two metadata entries are about DIFFERENT PLANES, which is why they no
// longer share a reason. SetMetadata writes the WORKSPACE's own key-value
// table — import hashes, `_project_id` — and no v0 operation touches it at
// all; the compare-and-set upstream added (#5473) is per-ISSUE metadata and
// answers a different question entirely.
//
// MergeMetadata is a raw per-issue write, and the wire CAN express what it
// does now that client wave ga-7i6by carries `patch.metadata`: a merge is
// MetadataPatch.Merge through Lifecycle.Update. It stays on the allowlist
// for the reason every other raw front door does — re-routing it here would
// put a second spelling of the edit beside the role's, with a different
// request shape and no actor rule — not because the wire cannot carry it.
"DeleteConfig": "write: raw settings remove (role: WorkspaceConfig, via UnsetSetting)",
"SetConfig": "write: raw settings write, protected key and all (role: WorkspaceConfig, via SetSetting). Its signature carries no guard and no per-key rule, so re-routing it would be a second door onto the plane that walks past the one issueops.SettingKeyIssuePrefix refusal exists for",
"SetMetadata": "write: the WORKSPACE metadata table has no wire operation at all; compareAndSetMetadata is the per-ISSUE plane (role: MetadataCAS)",
"MergeMetadata": "write: raw per-issue metadata merge (role: Lifecycle, via IssuePatch.Metadata.Merge)",
// Repo mtime and merge slots: clone-local bookkeeping for a local database.
"ClearRepoMtime": "clone-local bookkeeping",
"GetRepoMtime": "clone-local bookkeeping",
"SetRepoMtime": "clone-local bookkeeping",
"SlotClear": "clone-local bookkeeping",
"SlotGet": "clone-local bookkeeping",
"SlotSet": "clone-local bookkeeping",
// Counts. `getStats` answers the aggregate probes, and the two counts
// operations the wave-2 wire published are answered by ROLES — Counter over
// issues.count and GraphCounter over dependencies.count. These are the raw
// front doors beside them, and the split is no longer "no operation" for
// most of the list:
//
// - the four edge counts and the two issue counts stay unwired for the
// rule every other raw front door here follows (CreateIssue's, above):
// re-routing them would put a second spelling of the question beside the
// role's, with a WIDER request shape. CountIssues takes a free-text
// query and a whole types.IssueFilter — SkipWisps, IsTemplate, Pinned,
// ExcludeTypes and twenty more members issueops.CountRequest deliberately
// does not have — so a re-route would silently drop them, which is the
// one thing a count must never do;
// - CountDependentRecords is different and genuinely inexpressible: it is
// a DISTINCT count of edge rows, and the role's count is a SUM over the
// two dependency planes. issueops.AnchorEdgeCount.Count says so and says
// the two differ exactly where one row id lives in both tables;
// - CountEvents and CountIssueComments still have no operation at all.
"CountDependencies": "count: raw per-issue dependency count (role: GraphCounter, direction out)",
"CountDependentRecords": "count: a DISTINCT count of edge rows; the wire's count is a SUM across the two dependency planes and the two differ on a cross-table id collision",
"CountDependents": "count: raw per-issue dependent count (role: GraphCounter, direction in)",
"CountDependentsByStatus": "count: raw per-issue dependent count narrowed by status (role: GraphCounter, direction in plus Status)",
"CountEvents": "count: no counts operation",
"CountIssueComments": "count: no counts operation",
"CountIssues": "count: raw issue count taking a free-text query and a whole types.IssueFilter, whose members the count operation does not publish (role: Counter)",
"CountIssuesByGroup": "count: raw grouped issue count over the same wider filter (role: Counter)",
// THERE ARE TWO EVENT PLANES AND THIS BLOCK IS ABOUT ONE OF THEM, which is
// the disambiguation the entries below used to leave unstated. "events: no
// wire surface" read as false the day GET /v0/beads/events landed and this
// client started reading it (journal.go), and it was never about that plane
// at all — the same shape SetMetadata's entry has to spell out for the two
// metadata planes.
//
// The five methods here are the AUDIT plane: storage.DoltStorage's own
// types.Event log, read by time or by issue id. No v0 operation touches it.
// The DURABLE MUTATION JOURNAL is a different question with a different
// record type, and this client serves it — journalops.Journal is not on
// storage.DoltStorage, so it sits on *Store as a type assertion a caller
// makes rather than as an accessor, and it is out of this allowlist's
// denominator entirely.
"EventsSince": "events (AUDIT plane): no wire surface for the types.Event log; the mutation JOURNAL is journalops.Journal over GET /v0/beads/events and is served",
"GetAllEventsSince": "events (AUDIT plane): no wire surface; see EventsSince",
"GetEvents": "events (AUDIT plane): no wire surface; see EventsSince",
"IterAllEventsSince": "events (AUDIT plane): no wire surface, and streaming has no wire shape either; see EventsSince",
"IterEvents": "events (AUDIT plane): no wire surface, and streaming has no wire shape either; see EventsSince",
// Dependency and blocked-set raw reads. The served dependency surface is
// anchored (listDependencies takes >=1 issue_id) and role-shaped; these are
// the unanchored or off-role shapes. `bd blocked` and `bd ready --explain`
// refuse on these, which is why they are named in D7's refused class.
"DetectCycles": "raw read: role CycleDetector serves this shape",
"FindWispDependentsRecursive": "raw read: no recursive-dependents operation",
"GetAllDependencyRecords": "raw read: listDependencies is anchored (L8, `bd list --deps`)",
"GetBlockedIssues": "raw read: no blocked-set operation (`bd blocked`)",
"GetBlockingInfoForIssues": "raw read: role BlockingAnnotator serves this shape",
"GetDependencies": "raw read: role EdgeReader serves this shape",
"GetDependencyCounts": "raw read: the paired blocks-only batch, expressible as two GraphCounter calls with Types set to the blocking type — the role's own leaf declines to name it as a third method, and re-routing it here would invent the map-of-two-numbers shape no wire operation carries",
"GetDependencyTree": "raw read: role TreeWalker serves this shape",
"GetDependentRecords": "raw read: no dependents operation off getIssue",
"GetDependencyRecordsForIssues": "raw read: no multi-id dependencies operation; the source-keyed, multi-id mirror of GetDependentRecordsForIssues' target-keyed shape — same gap, opposite direction",
"GetDependentRecordsForIssues": "raw read: no multi-id dependents operation",
"GetDependents": "raw read: no dependents operation off getIssue",
"IsBlocked": "raw read: role BlockingAnnotator serves this shape",
"IsBlockedBatch": "raw read: role BlockingAnnotator serves this shape",
"IterAllDependencyRecords": "raw read: streaming has no wire shape",
"IterDependenciesWithMetadata": "raw read: streaming has no wire shape",
"IterDependentsWithMetadata": "raw read: streaming has no wire shape",
// Comment reads beyond getIssue's include_comments.
"GetCommentCounts": "raw read: no comment-count operation",
"GetCommentsForIssues": "raw read: comments ride include_comments, one issue at a time",
"GetIssueCommentsPage": "raw read: no comment paging operation",
"IterIssueComments": "raw read: streaming has no wire shape",
// Issue reads with no wire mapping.
"GetEpicsEligibleForClosure": "raw read: no epic-eligibility operation",
"GetIssueByExternalRef": "raw read: no external-ref lookup operation",
"GetIssuesByIDs": "raw read: multi-id fan-out belongs to the SearchIssues IDs shape",
"GetIssuesByLabel": "raw read: role Reader serves the label filter (ListRequest.Labels). It said \"no label-filtered operation\", and listIssues publishes label, label_any and exclude_label — the encoder sends all three. What is true is that Reader.List does not answer THIS question: this method unions the durable and wisp planes with no status, type or plane suppression at all and its own priority/created order, where the listing answers the durable plane under workapi's default suppressions. Re-routing it would be a second spelling that returns a different set",
"GetLabelsForIssues": "raw read: no multi-id label operation",
"GetNewlyUnblockedByClose": "raw read: no unblocked-by-close operation",
"GetNextChildID": "raw read: id allocation is a server-side act",
"GetStaleIssues": "raw read: no staleness operation",
"GetStatisticsNoBlocked": "raw read: getStats has no blocked-suppression variant",
"SearchIssueIDs": "raw read: no partial-id search operation (D11)",
"SearchIssueSummaries": "raw read: no summary-projection search operation; SearchIssues (role: Searcher) hydrates full issues, and the wire publishes no narrower searchIssues projection for list-shaped rendering to drop onto",
"SearchIssuesWithCounts": "raw read: no counts-bearing search operation",
// Streaming iterators. Every wire read is a page, not a stream.
"IterBlockedIssues": "raw read: streaming has no wire shape",
"IterIssues": "raw read: streaming has no wire shape",
"IterReadyWork": "raw read: streaming has no wire shape",
"IterWisps": "raw read: streaming has no wire shape",
"ListWisps": "raw read: no operation answers the EPHEMERAL PLANE ALONE. listIssues' include_ephemeral admits that plane into a merged listing (which is why L1 retired), and a merged page is not this method's answer",
// Molecule progress reads.
"GetMoleculeLastActivity": "raw read: no molecule operation",
"GetMoleculeProgress": "raw read: no molecule operation",
// Transactions. A multi-statement transaction cannot span HTTP requests;
// each wire write is its own transaction server-side.
"RunInTransaction": "transaction: cannot span requests",
"RunInIssueLifecycleTransaction": "transaction: cannot span requests",
}
var shellMethodRe = regexp.MustCompile(`func \(unsupportedDoltStorage\) ([A-Za-z0-9]+)\(`)
// TestInterfaceCompleteness is the STRUCTURAL half: the generated refusing shell
// must equal the allowlist exactly. A method that drifts into the shell without
// a reason is a silent capability loss; an allowlist entry no longer in the
// shell is a stale justification for something now implemented.
func TestInterfaceCompleteness(t *testing.T) {
data, err := os.ReadFile("unsupported_gen.go")
if err != nil {
t.Fatalf("read unsupported_gen.go: %v", err)
}
shell := map[string]bool{}
for _, m := range shellMethodRe.FindAllStringSubmatch(string(data), -1) {
shell[m[1]] = true
}
if len(shell) == 0 {
t.Fatal("parsed 0 shell methods — regex or file drift")
}
var names []string
for name := range shell {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if _, ok := legitimatelyUnsupported[name]; !ok {
t.Errorf("method %q resolves to the typed-unsupported shell but is NOT in legitimatelyUnsupported: "+
"implement it on *Store (then regenerate the shell: go generate ./internal/httpclient), or add it here with a reason", name)
}
}
names = names[:0]
for name := range legitimatelyUnsupported {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if !shell[name] {
t.Errorf("method %q is in legitimatelyUnsupported but no longer in the shell (implemented?): "+
"remove the allowlist entry", name)
}
}
}
// TestUnsupportedContract is the BEHAVIORAL half: every allowlisted method must
// really return a typed *storage.ErrUnsupported naming itself. DB-free and
// network-free — the generated stubs ignore their receiver, so a zero-value
// store answers them.
func TestUnsupportedContract(t *testing.T) {
conformance.RunUnsupportedContract(t, &Store{}, legitimatelyUnsupported)
}
// wireBackedAccessors is design D8's matrix, spelled as code: the role accessors
// with a v0 operation behind them.
//
// THE THREE QUALIFIERS THIS LINE CARRIED ARE DOWN TO ONE. It read "one partial —
// WorkspaceConfig, whose write verbs have no operation — and two composed,
// ReadyClaimer and BatchCloser", and client wave ga-jpywb falsified two of the
// three clauses. WorkspaceConfig is no longer partial: #5596 published both
// write verbs and the accessor dials them, so the partial column is EMPTY.
// ReadyClaimer is no longer composed in the sense this line meant it: it dials
// claimNext (#5510) and keeps the composition only as a capability-gated
// down-level leg, which is a fallback rather than the way the role is served.
// BatchCloser is the last one, and it has the same shape for the same reason —
// issues.batchClose where advertised, a single closeIssue where not.
//
// So the qualifier that survives is "one accessor whose down-level leg is a
// composition, and one more beside it", which is a statement about SERVER AGE
// rather than about the wire's surface. The distinction is worth keeping
// separate from the count below: every name here has a v0 operation behind it
// today, and that was not true when the list was written.
//
// IssueLifecycle left the partial column with client wave ga-jbuyf: createIssue
// was the operation its Create half had nothing to dial, and upstream #5483
// published it.
//
// The design page records seventeen because its row 17 was PENDING-DECISION when
// it was written. The decision recorded on ga-141ra moved BatchCloser across:
// `bd close` routes every id, single-id included, through CloseBatch, so leaving
// it refused left an http workspace with no close path at all while the server
// advertised issues.close to nobody.
//
// MetadataCAS and BatchApplier are the two the upstream sync added
// (compareAndSetMetadata #5473, applyBatch #5480), and they were the whole
// population of pendingWireBackedAccessors below, which is what that list was
// written for. MetadataCAS left it with client wave ga-7i6by.
// Counter and GraphCounter are the twenty-first and twenty-second, from client
// wave ga-icks1: countIssues (#5508) and dependencies.count (#5536) were both
// published by the wave-2 wire sync and both accessors landed with the same
// wave, so neither spent a PR in pendingWireBackedAccessors below.
//
// Releaser, Commenter and IssueRelations are the twenty-third, twenty-fourth
// and twenty-fifth, from client wave ga-f352s. All three had been published
// upstream ahead of this client — releaseIssue #5507, addComment #5594,
// listRelatedIssues #5540 — and all three landed in ONE wave, so none of them
// spent a PR in pendingWireBackedAccessors either. What they have in common is
// the shape of the port rather than the shape of the operation: each maps member
// for member, and what each one cost was a decision about the ANSWER — an
// anonymous post-state, a stored row that must not be discarded, and a
// single-anchor miss that is a 404 rather than a sentinel.
//
// ReadyLister is NOT in this list. S3 reconciliation (2026-10) removed it: bd-enterprise's issueops.ReadyLister/ReadyListRequest/
// ReadyListing have no OSS counterpart at all — there is no v0 route table
// entry and no role type to accept one — so there is nothing for an accessor
// to return. S13 schedules it; until then this is a twenty-fifth row neither
// here nor in refusingAccessors, because OSS's storage.DoltStorage does not
// define a ReadyLister method for the matrix to count either way.
// BatchGetter is the twenty-sixth, and the first accessor added to this
// matrix since client wave ga-f352s: S3 reconciliation's own rebase onto
// origin/main brought in upstream #7248's issueops.BatchGetter (the
// batchGetIssues operation, POST /v0/beads/issues:batchGet), which
// storage.DoltStorage now requires of every leg. Unlike every accessor
// before it, it was never a bare interface-completeness stub waiting on a
// client wave of its own — it arrived as a brand-new role on the SAME PR
// that wired it, so it spent no PR in pendingWireBackedAccessors below. See
// batchgetter.go.
var wireBackedAccessors = []string{
"IssueReader", "ReadyCounter", "IssueClaimer", "ReadyClaimer", "Querier",
"StatsReporter", "CycleDetector", "TreeWalker", "EdgeReader",
"BlockingAnnotator", "WorkspaceConfig", "Sweeper", "Deleter", "BatchCreator",
"Memories", "IssueLifecycle", "DependencyEditor", "BatchCloser",
"MetadataCAS", "BatchApplier", "Counter", "GraphCounter",
"Releaser", "Commenter", "IssueRelations", "BatchGetter",
}
// refusingAccessors is the complement: the ones with no wire operation at all.
//
// IT NO LONGER HAS A SECOND CLAUSE. The list used to read "or with one this
// client has no wave behind yet", and three of its six names were in that second
// state — Releaser, Commenter and IssueRelations, each with a complete operation
// upstream and no accessor here. Client wave ga-f352s wired all three, so what
// is left is the first clause alone: three acts that are about a database this
// process does not have, which no wire operation will ever answer for a client.
var refusingAccessors = []string{
"VersionReconciler", "Bootstrapper", "InitVerifier",
}
// pendingWireBackedAccessors are the wire-backed rows of D8's matrix whose role
// is not wired YET: the server advertises the operation, but the accessor still
// refuses through (*Store).unsupported until its role bead lands. They are a
// subset of wireBackedAccessors, split out so the behavioral probe can demand
// that every OTHER wire-backed accessor already returns a live role while these
// still refuse — which is what forces a flip to move the name across in the same
// PR as the wiring.
//
// IT WAS EMPTY, and the case it was kept for arrived: "a v0 operation landing
// upstream tomorrow gets an accessor that refuses for exactly one PR, and this
// is the list that says so out loud." Two did — compareAndSetMetadata (#5473)
// and applyBatch (#5480) — and their accessors refused in accessors.go until
// the ports landed. MetadataCAS's did, with client wave ga-7i6by, and moving
// its name out of this list was not optional: the probe below fails the day a
// pending role starts answering, which is the flip rule enforced behaviorally.
//
// Leaving these OFF the matrix entirely was the alternative, and it is the one
// that hides them: an accessor named nowhere is an accessor no gate reads, so
// nothing would have failed on the day one was wired without review.
// IT IS EMPTY AGAIN, and that is the list working rather than the list being
// pointless: both names that entered it have left it through the flip rule the
// probe below enforces — MetadataCAS with client wave ga-7i6by, BatchApplier
// with ga-mijra — and the next operation the wire publishes ahead of its client
// wave lands here for exactly one PR.
var pendingWireBackedAccessors = []string{}
// TestAccessorMatrixMatchesDesign pins the 25/3 split against the allowlist so a
// role accessor cannot change sides without the design row changing with it.
//
// The numbers are the LIST's, not a literal: the design page recorded 20/8 when
// it was written and five accessors have crossed since (Counter and GraphCounter
// with ga-icks1; Releaser, Commenter and IssueRelations with ga-f352s). The
// three that remain refusing are permanently unservable, so this ratio only
// moves again if the tier itself grows.
//
// S3 reconciliation removed ReadyLister from both sides of this split: OSS has
// no issueops.ReadyLister at all (S13), so there is no accessor name for the
// matrix to count on either the wire-backed or the refusing side.
// This is the capability-matrix flip rule applied to the store: a refuse→served
// flip lands in the same PR as the method that serves it.
func TestAccessorMatrixMatchesDesign(t *testing.T) {
if got, want := len(wireBackedAccessors)+len(refusingAccessors), 29; got != want {
t.Fatalf("the matrix covers %d accessors, want %d", got, want)
}
for _, name := range wireBackedAccessors {
if reason, ok := legitimatelyUnsupported[name]; ok {
t.Errorf("%q is wire-backed in D8 but sits on the unsupported allowlist (%q): "+
"it belongs in accessors.go, refusing until its role bead lands", name, reason)
}
}
for _, name := range refusingAccessors {
if _, ok := legitimatelyUnsupported[name]; !ok {
t.Errorf("%q refuses in D8 but is not on the unsupported allowlist", name)
}
}
}
// TestWireBackedAccessorsAreBehaviorallyWired is the behavioral half of the
// matrix. TestAccessorMatrixMatchesDesign pins the split STRUCTURALLY — which
// names sit on the unsupported allowlist — but cannot tell a wired accessor from
// one still handing back (*Store).unsupported, because both compile and both
// satisfy the interface. This one CALLS each accessor: a wired one must not
// return the typed sentinel for a valid call, and a pending one must. So 'wired'
// comes to MEAN 'does not refuse', and the day a pending role is wired this test
// fails until its name moves out of pendingWireBackedAccessors — the flip rule,
// enforced behaviorally.
func TestWireBackedAccessorsAreBehaviorallyWired(t *testing.T) {
pending := map[string]bool{}
for _, name := range pendingWireBackedAccessors {
if !slices.Contains(wireBackedAccessors, name) {
t.Errorf("%q is listed pending but is not a wire-backed accessor", name)
}
pending[name] = true
}
// A store with a transport, so the accessors that narrow it (roleWire) build
// their role rather than reporting the no-transport build fault. Constructing a
// role dials nothing, and neither does (*Store).unsupported, so this stays a
// server-free smoke.
s := New(testTarget(t), &fakeWire{res: &apigen.ContextResponse{}}, nil)
for _, name := range wireBackedAccessors {
method := reflect.ValueOf(s).MethodByName(name)
if !method.IsValid() {
t.Errorf("%q is not a method on *Store", name)
continue
}
out := method.Call(nil)
if len(out) != 2 {
t.Errorf("%s returns %d values, want (role, error)", name, len(out))
continue
}
err, _ := out[1].Interface().(error)
var unsup *storage.ErrUnsupported
refused := err != nil && errors.As(err, &unsup)
switch {
case pending[name]:
if !refused {
t.Errorf("%s is listed pending but does NOT return the typed sentinel (err=%v): "+
"its role is wired — move it out of pendingWireBackedAccessors", name, err)
}
case refused:
t.Errorf("%s is wire-backed but still returns the typed sentinel (%v): "+
"wire its role, or list it in pendingWireBackedAccessors", name, err)
case err != nil:
t.Errorf("%s returned a non-sentinel error on a valid call: %v", name, err)
}
}
}

View file

@ -0,0 +1,143 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/composition_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"errors"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/storage"
)
// The served-surface composition fixture shape.
//
// Behavior parity for this backend is proved by running the per-role conformance
// contracts through client → in-process `bd serve` → reference store, never by
// bare RunAll: RunAll's Factory contract wants a write-ready store and its cases
// seed through raw CreateIssue/SetConfig, both of which this backend refuses.
//
// The binding rule that makes the composition honest is that SEEDING NEVER GOES
// THROUGH THE CLIENT. Each fixture's seed handles bind to the reference store the
// server serves; only the subject role binds to the http client. A fixture that
// seeded through the client would prove the client agrees with itself.
//
// This bead bootstraps the shape and its invariants. Standing up the in-process
// server and wiring the per-role contracts onto it is ga-soq7e's work.
// servedFixture is what a per-role contract binds against.
type servedFixture struct {
// Reference is the store the server serves — the seed handle. Contracts
// write their preconditions here.
Reference storage.DoltStorage
// Subject is the http client store under test. Contracts read and exercise
// the role through this and only this.
Subject *Store
// BaseURL is the address the in-process server bound.
BaseURL string
}
// errSeedsThroughClient reports the one binding that silently invalidates every
// contract run through the fixture.
var errSeedsThroughClient = errors.New(
"served fixture seeds through the client: the seed handle must be the server's reference " +
"store, or the contract proves only that the client agrees with itself")
// checkFixtureBinding validates a binding before it is used. It is separate from
// newServedFixture so the invariant itself is testable without a live harness.
func checkFixtureBinding(reference storage.DoltStorage, subject *Store) error {
if reference == nil {
return errors.New("served fixture needs a reference store to seed through")
}
if subject == nil {
return errors.New("served fixture needs a client store as its subject")
}
if reference == storage.DoltStorage(subject) {
return errSeedsThroughClient
}
return nil
}
// newServedFixture binds a reference store and a client store into the shape
// above.
func newServedFixture(t *testing.T, reference storage.DoltStorage, subject *Store, baseURL string) servedFixture {
t.Helper()
if err := checkFixtureBinding(reference, subject); err != nil {
t.Fatal(err)
}
return servedFixture{Reference: reference, Subject: subject, BaseURL: baseURL}
}
// bindRole is how a role contract asks the fixture for its subject. It returns
// the accessor's error unchanged, so a contract wired before its role bead lands
// FAILS rather than skips — refusals are owned by the unsupported contract, not
// by skipped conformance cases.
func (f servedFixture) bindRole(bind func(*Store) error) error {
return bind(f.Subject)
}
// stubReference is a placeholder seed handle: it exists so the fixture shape can
// be exercised before the in-process server harness lands. ga-soq7e replaces it
// with the real embedded-Dolt store the server serves.
type stubReference struct{ *Store }
// TestFixtureBindingRejectsSeedingThroughTheClient pins the invariant. It is the
// one thing about the composition that cannot be checked by reading the fixture
// wiring later, once there are seventeen of them.
func TestFixtureBindingRejectsSeedingThroughTheClient(t *testing.T) {
subject := New(testTarget(t), &fakeWire{res: &apigen.ContextResponse{}}, nil)
if err := checkFixtureBinding(subject, subject); !errors.Is(err, errSeedsThroughClient) {
t.Errorf("binding the client as its own seed handle = %v, want a refusal", err)
}
if err := checkFixtureBinding(nil, subject); err == nil {
t.Error("binding with no reference store was accepted")
}
if err := checkFixtureBinding(stubReference{subject}, nil); err == nil {
t.Error("binding with no subject was accepted")
}
}
// TestServedFixtureBindsSubjectAndReferenceApart is the positive arm.
func TestServedFixtureBindsSubjectAndReferenceApart(t *testing.T) {
subject := New(testTarget(t), &fakeWire{res: &apigen.ContextResponse{}}, nil)
reference := stubReference{New(testTarget(t), nil, nil)}
f := newServedFixture(t, reference, subject, "http://127.0.0.1:7777")
if f.Subject != subject {
t.Error("fixture bound the wrong subject")
}
if f.Reference == storage.DoltStorage(f.Subject) {
t.Error("fixture bound one store as both seed handle and subject")
}
}
// TestServedFixtureRoleBindingFailsRatherThanSkips: until a role bead lands, its
// accessor refuses, and a contract wired against it must surface that refusal.
func TestServedFixtureRoleBindingFailsRatherThanSkips(t *testing.T) {
subject := New(testTarget(t), &fakeWire{res: &apigen.ContextResponse{}}, nil)
reference := stubReference{New(testTarget(t), nil, nil)}
f := newServedFixture(t, reference, subject, "http://127.0.0.1:7777")
// VersionReconciler is the sample: this case needs an ACCESSOR — that is what
// bindRole takes — and it asserts only the typed sentinel and its Op, both
// of which the generated shell's refusal carries. So unlike the two refusal
// tests in store_test.go it does not need a store-bound refusal, and it must
// use one of the accessors that refuses PERMANENTLY rather than one that
// eventually flips.
//
// It used to be Commenter, chosen when that was one of seven permanent
// refusals. It stopped being one: #5594 published addComment and client wave
// ga-f352s wired the accessor, so this case failed the day the role started
// answering — which is the flip rule finding a second, unplanned home. The
// sample is now a role no wire operation can ever answer for a client:
// version markers are clone-local, so there is nothing for a server to serve.
err := f.bindRole(func(s *Store) error {
_, err := s.VersionReconciler()
return err
})
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) || unsup.Op != "VersionReconciler" {
t.Fatalf("role binding returned %v, want the typed refusal naming VersionReconciler", err)
}
}

View file

@ -0,0 +1,191 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/counter.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"net/http"
"slices"
"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"
)
// httpCounter is issueops.Counter over countIssues (GET /v0/beads/issues:count)
// — the operation behind `bd count`, and the TWENTY-FIRST wire-backed accessor.
//
// ONE OPERATION, TWO METHODS. `group_by` chooses between them, which is the
// role's own shape rather than this layer's: a grouped count is the scalar
// count plus a dimension, asked of the same set. So both methods encode through
// one builder and dial one path, and the only thing that differs is the one
// parameter and the one response member.
//
// WHAT A COUNT MAKES DIFFERENT from every other read here is that its answer
// carries no evidence of the set it came from. A listing that quietly widened
// hands back rows a caller can look at; a count hands back a number, and a
// number computed from a filter this client forgot to send is indistinguishable
// from the right one. That is why the encoder's refusal walk runs on a request
// whose every member the wire publishes: today it refuses nothing, and the day
// upstream adds a twenty-fourth member it refuses rather than answering about a
// wider set.
type httpCounter struct{ store *Store }
// Count returns how many issues match.
func (c httpCounter) Count(ctx context.Context, req issueops.CountRequest) (issueops.CountResult, error) {
if err := c.refuseUnservedScope(ctx, "Counter.Count", req); err != nil {
return issueops.CountResult{}, err
}
params, err := encode.CountParams(req)
if err != nil {
return issueops.CountResult{}, c.store.inexpressible("Counter.Count", err)
}
var body apigen.IssueCount
if err := c.store.dispatch(ctx, wire.Request{
Op: wire.OpCountIssues,
Method: http.MethodGet,
Path: wire.PathIssuesCount,
Query: params,
}, &body); err != nil {
return issueops.CountResult{}, err
}
// Total is int64 end to end — apigen's member, the role's result and the
// document's `format: int64` are one width. A workspace's row count is not
// bounded by 2^53, and a lossy read would answer a number NEAR the
// cardinality, which on a count is worse than an error because nothing
// downstream can tell.
return issueops.CountResult{Total: body.Total}, nil
}
// CountByGroup returns the same count bucketed by one dimension, plus the
// scalar total of the whole matching set.
func (c httpCounter) CountByGroup(ctx context.Context, req issueops.CountByGroupRequest) (issueops.CountByGroupResult, error) {
if err := validateCountGroup(req.GroupBy); err != nil {
return issueops.CountByGroupResult{}, err
}
if err := c.refuseUnservedScope(ctx, "Counter.CountByGroup", req.Filter); err != nil {
return issueops.CountByGroupResult{}, err
}
params, err := encode.CountByGroupParams(req)
if err != nil {
return issueops.CountByGroupResult{}, c.store.inexpressible("Counter.CountByGroup", err)
}
var body apigen.IssueCount
if err := c.store.dispatch(ctx, wire.Request{
Op: wire.OpCountIssues,
Method: http.MethodGet,
Path: wire.PathIssuesCount,
Query: params,
}, &body); err != nil {
return issueops.CountByGroupResult{}, err
}
groups, err := decodeCountGroups(body.Groups)
if err != nil {
return issueops.CountByGroupResult{}, err
}
// Total is NOT the sum of the buckets and is not recomputed from them here:
// label buckets overlap, so an issue carrying three labels is one row in the
// total and one row in three buckets. The server answers both numbers and
// this reads both.
return issueops.CountByGroupResult{Groups: groups, Total: body.Total}, nil
}
// refuseUnservedScope is the pre-dial half of S8's client-skew note
// (internal/httpapi/routes.go, beside CapIssuesCountScope): a request that
// sets ParentID, NoParent, ExcludeTypes or ExcludeStatus asks for something
// only a server advertising issues.count.scope answers, and an older server
// predating the token answers all four with a guaranteed 400
// invalid_argument/unknown_parameter.
//
// It is called BEFORE encode.CountParams/CountByGroupParams, so a server that
// cannot serve the scope never sees the request at all — never a wasted round
// trip for a guaranteed refusal, and never a silent drop of the fields that
// would answer a wider count than the caller asked for. The dispatch path's
// own Preflight (dispatch.go) only gates the OPERATION as a whole via its
// coarse per-op token (issues.count); it has no visibility into which fields
// a particular request populates, which is why this finer-grained behavior
// check has to live here, explicitly, rather than ride the generic path.
//
// A request with none of the four fields set never dials the handshake for
// this check at all — snapshot() is only consulted when there is something to
// gate, so a plain, scope-free count against an old server pays nothing extra.
func (c httpCounter) refuseUnservedScope(ctx context.Context, op string, req issueops.CountRequest) error {
if req.ParentID == "" && !req.NoParent && len(req.ExcludeTypes) == 0 && len(req.ExcludeStatus) == 0 {
return nil
}
snap, err := c.store.snapshot(ctx)
if err != nil {
return err
}
if slices.Contains(snap.Capabilities, wire.CapCountScope) {
return nil
}
return c.store.unsupportedCapability(op, wire.CapCountScope)
}
// countGroups is the closed bucketing vocabulary, spelled with the ROLE's
// constants rather than as strings.
//
// It is the client-side twin of internal/httpapi's list of the same name, and
// it is redeclared rather than imported for list_walk.go's reason:
// internal/workapi — where ValidateCountGroup lives — is denied to this package
// by depguard. TestTheCountGroupVocabularyMatchesTheSharedOne pins it against
// that validator from a test file, where the rule does not apply.
var countGroups = []issueops.CountGroup{
issueops.CountGroupStatus,
issueops.CountGroupPriority,
issueops.CountGroupType,
issueops.CountGroupAssignee,
issueops.CountGroupLabel,
}
// validateCountGroup answers the role's own dimension refusal before the dial.
//
// An empty or unknown GroupBy is ErrValidation on THIS ROLE at every backend —
// counter.go says so, and a caller that misspelled a dimension and got zero
// buckets back has no way to tell that from a workspace with nothing in it. The
// operation refuses it too, naming the parameter, and that row is not redundant:
// what a server-side refusal cannot do is tell a caller their REQUEST is wrong
// rather than their server, which is validateCountReadyPage's argument exactly.
//
// The EMPTY dimension is refused with the rest and is the sharper half. The
// encoder would omit an empty `group_by`, the server would answer the scalar
// shape with no `groups` member, and a caller that asked for buckets would read
// "no buckets" — a wrong answer wearing the shape of a right one.
func validateCountGroup(group issueops.CountGroup) error {
if slices.Contains(countGroups, group) {
return nil
}
if group == "" {
return fmt.Errorf("%w: a grouped count needs a dimension (one of %v): a caller that wanted a number calls Count",
issueops.ErrValidation, countGroups)
}
return fmt.Errorf("%w: %q is not a count dimension (one of %v)", issueops.ErrValidation, group, countGroups)
}
// decodeCountGroups reads the buckets off a grouped answer.
//
// PRESENCE IS THE CONTRACT and it is checked rather than trusted. `groups` is
// published as present exactly when the request carried `group_by`, and this
// request always does — so an absent or null member is a server that did not
// bucket. Reading either as an empty map would answer "nothing matched" to a
// question that may have matched thousands, which is the one failure mode a
// bucketed count has that a scalar one does not: every bucket that should have
// been there is simply gone, and the total beside it still looks right.
//
// The map is COPIED rather than handed back, so the answer cannot alias the
// decoded response body, and it is non-nil for the same reason the role promises
// non-nil: a caller ranges over it without checking.
func decodeCountGroups(groups *map[string]int) (map[string]int, error) {
if groups == nil || *groups == nil {
return nil, fmt.Errorf("bd serve answered a grouped count with no `groups` member: " +
"the operation publishes it whenever the request carries group_by, and an absent one cannot be told from a count with no buckets")
}
out := make(map[string]int, len(*groups))
for key, count := range *groups {
out[key] = count
}
return out, nil
}

View file

@ -0,0 +1,738 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/counts_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"reflect"
"slices"
"strings"
"testing"
"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/workapi"
"github.com/steveyegge/beads/issueops"
)
// The two counting roles' own gates: the properties a served run cannot show,
// because a served run answers with the RIGHT number and the failure mode here
// is a number that looks equally right.
//
// Three of them recur and each has its own test below: a cardinality is 64 bits
// wide and must not be read through a float; a bucket map that arrives absent is
// not a bucket map that arrived empty; and an anchor's Missing flag is a
// SENTINEL rather than a zero, which is the only thing separating a typo from
// an issue that genuinely has no edges.
// countingWire records the request each role dialed and answers with a body the
// test supplied. It answers the READ half of the seam only, which is all either
// role touches.
type countingWire struct {
fakeWire
dialed []wire.Request
body string
err error
}
func newCountingWire(body string) *countingWire {
w := &countingWire{body: body}
w.preflight = func(context.Context, string) error { return nil }
w.do = func(_ context.Context, req wire.Request, out any) error {
w.dialed = append(w.dialed, req)
if w.err != nil {
return w.err
}
return json.Unmarshal([]byte(w.body), out)
}
return w
}
func (w *countingWire) query(t *testing.T) url.Values {
t.Helper()
if len(w.dialed) != 1 {
t.Fatalf("dialed %d times, want exactly 1", len(w.dialed))
}
return w.dialed[0].Query
}
func countRole(t *testing.T, w *countingWire) issueops.Counter {
t.Helper()
counter, err := New(testTarget(t), w, nil).Counter()
if err != nil {
t.Fatalf("Counter(): %v", err)
}
return counter
}
func graphCountRole(t *testing.T, w *countingWire) issueops.GraphCounter {
t.Helper()
counter, err := New(testTarget(t), w, nil).GraphCounter()
if err != nil {
t.Fatalf("GraphCounter(): %v", err)
}
return counter
}
// TestACountIsReadAsSixtyFourBits is the decode convention, on both roles at
// once.
//
// The value is chosen so a float64 round trip is VISIBLE: 2^53+1 is the first
// integer a double cannot represent, and a lossy read answers 2^53 — a number
// near the cardinality, which on a count is worse than an error because nothing
// downstream can tell. The wire says `format: int64` on both members and the
// role's results are int64; this is what holds the client to it.
func TestACountIsReadAsSixtyFourBits(t *testing.T) {
const beyondFloat64 = int64(1)<<53 + 1
t.Run("the issue count's total", func(t *testing.T) {
w := newCountingWire(fmt.Sprintf(`{"total":%d}`, beyondFloat64))
got, err := countRole(t, w).Count(t.Context(), issueops.CountRequest{})
if err != nil {
t.Fatalf("Count: %v", err)
}
if got.Total != beyondFloat64 {
t.Errorf("Total = %d, want %d", got.Total, beyondFloat64)
}
})
t.Run("the grouped total", func(t *testing.T) {
w := newCountingWire(fmt.Sprintf(`{"total":%d,"groups":{"open":3}}`, beyondFloat64))
got, err := countRole(t, w).CountByGroup(t.Context(), issueops.CountByGroupRequest{
GroupBy: issueops.CountGroupStatus,
})
if err != nil {
t.Fatalf("CountByGroup: %v", err)
}
if got.Total != beyondFloat64 {
t.Errorf("Total = %d, want %d", got.Total, beyondFloat64)
}
})
t.Run("an anchor's edge count", func(t *testing.T) {
w := newCountingWire(fmt.Sprintf(`{"anchors":[{"id":"bd-1","count":%d,"missing":false}]}`, beyondFloat64))
got, err := graphCountRole(t, w).CountEdges(t.Context(), issueops.EdgeCountRequest{
IDs: []string{"bd-1"}, Direction: issueops.EdgeDirectionOut,
})
if err != nil {
t.Fatalf("CountEdges: %v", err)
}
if got.Anchors[0].Count != beyondFloat64 {
t.Errorf("Count = %d, want %d", got.Anchors[0].Count, beyondFloat64)
}
})
}
// TestTheCountsQueryCarriesTheWholePredicate drives the role rather than the
// encoder, which is the difference that matters: the encoder is gated against
// the document, and this is what proves the ROLE hands it the caller's request
// instead of a request of its own.
func TestTheCountsQueryCarriesTheWholePredicate(t *testing.T) {
w := newCountingWire(`{"total":7}`)
if _, err := countRole(t, w).Count(t.Context(), issueops.CountRequest{
Status: "closed",
IssueType: "bug",
IDFilter: "bd-1,bd-2",
Labels: []string{"alpha"},
IncludeInfra: true,
}); err != nil {
t.Fatalf("Count: %v", err)
}
q := w.query(t)
for param, want := range map[string]string{
"status": "closed", "type": "bug", "id": "bd-1,bd-2", "label": "alpha", "include_infra": "true",
} {
if got := q.Get(param); got != want {
t.Errorf("%s = %q, want %q", param, got, want)
}
}
// A scalar count must not ask for buckets: `groups` would come back, and a
// caller that asked for a number would be paying for a second query.
if q.Has("group_by") {
t.Errorf("a scalar count sent group_by=%q", q.Get("group_by"))
}
if op := w.dialed[0].Op; op != wire.OpCountIssues {
t.Errorf("dialed %q, want %q", op, wire.OpCountIssues)
}
if path := w.dialed[0].Path; path != wire.PathIssuesCount {
t.Errorf("dialed %q, want %q", path, wire.PathIssuesCount)
}
}
// TestAGroupedCountAsksTheSamePredicateAsTheScalarOne is the identity the role
// is built around, asserted where it can actually break: the two methods must
// send the SAME query but for `group_by`.
//
// A grouped count that narrowed differently would answer buckets over a set the
// caller never asked about, and every bucket in it would look plausible — the
// total beside them would even be self-consistent, because the server computes
// it from the same filter it bucketed.
func TestAGroupedCountAsksTheSamePredicateAsTheScalarOne(t *testing.T) {
predicate := issueops.CountRequest{
Status: "open", Assignee: "agent-7", Labels: []string{"alpha", "beta"},
IDFilter: "bd-1,bd-2", NoLabels: true, IncludeInfra: true,
}
scalar := newCountingWire(`{"total":2}`)
if _, err := countRole(t, scalar).Count(t.Context(), predicate); err != nil {
t.Fatalf("Count: %v", err)
}
grouped := newCountingWire(`{"total":2,"groups":{"open":2}}`)
if _, err := countRole(t, grouped).CountByGroup(t.Context(), issueops.CountByGroupRequest{
Filter: predicate, GroupBy: issueops.CountGroupStatus,
}); err != nil {
t.Fatalf("CountByGroup: %v", err)
}
want, got := scalar.query(t), grouped.query(t)
if got.Get("group_by") != string(issueops.CountGroupStatus) {
t.Errorf("group_by = %q, want %q", got.Get("group_by"), issueops.CountGroupStatus)
}
got.Del("group_by")
if got.Encode() != want.Encode() {
t.Errorf("the grouped count asked %q and the scalar one asked %q; the two must ask the same predicate", got.Encode(), want.Encode())
}
}
// TestAGroupedCountWithoutBucketsRefusesRatherThanReadingZero is the presence
// rule, and it is the one decode decision on this role that had a plausible
// wrong answer.
//
// `groups` is published as present exactly when the request carried `group_by`,
// and this client always sends it — so an absent member is a server that did not
// bucket. Substituting an empty map would answer "nothing matched" to a question
// that may have matched thousands, with a correct-looking total sitting beside
// it. A present-but-null member is the same fact in a different spelling and is
// refused with it.
func TestAGroupedCountWithoutBucketsRefusesRatherThanReadingZero(t *testing.T) {
for _, tc := range []struct{ name, body string }{
{"absent", `{"total":9}`},
{"present but null", `{"total":9,"groups":null}`},
} {
t.Run(tc.name, func(t *testing.T) {
w := newCountingWire(tc.body)
got, err := countRole(t, w).CountByGroup(t.Context(), issueops.CountByGroupRequest{
GroupBy: issueops.CountGroupLabel,
})
if err == nil {
t.Fatalf("CountByGroup answered %+v for a body carrying no buckets", got)
}
if !strings.Contains(err.Error(), "groups") {
t.Errorf("the refusal does not name the member: %v", err)
}
})
}
// The other side of the same rule: an EMPTY object is a real answer — the
// predicate matched nothing — and must not be refused with it.
w := newCountingWire(`{"total":0,"groups":{}}`)
got, err := countRole(t, w).CountByGroup(t.Context(), issueops.CountByGroupRequest{GroupBy: issueops.CountGroupLabel})
if err != nil {
t.Fatalf("an empty bucket set refused: %v", err)
}
if got.Groups == nil || len(got.Groups) != 0 {
t.Errorf("Groups = %v, want an empty non-nil map", got.Groups)
}
}
// TestAnUnknownCountDimensionRefusesWithoutDialing pins the role's own closed
// vocabulary, and pins that the refusal costs no round trip.
//
// The EMPTY dimension is the sharp one. The encoder omits an empty `group_by`,
// so a client that let it through would dial the SCALAR shape, read a body with
// no `groups`, and — but for the presence rule above — hand a caller who asked
// for buckets an answer that had none.
func TestAnUnknownCountDimensionRefusesWithoutDialing(t *testing.T) {
for _, group := range []issueops.CountGroup{"", "owner", "Status", "label "} {
w := newCountingWire(`{"total":0,"groups":{}}`)
_, err := countRole(t, w).CountByGroup(t.Context(), issueops.CountByGroupRequest{GroupBy: group})
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("CountByGroup(%q) error = %v, want ErrValidation", group, err)
}
if len(w.dialed) != 0 {
t.Errorf("CountByGroup(%q) dialed %d times before refusing", group, len(w.dialed))
}
}
}
// TestTheCountGroupVocabularyMatchesTheSharedOne pins this package's redeclared
// dimension list in BOTH directions, and the second direction is the one that
// needed an authority outside this file.
//
// internal/workapi is denied to this package by depguard — a client that built
// filters would be answering questions the wire is supposed to answer — so the
// list is redeclared here, and something has to keep the copy honest. It runs
// from a test file, where the rule does not apply, exactly as
// TestDefaultListLimitMatchesTheSharedDefault does for the list default.
//
// The DOCUMENT is what the second direction reads, because it is the only side
// of this that a client can be wrong about without being wrong on its own
// terms. A dimension this package carries and the shared validator refuses is
// caught by asking the validator; a dimension the WIRE publishes and this
// package does not carry is invisible to any check written out of this file's
// own constants — the client would refuse a value the server would have
// answered, on its own authority, and every test in this package would agree
// with it. So the enum comes off internal/httpapi/spec/openapi.v0.yaml, which
// the encoder's own bijection gate already treats as the surface authority,
// and each published value is put back through the shared validator so the
// document and the role vocabulary are held together too.
func TestTheCountGroupVocabularyMatchesTheSharedOne(t *testing.T) {
for _, group := range countGroups {
if _, err := workapi.ValidateCountGroup(group); err != nil {
t.Errorf("this package accepts %q, which the shared validator refuses: %v", group, err)
}
}
published := publishedCountGroups(t)
if len(published) == 0 {
t.Fatal("the document published no group_by enum; this direction would assert nothing")
}
for _, group := range published {
if err := validateCountGroup(group); err != nil {
t.Errorf("the wire publishes group_by=%q and this package refuses it: %v.\n"+
"A dimension added upstream must be carried, not turned down on this client's own authority.", group, err)
}
if _, err := workapi.ValidateCountGroup(group); err != nil {
t.Errorf("the wire publishes group_by=%q and the shared validator refuses it: %v", group, err)
}
}
for _, group := range countGroups {
if !slices.Contains(published, group) {
t.Errorf("this package carries %q, which the document does not publish: the server would answer 400 for it", group)
}
}
}
// publishedCountGroups reads countIssues' `group_by` enum out of the wire
// contract itself, rather than out of a second copy of the five names.
func publishedCountGroups(t *testing.T) []issueops.CountGroup {
t.Helper()
published := publishedParamEnum(t, wire.OpCountIssues, "group_by")
out := make([]issueops.CountGroup, 0, len(published))
for _, value := range published {
out = append(out, issueops.CountGroup(value))
}
return out
}
// TestTheEdgeCountQueryCarriesEveryMember drives the graph count and reads its
// query back.
//
// The direction is the member worth naming: it is REQUIRED and has no default,
// so a client that omitted it would earn a 400 — and a client that defaulted it
// would count the other end of every edge and never say so.
func TestTheEdgeCountQueryCarriesEveryMember(t *testing.T) {
w := newCountingWire(`{"anchors":[{"id":"bd-1","count":2,"missing":false},{"id":"bd-2","count":0,"missing":true}]}`)
if _, err := graphCountRole(t, w).CountEdges(t.Context(), issueops.EdgeCountRequest{
IDs: []string{"bd-1", "bd-2"},
Direction: issueops.EdgeDirectionIn,
Types: []issueops.DependencyType{"blocks", "related"},
Status: "open",
}); err != nil {
t.Fatalf("CountEdges: %v", err)
}
q := w.query(t)
if got := q["issue_id"]; !reflect.DeepEqual(got, []string{"bd-1", "bd-2"}) {
t.Errorf("issue_id = %v, want the anchors in first-mention order", got)
}
// Repeated, never comma-joined: the operation reads `type` with the
// repeatable decoder and does no splitting, so a comma would travel into a
// type name and match no edge.
if got := q["type"]; !reflect.DeepEqual(got, []string{"blocks", "related"}) {
t.Errorf("type = %v, want two repeated values", got)
}
if got := q.Get("direction"); got != string(issueops.EdgeDirectionIn) {
t.Errorf("direction = %q, want %q", got, issueops.EdgeDirectionIn)
}
if got := q.Get("status"); got != "open" {
t.Errorf("status = %q, want open", got)
}
if op, path := w.dialed[0].Op, w.dialed[0].Path; op != wire.OpCountDependencyEdges || path != wire.PathDependenciesCount {
t.Errorf("dialed %q %q, want %q %q", op, path, wire.OpCountDependencyEdges, wire.PathDependenciesCount)
}
}
// TestEdgeCountRequestSendsEveryMember is what the graph count has instead of an
// encoder table: a reflective sweep over the request shape.
//
// The three anchored graph reads beside it build their queries inline for the
// same reason this one does — an anchored request is not a predicate — but
// inline building has the encoder's own failure mode, which is SILENCE: a member
// added upstream tomorrow is a member nothing sends, and a count that dropped a
// type filter answers a bigger number that looks exactly like a count.
//
// So the classification is enumerated here and checked against reflection, and
// each entry is driven through the role to prove the wire member it names really
// moves when the member does.
func TestEdgeCountRequestSendsEveryMember(t *testing.T) {
// Every populatable member of the request, with the parameter it becomes
// and a value that changes the query.
sends := map[string]struct {
param string
set func(*issueops.EdgeCountRequest)
}{
"IDs": {"issue_id", func(r *issueops.EdgeCountRequest) { r.IDs = []string{"bd-1", "bd-9"} }},
"Direction": {"direction", func(r *issueops.EdgeCountRequest) { r.Direction = issueops.EdgeDirectionOut }},
"Types": {"type", func(r *issueops.EdgeCountRequest) { r.Types = []issueops.DependencyType{"blocks"} }},
"Status": {"status", func(r *issueops.EdgeCountRequest) { r.Status = "in_progress" }},
}
rt := reflect.TypeOf(issueops.EdgeCountRequest{})
for i := range rt.NumField() {
name := rt.Field(i).Name
if !rt.Field(i).IsExported() {
continue
}
if _, ok := sends[name]; !ok {
t.Errorf("EdgeCountRequest.%s is populatable and UNCLASSIFIED.\n"+
"The graph count builds its query inline, so a member nobody sends is a member silently dropped — and a dropped filter on a COUNT is a bigger number with nothing to show for it.", name)
}
}
for name, entry := range sends {
t.Run(name, func(t *testing.T) {
// The baseline is the smallest request this role accepts, and it
// is the INBOUND direction because `status` is legal only there —
// the one member whose validity depends on another. The direction
// case flips it; every other case leaves it alone.
base := issueops.EdgeCountRequest{IDs: []string{"bd-1"}, Direction: issueops.EdgeDirectionIn}
body := `{"anchors":[{"id":"bd-1","count":0,"missing":false},{"id":"bd-9","count":0,"missing":false}]}`
before := newCountingWire(body)
if _, err := graphCountRole(t, before).CountEdges(t.Context(), base); err != nil {
t.Fatalf("the baseline refused: %v", err)
}
populated := base
entry.set(&populated)
after := newCountingWire(body)
if _, err := graphCountRole(t, after).CountEdges(t.Context(), populated); err != nil {
t.Fatalf("a populated %s refused: %v", name, err)
}
if reflect.DeepEqual(before.query(t)[entry.param], after.query(t)[entry.param]) {
t.Errorf("a populated %s left %s at %v; the member never reached the wire",
name, entry.param, after.query(t)[entry.param])
}
})
}
}
// TestEdgeCountRefusesMoreAnchorsThanTheWireCarries is L-edgecount-bound's pin,
// both sides of the boundary, plus the fact that the refusal never dials.
//
// IT IS A UNIT PIN AND THAT IS THE WHOLE POINT, not a gap the served tier will
// close later: the refusal is PRE-DIAL BY DESIGN, so a served run would prove
// only that a request this client never sends would also have been refused by
// the server. What has to be true is that the client refuses first and reaches
// no server at all, and a fake wire is the only thing that can witness the
// second half. No conformance case reaches this bound either — the contract
// sets no cap, because the role sets none.
//
// The bound is measured AFTER the collapse, which is the half a naive check
// would get wrong: a caller naming one id a hundred and one times is asking
// about ONE anchor, and refusing it for a size the answer would never have had
// is a refusal about nothing.
func TestEdgeCountRefusesMoreAnchorsThanTheWireCarries(t *testing.T) {
anchors := func(n int) []string {
out := make([]string, 0, n)
for i := range n {
out = append(out, fmt.Sprintf("bd-%04d", i))
}
return out
}
body := func(ids []string) string {
entries := make([]string, 0, len(ids))
for _, id := range ids {
entries = append(entries, fmt.Sprintf(`{"id":%q,"count":0,"missing":true}`, id))
}
return `{"anchors":[` + strings.Join(entries, ",") + `]}`
}
exactly := anchors(maxEdgeCountAnchors)
w := newCountingWire(body(exactly))
got, err := graphCountRole(t, w).CountEdges(t.Context(), issueops.EdgeCountRequest{
IDs: exactly, Direction: issueops.EdgeDirectionOut,
})
if err != nil {
t.Fatalf("exactly %d anchors refused: %v", maxEdgeCountAnchors, err)
}
if len(got.Anchors) != maxEdgeCountAnchors {
t.Errorf("answered %d anchors, want %d", len(got.Anchors), maxEdgeCountAnchors)
}
over := newCountingWire(`{"anchors":[]}`)
_, err = graphCountRole(t, over).CountEdges(t.Context(), issueops.EdgeCountRequest{
IDs: append(anchors(maxEdgeCountAnchors), "bd-over"), Direction: issueops.EdgeDirectionOut,
})
if !errors.Is(err, encode.ErrRefused) {
t.Fatalf("%d anchors encoded without a refusal: %v", maxEdgeCountAnchors+1, err)
}
var refusal *encode.RefusedError
if !errors.As(err, &refusal) || refusal.Row.ID != "L-edgecount-bound" {
t.Errorf("refusal cites %+v, want ledger row L-edgecount-bound", err)
}
if len(over.dialed) != 0 {
t.Errorf("the refusal dialed %d times; it must never reach the server", len(over.dialed))
}
// The collapse comes first: a hundred and one mentions of ONE anchor is one
// anchor, and it serves.
repeated := make([]string, maxEdgeCountAnchors+1)
for i := range repeated {
repeated[i] = "bd-1"
}
collapsed := newCountingWire(`{"anchors":[{"id":"bd-1","count":3,"missing":false}]}`)
result, err := graphCountRole(t, collapsed).CountEdges(t.Context(), issueops.EdgeCountRequest{
IDs: repeated, Direction: issueops.EdgeDirectionOut,
})
if err != nil {
t.Fatalf("%d mentions of one anchor refused: %v", len(repeated), err)
}
if len(result.Anchors) != 1 || result.Anchors[0].Count != 3 {
t.Errorf("answered %+v, want one anchor counting 3", result.Anchors)
}
if got := collapsed.query(t)["issue_id"]; !reflect.DeepEqual(got, []string{"bd-1"}) {
t.Errorf("sent issue_id=%v, want the collapsed single anchor", got)
}
}
// TestAnUnansweredAnchorRefusesRatherThanCountingZero is the Missing sentinel's
// other half.
//
// The operation carries one entry per distinct requested id. A body missing one
// leaves a client two plausible substitutions — count 0, or missing — and those
// are the exact two answers this role exists to tell apart, so it makes neither.
func TestAnUnansweredAnchorRefusesRatherThanCountingZero(t *testing.T) {
w := newCountingWire(`{"anchors":[{"id":"bd-1","count":4,"missing":false}]}`)
_, err := graphCountRole(t, w).CountEdges(t.Context(), issueops.EdgeCountRequest{
IDs: []string{"bd-1", "bd-2"}, Direction: issueops.EdgeDirectionOut,
})
if err == nil {
t.Fatal("an answer missing an anchor was accepted")
}
if !strings.Contains(err.Error(), "bd-2") {
t.Errorf("the refusal does not name the unanswered anchor: %v", err)
}
}
// TestTheMissingSentinelSurvivesTheProjection is the decode convention that
// matters most on this role: Missing is a FACT, and 0 is the common answer.
//
// A projection that read the count and forgot the flag would answer 0/false for
// a typo — indistinguishable from an issue with no edges in that direction, and
// therefore a mistake a caller could not find.
func TestTheMissingSentinelSurvivesTheProjection(t *testing.T) {
w := newCountingWire(`{"anchors":[
{"id":"bd-present","count":0,"missing":false},
{"id":"bd-typo","count":0,"missing":true}
]}`)
got, err := graphCountRole(t, w).CountEdges(t.Context(), issueops.EdgeCountRequest{
IDs: []string{"bd-present", "bd-typo"}, Direction: issueops.EdgeDirectionOut,
})
if err != nil {
t.Fatalf("CountEdges: %v", err)
}
want := []issueops.AnchorEdgeCount{
{ID: "bd-present", Count: 0, Missing: false},
{ID: "bd-typo", Count: 0, Missing: true},
}
if !reflect.DeepEqual(got.Anchors, want) {
t.Errorf("anchors = %+v, want %+v", got.Anchors, want)
}
}
// TestAnEmptyEdgeCountAnswersWithoutDialing pins the two shapes that must not
// reach a server, in the role's own order.
//
// The direction is checked FIRST, so EdgeCountRequest{} is a refusal ABOUT THE
// DIRECTION rather than an empty answer — a caller who forgot it would otherwise
// get a plausible response forever. Only then is an empty anchor list a success
// with no anchors, which the operation itself could not answer: it requires at
// least one `issue_id`.
func TestAnEmptyEdgeCountAnswersWithoutDialing(t *testing.T) {
w := newCountingWire(`{"anchors":[]}`)
if _, err := graphCountRole(t, w).CountEdges(t.Context(), issueops.EdgeCountRequest{}); !errors.Is(err, issueops.ErrValidation) {
t.Errorf("the empty request error = %v, want ErrValidation about the direction", err)
}
got, err := graphCountRole(t, w).CountEdges(t.Context(), issueops.EdgeCountRequest{Direction: issueops.EdgeDirectionOut})
if err != nil {
t.Fatalf("an empty anchor list refused: %v", err)
}
if got.Anchors == nil || len(got.Anchors) != 0 {
t.Errorf("Anchors = %+v, want an empty non-nil slice", got.Anchors)
}
if len(w.dialed) != 0 {
t.Errorf("dialed %d times for requests that need no server", len(w.dialed))
}
}
// TestNeitherCountingRoleWritesThroughTheCallerRequest pins the snapshot promise
// both roles carry, on the members that would be written through: the count's
// two label slices and the graph count's anchors and types.
//
// Reusing one request for several counts is the ordinary way to hold either
// role, so a normalization that sorted or de-duplicated in place would change
// the caller's next question rather than this one's answer.
func TestNeitherCountingRoleWritesThroughTheCallerRequest(t *testing.T) {
count := issueops.CountRequest{Labels: []string{" beta ", "alpha", "alpha"}, LabelsAny: []string{"gamma", ""}}
before := fmt.Sprint(count.Labels, count.LabelsAny)
w := newCountingWire(`{"total":1}`)
if _, err := countRole(t, w).Count(t.Context(), count); err != nil {
t.Fatalf("Count: %v", err)
}
if after := fmt.Sprint(count.Labels, count.LabelsAny); after != before {
t.Errorf("the caller's label slices became %s, want %s", after, before)
}
edges := issueops.EdgeCountRequest{
IDs: []string{"bd-2", "bd-1", "bd-2"},
Types: []issueops.DependencyType{"related", "blocks"},
Direction: issueops.EdgeDirectionOut,
}
edgesBefore := fmt.Sprint(edges.IDs, edges.Types)
g := newCountingWire(`{"anchors":[{"id":"bd-2","count":1,"missing":false},{"id":"bd-1","count":0,"missing":false}]}`)
if _, err := graphCountRole(t, g).CountEdges(t.Context(), edges); err != nil {
t.Fatalf("CountEdges: %v", err)
}
if after := fmt.Sprint(edges.IDs, edges.Types); after != edgesBefore {
t.Errorf("the caller's anchors became %s, want %s", after, edgesBefore)
}
}
// countRoleWithSnapshot is countRole's twin for the S8 (#7199) count-scope
// tests below, which need to pin exactly what the handshake advertises
// (CapCountScope present or absent) rather than accept countRole's bare nil —
// passing a snapshot straight through New is the same idiom
// wave2c_claimnext_test.go uses to pin a capability set without a live
// handshake dial.
func countRoleWithSnapshot(t *testing.T, w *countingWire, snap *apigen.ContextResponse) issueops.Counter {
t.Helper()
counter, err := New(testTarget(t), w, snap).Counter()
if err != nil {
t.Fatalf("Counter(): %v", err)
}
return counter
}
// TestCountScopeFieldsEncodeOntoTheQuery is S8's client half, the encoding
// side: each of the four count-scope fields (ParentID, NoParent, ExcludeTypes,
// ExcludeStatus — internal/httpapi/routes.go's issues.count.scope) reaches the
// wire once the handshake advertises the token.
//
// ParentID and NoParent are exercised in separate cases rather than together:
// the ROLE (issueops/counter.go) refuses that combination as ErrValidation on
// every backend, this one included, so a case that set both would be testing a
// refusal rather than an encoding.
func TestCountScopeFieldsEncodeOntoTheQuery(t *testing.T) {
served := &apigen.ContextResponse{Capabilities: []string{wire.CapCountScope}}
for _, tc := range []struct {
name string
req issueops.CountRequest
want url.Values
}{
{"ParentID", issueops.CountRequest{ParentID: "bd-1"}, url.Values{"parent": {"bd-1"}}},
{"NoParent", issueops.CountRequest{NoParent: true}, url.Values{"no_parent": {"true"}}},
{"ExcludeTypes", issueops.CountRequest{ExcludeTypes: []string{"wisp", "gate"}}, url.Values{"exclude_type": {"wisp", "gate"}}},
{"ExcludeStatus", issueops.CountRequest{ExcludeStatus: []string{"closed", "archived"}}, url.Values{"exclude_status": {"closed", "archived"}}},
} {
t.Run(tc.name, func(t *testing.T) {
w := newCountingWire(`{"total":3}`)
if _, err := countRoleWithSnapshot(t, w, served).Count(t.Context(), tc.req); err != nil {
t.Fatalf("Count: %v", err)
}
q := w.query(t)
for param, want := range tc.want {
if got := q[param]; !slices.Equal(got, want) {
t.Errorf("query[%q] = %v, want %v (full query: %v)", param, got, want, q)
}
}
})
}
}
// TestCountScopeRefusesLocallyWhenTheServerLacksTheCapability is S8's other
// half, the skew side: internal/httpapi/routes.go's CLIENT-SKEW NOTE beside
// CapIssuesCountScope requires that a request setting any of the four scope
// fields refuse BEFORE dialing when the handshake does not advertise
// issues.count.scope — never a round trip for a guaranteed 400, and never a
// silent drop that answers a wider count than asked for.
func TestCountScopeRefusesLocallyWhenTheServerLacksTheCapability(t *testing.T) {
masked := &apigen.ContextResponse{Capabilities: []string{"issues.count"}}
for _, tc := range []struct {
name string
req issueops.CountRequest
}{
{"ParentID", issueops.CountRequest{ParentID: "bd-1"}},
{"NoParent", issueops.CountRequest{NoParent: true}},
{"ExcludeTypes", issueops.CountRequest{ExcludeTypes: []string{"wisp"}}},
{"ExcludeStatus", issueops.CountRequest{ExcludeStatus: []string{"closed"}}},
} {
t.Run(tc.name, func(t *testing.T) {
w := newCountingWire(`{"total":0}`)
_, err := countRoleWithSnapshot(t, w, masked).Count(t.Context(), tc.req)
if err == nil {
t.Fatal("Count 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 != wire.CapCountScope {
t.Errorf("Capability = %q, want %q", unsup.Capability, wire.CapCountScope)
}
if unsup.Op != "Counter.Count" {
t.Errorf("Op = %q, want %q", unsup.Op, "Counter.Count")
}
if len(w.dialed) != 0 {
t.Errorf("dialed %d times, want 0: a pre-dial refusal must never reach the wire", len(w.dialed))
}
})
t.Run(tc.name+"/CountByGroup", func(t *testing.T) {
w := newCountingWire(`{"total":0,"groups":{}}`)
counter, err := New(testTarget(t), w, masked).Counter()
if err != nil {
t.Fatalf("Counter(): %v", err)
}
_, err = counter.CountByGroup(t.Context(), issueops.CountByGroupRequest{
Filter: tc.req, GroupBy: issueops.CountGroupStatus,
})
if err == nil {
t.Fatal("CountByGroup 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 != wire.CapCountScope {
t.Errorf("Capability = %q, want %q", unsup.Capability, wire.CapCountScope)
}
if len(w.dialed) != 0 {
t.Errorf("dialed %d times, want 0", len(w.dialed))
}
})
}
// The converse: a scope-free count against the SAME masked server dials
// normally. The gate guards the four fields, not the operation — a plain
// `bd count` must keep working against a server that predates S8.
t.Run("no scope field set dials normally", func(t *testing.T) {
w := newCountingWire(`{"total":5}`)
if _, err := countRoleWithSnapshot(t, w, masked).Count(t.Context(), issueops.CountRequest{Status: "open"}); err != nil {
t.Fatalf("Count: %v", err)
}
if len(w.dialed) != 1 {
t.Errorf("dialed %d times, want exactly 1", len(w.dialed))
}
})
}

View file

@ -27,11 +27,13 @@ import (
type CredentialProvider = wire.CredentialProvider
const (
// TokenEnv carries the bearer token itself, the highest rung.
// TokenEnv carries the bearer token itself, the highest rung, scoped to one
// server: "host[:port]=token" (see scopedEnvValue).
// #nosec G101 -- the NAME of an environment variable, not a credential.
TokenEnv = "BEADS_HTTP_TOKEN"
// TokenCommandEnv names a helper that prints a token, either bare or in the
// kubectl ExecCredential envelope {"token","expirationTimestamp"}.
// kubectl ExecCredential envelope {"token","expirationTimestamp"}, scoped the
// same way: "host[:port]=command".
// #nosec G101 -- the NAME of an environment variable, not a credential.
TokenCommandEnv = "BEADS_HTTP_TOKEN_COMMAND"
)
@ -42,6 +44,12 @@ const (
// the tip OSS server's loopback-trust posture and a legitimate answer, not a
// failure.
//
// Every rung is scoped to the server it authorizes against: the credentials
// file by its section key, the two env rungs by the host pattern their value
// carries. The server comes from the workspace's http_target.json, which a
// cloned repo can supply, so an unscoped rung would hand an operator's token to
// whatever server that file names.
//
// The ladder fails closed. A rung the operator configured that then errors
// aborts the request; it never falls through to a lower rung, because the
// difference between a broken token command and an unauthenticated request is
@ -50,8 +58,10 @@ const (
// The resolved token is held in memory for the life of the provider and is
// never logged: the only place it appears is the Authorization header.
type BearerProvider struct {
// endpoint is the server this provider authorizes against, rendered for the
// posture warning only. host/port key the credentials-file rung.
// base is the server this provider authorizes against; the env rungs match
// their host pattern against it. endpoint renders it for the posture warning
// only. host/port key the credentials-file rung.
base *url.URL
endpoint string
host string
port int
@ -75,7 +85,8 @@ func NewBearerProvider(base *url.URL) *BearerProvider {
if base == nil {
return p
}
p.endpoint = base.Redacted()
p.base = base
p.endpoint = withoutUserinfo(base).String()
p.host = base.Hostname()
p.port = endpointPort(base)
p.insecure = base.Scheme == "http" && !configfile.IsLocalHostString(p.host)
@ -182,8 +193,8 @@ func (p *BearerProvider) Source() string {
// both when the ladder is unconfigured).
func (p *BearerProvider) resolve(ctx context.Context) (token, source string, err error) {
cred, ok, err := creds.ResolveLadder(ctx,
envTokenSource{Var: TokenEnv},
commandTokenSource{Var: TokenCommandEnv},
envTokenSource{Var: TokenEnv, Base: p.base},
commandTokenSource{Var: TokenCommandEnv, Base: p.base},
credentialsFileTokenSource{Host: p.host, Port: p.port},
)
if err != nil {
@ -211,37 +222,100 @@ func (p *BearerProvider) warnInsecure() {
// envTokenSource is the token-in-the-environment rung. The value is read at
// resolution time rather than at construction, so Refresh sees a token the
// process was handed after this provider was built.
type envTokenSource struct{ Var string }
type envTokenSource struct {
Var string
Base *url.URL
}
func (s envTokenSource) Name() string { return s.Var }
func (s envTokenSource) Resolve(context.Context) (creds.Credential, bool, error) {
value := strings.TrimSpace(os.Getenv(s.Var))
if value == "" {
return creds.Credential{}, false, nil
value, ok, err := scopedEnvValue(s.Var, "token", s.Base)
if err != nil || !ok {
return creds.Credential{}, false, err
}
return creds.Credential{Value: value, Kind: creds.KindIdentity, Source: s.Var}, true, nil
}
// commandTokenSource runs an operator-named helper and reads a token from its
// stdout — the credential-process idiom bd already uses for database passwords.
// A helper scoped to another server is not run at all.
//
// The helper owns its own error text: internal/creds folds the helper's stderr
// into the failure, exactly as it does on the postgres ladder, so a helper must
// keep secrets off stderr the way `bd __gw-credential` does with its canned
// messages.
type commandTokenSource struct{ Var string }
type commandTokenSource struct {
Var string
Base *url.URL
}
func (s commandTokenSource) Name() string { return s.Var }
func (s commandTokenSource) Resolve(ctx context.Context) (creds.Credential, bool, error) {
command := strings.TrimSpace(os.Getenv(s.Var))
if command == "" {
return creds.Credential{}, false, nil
command, ok, err := scopedEnvValue(s.Var, "command", s.Base)
if err != nil || !ok {
return creds.Credential{}, false, err
}
return creds.CommandSource{Command: command, Kind: creds.KindIdentity, Label: s.Var}.Resolve(ctx)
}
// scopedEnvValue reads one of the env rungs, which take CAFileEnv's host-scoped
// syntax, "host[:port]=value", and match it with the same caHostMatches: a
// pattern with no port names the host on any port, one with a port names that
// host:port alone. It returns the value only when the pattern names base. An
// unset variable is not configured; so is a well-formed one scoped to another
// server, which falls through to the next rung exactly as CAFileEnv falls
// through to the sidecar. A malformed value — the bare form included — is an
// error, so the ladder fails closed on it rather than falling through. A bare
// token that contains "=" can still parse as a pattern naming no real server;
// that fails safe, since the token then goes nowhere.
func scopedEnvValue(name, what string, base *url.URL) (string, bool, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return "", false, nil
}
pattern, value, err := parseScopedEnv(raw, what)
if err != nil {
return "", false, err
}
matches, err := caHostMatches(pattern, Target{BaseURL: base})
if err != nil {
// The pattern parsed above, so what failed is the target's own host,
// which carries no secret.
return "", false, err
}
if !matches {
return "", false, nil
}
return value, true, nil
}
// parseScopedEnv splits a host-scoped env value on its FIRST "=": a host
// pattern never contains one, and a token (base64 padding) or a command (a
// --flag=value) may. Nothing from raw is echoed into an error. The value is a
// credential, and a bare token that happens to contain "=" would put part of
// itself in the pattern half.
func parseScopedEnv(raw, what string) (hostPattern, value string, err error) {
want := fmt.Sprintf("want host[:port]=%s, e.g. serve.example.com=<%s> or serve.example.com:8443=<%s> (the value is not echoed)", what, what, what)
eq := strings.Index(raw, "=")
if eq < 0 {
return "", "", fmt.Errorf("an unscoped %s would be used for whatever server the workspace's %s names; %s", what, TargetFileName, want)
}
hostPattern = strings.TrimSpace(raw[:eq])
value = strings.TrimSpace(raw[eq+1:])
if hostPattern == "" || value == "" {
return "", "", fmt.Errorf("nothing on one side of the first \"=\"; %s", want)
}
if strings.HasSuffix(hostPattern, ":") {
return "", "", fmt.Errorf("the host pattern ends with \":\" and no port; %s", want)
}
if _, _, splitErr := splitCAHostPort(hostPattern, ""); splitErr != nil {
return "", "", fmt.Errorf("the text before the first \"=\" is not a host[:port]; %s", want)
}
return hostPattern, value, nil
}
// credentialsFileTokenSource reads the bearer from the shared credentials file's
// [host:port] section, under the same `password` key every other endpoint uses
// there. It is the lowest configured rung and, like the postgres ladder's copy,

View file

@ -32,7 +32,7 @@ func resolveProvider(t *testing.T, p *BearerProvider) {
}
func TestSourceNamesTheEnvRung(t *testing.T) {
t.Setenv(TokenEnv, "tok-env")
t.Setenv(TokenEnv, "127.0.0.1=tok-env")
p := NewBearerProvider(mustURL(t, "http://127.0.0.1:8080"))
resolveProvider(t, p)
if got := p.Source(); got != TokenEnv {
@ -43,7 +43,7 @@ func TestSourceNamesTheEnvRung(t *testing.T) {
func TestSourceNamesTheTokenCommandRung(t *testing.T) {
// The env rung must be empty so the ladder falls to the command rung.
t.Setenv(TokenEnv, "")
t.Setenv(TokenCommandEnv, "printf tok-cmd")
t.Setenv(TokenCommandEnv, "127.0.0.1=printf tok-cmd")
p := NewBearerProvider(mustURL(t, "http://127.0.0.1:8080"))
resolveProvider(t, p)
if got := p.Source(); got != TokenCommandEnv {

View file

@ -13,6 +13,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
@ -82,7 +83,7 @@ func TestCredentialLadderPrecedence(t *testing.T) {
t.Run("env is the top rung", func(t *testing.T) {
clearCredentialEnvironment(t)
writeCredentialsFile(t, "127.0.0.1", 8080, "from-file", 0o600)
t.Setenv(TokenEnv, "from-env")
t.Setenv(TokenEnv, "127.0.0.1=from-env")
if got := authorizeWith(t, NewBearerProvider(base)); got != "Bearer from-env" {
t.Errorf("Authorization = %q, want the env rung", got)
}
@ -121,7 +122,7 @@ func TestCredentialLadderPrecedence(t *testing.T) {
func TestCredentialLadderFailsClosed(t *testing.T) {
clearCredentialEnvironment(t)
writeCredentialsFile(t, "127.0.0.1", 8080, "lower-rung", 0o600)
t.Setenv(TokenCommandEnv, "exit 7")
t.Setenv(TokenCommandEnv, "127.0.0.1=exit 7")
p := NewBearerProvider(mustParseURL(t, "http://127.0.0.1:8080"))
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/v0/beads/context", nil)
@ -140,6 +141,108 @@ func TestCredentialLadderFailsClosed(t *testing.T) {
}
}
// TestTokenEnvRungsAreHostScoped keeps an operator's token on the server it was
// issued for. The server a provider authorizes against comes from the
// workspace's http_target.json, which a cloned repo can supply, so a token
// scoped to one server must never reach another, and a token command scoped
// elsewhere must not even run.
func TestTokenEnvRungsAreHostScoped(t *testing.T) {
base := mustParseURL(t, "http://127.0.0.1:8080")
t.Run("a token scoped to another host is not sent", func(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "serve.example.com=not-for-you")
if got := authorizeWith(t, NewBearerProvider(base)); got != "" {
t.Errorf("Authorization = %q, want no header: the token names another server", got)
}
})
t.Run("a token scoped to another host falls through to the lower rungs", func(t *testing.T) {
clearCredentialEnvironment(t)
writeCredentialsFile(t, "127.0.0.1", 8080, "from-file", 0o600)
t.Setenv(TokenEnv, "serve.example.com=not-for-you")
if got := authorizeWith(t, NewBearerProvider(base)); got != "Bearer from-file" {
t.Errorf("Authorization = %q, want the credentials-file rung", got)
}
})
t.Run("a token command scoped to another host is not run", func(t *testing.T) {
clearCredentialEnvironment(t)
// Run, `exit 7` would fail the ladder closed and Authorize with it.
t.Setenv(TokenCommandEnv, "serve.example.com=exit 7")
if got := authorizeWith(t, NewBearerProvider(base)); got != "" {
t.Errorf("Authorization = %q, want no header", got)
}
})
t.Run("a pattern with a port names that port alone", func(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "127.0.0.1:9999=wrong-port")
if got := authorizeWith(t, NewBearerProvider(base)); got != "" {
t.Errorf("Authorization = %q, want no header: the pattern names another port", got)
}
t.Setenv(TokenEnv, "127.0.0.1:8080=right-port")
if got := authorizeWith(t, NewBearerProvider(base)); got != "Bearer right-port" {
t.Errorf("Authorization = %q, want the port-scoped token", got)
}
})
t.Run("host case and an https default port normalize", func(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "Beads.Example.com:443=tls-token")
if got := authorizeWith(t, NewBearerProvider(mustParseURL(t, "https://beads.example.com/"))); got != "Bearer tls-token" {
t.Errorf("Authorization = %q, want the token", got)
}
})
t.Run("the split is on the first =", func(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "127.0.0.1=padded==")
if got := authorizeWith(t, NewBearerProvider(base)); got != "Bearer padded==" {
t.Errorf("Authorization = %q, want the token with its padding", got)
}
})
}
// TestMalformedTokenEnvIsRefusedWithoutEchoingIt: an unscoped value, the form
// these rungs took before they were scoped, is refused rather than applied to
// whatever server the workspace names, and so is any other value that does not
// parse. The refusal names the variable but no part of its value, since the
// value is the credential.
func TestMalformedTokenEnvIsRefusedWithoutEchoingIt(t *testing.T) {
for _, tc := range []struct{ name, env, value string }{
{"a bare token", TokenEnv, "bare-s3cr3t"},
{"a bare token whose padding splits it", TokenEnv, "s3cr3t+b64/x=="},
{"a bare token command", TokenCommandEnv, "printf s3cr3t"},
{"nothing after the =", TokenEnv, "127.0.0.1="},
{"a port-less colon", TokenEnv, "127.0.0.1:=s3cr3t"},
} {
t.Run(tc.name, func(t *testing.T) {
clearCredentialEnvironment(t)
writeCredentialsFile(t, "127.0.0.1", 8080, "lower-rung", 0o600)
t.Setenv(tc.env, tc.value)
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/v0/beads/context", nil)
if err != nil {
t.Fatalf("new request: %v", err)
}
err = NewBearerProvider(mustParseURL(t, "http://127.0.0.1:8080")).Authorize(context.Background(), req)
if err == nil {
t.Fatal("Authorize = nil; a malformed token variable must abort the request")
}
if !strings.Contains(err.Error(), tc.env) {
t.Errorf("error %q does not name the variable", err)
}
if strings.Contains(err.Error(), "s3cr3t") {
t.Fatalf("the refusal echoed the value: %v", err)
}
if req.Header.Get("Authorization") != "" {
t.Error("a refused ladder still set an Authorization header")
}
})
}
}
// TestRefreshRereadsTheCredentialSource is the client half of the server's
// rotation contract. The server re-reads its token file on a ~1s gate, so a
// rolled client 401s once and succeeds on the retry — but only if Refresh
@ -199,7 +302,7 @@ func TestRefreshRereadsTheCredentialSource(t *testing.T) {
// it names the server, never the token.
func TestPlainHTTPBearerWarnsOnceAndLeaksNothing(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "s3cr3t-token")
t.Setenv(TokenEnv, "beads.example.com=s3cr3t-token")
var sink strings.Builder
p := NewBearerProvider(mustParseURL(t, "http://beads.example.com:8080"))
@ -223,9 +326,30 @@ func TestPlainHTTPBearerWarnsOnceAndLeaksNothing(t *testing.T) {
}
}
// TestPlainHTTPWarningDropsUserinfo: the warning names the server, and a url
// handed in with userinfo must not bring it along — the username included,
// which url.URL.Redacted would keep and which a token sometimes rides as.
func TestPlainHTTPWarningDropsUserinfo(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "beads.example.com=bearer-token")
var sink strings.Builder
p := NewBearerProvider(mustParseURL(t, "http://tok3n:pa55@beads.example.com:8080"))
p.warnTo = &sink
authorizeWith(t, p)
warning := sink.String()
if !strings.Contains(warning, "http://beads.example.com:8080") {
t.Errorf("warning does not name the server:\n%s", warning)
}
if strings.Contains(warning, "tok3n") || strings.Contains(warning, "pa55") {
t.Fatalf("the warning printed the url's userinfo:\n%s", warning)
}
}
func TestLoopbackBearerDoesNotWarn(t *testing.T) {
clearCredentialEnvironment(t)
t.Setenv(TokenEnv, "local-token")
t.Setenv(TokenEnv, "127.0.0.1=local-token")
var sink strings.Builder
p := NewBearerProvider(mustParseURL(t, "http://127.0.0.1:8080"))
@ -292,13 +416,19 @@ type contextServer struct {
// test lands the rewrite in the one place it happens in production: between
// the refused attempt and the client's re-read.
onUnauthorized func()
seen []string
// seenMu guards seen: a burst test drives this handler from several
// server goroutines at once. Readers look at seen only after their
// requests have returned.
seenMu sync.Mutex
seen []string
}
func (s *contextServer) start(t *testing.T) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.seenMu.Lock()
s.seen = append(s.seen, r.Header.Get("Authorization"))
s.seenMu.Unlock()
if s.require != "" && r.Header.Get("Authorization") != "Bearer "+s.require {
w.Header().Set("WWW-Authenticate", "Bearer")
w.Header().Set("Content-Type", "application/problem+json")

View file

@ -0,0 +1,125 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/deleter.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"strings"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/issueops"
)
// maxDeleteIDs mirrors the wire's own bound (internal/httpapi's delete.go, and
// the document's maxItems). It is checked HERE as well as there for
// maxAddDependencyEdges' reason, which is sharper on this operation: the whole
// delete is ONE transaction with at most one history entry, so a client that
// split a long id list into two requests would turn one all-or-nothing erasure
// into two — and the dependents guard, which can only see the ids of the request
// in front of it, would refuse a pair the caller had deliberately listed
// together. Refusing names the bound; chunking would quietly change the
// semantics.
const maxDeleteIDs = 1000
// httpDeleter serves issueops.Deleter from the deleteIssues custom method
// (design D8 row 13) — the capability behind `bd delete`.
//
// The REQUEST maps WHOLE, ExpectedVersion included: deleteIssues publishes the
// compare-and-delete precondition and this client sends it, absent staying
// absent so an unguarded delete stays unguarded.
//
// What else diverges is the REFUSAL VOCABULARY, in two places, and both are
// ledgered rather than papered over:
//
// - an id naming no row arrives as issueops.ErrNotFound without the
// *NotFoundError that names WHICH ids (L-delete-notfound);
// - the unforced dependents guard arrives as issueops.ErrValidation rather
// than *DependentsOutsideRequestError (L-delete-dependents).
//
// Both still FAIL the request and still delete nothing — the outcome is the
// contract's, only the classification is coarser — and both retire the day the
// wire grows a distinguishing code and the extension members to rebuild them
// from. `bd delete` still names the ids it could not resolve, because the
// server's own role does and the CLI is talking to the person who typed them.
type httpDeleter struct {
store *Store
wire WriteWire
}
var _ issueops.Deleter = (*httpDeleter)(nil)
// Delete dials POST /v0/beads/issues:delete.
//
// The ids are sent VERBATIM — not trimmed, not deduplicated, not sorted. The
// role promises the caller's slice is read and never written through, and the
// SERVER's role performs exactly the same normalization a local one would, so
// doing it again here would be a second implementation of a rule that already
// has one, on the operation where a disagreement about which ids were named
// deletes the wrong rows.
func (d *httpDeleter) Delete(ctx context.Context, req issueops.DeleteRequest) (result issueops.DeleteResult, err error) {
// 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.
defer func() { err = d.store.inexpressible("Deleter.Delete", err) }()
if err := checkDeleteIDs(req.IDs); err != nil {
return issueops.DeleteResult{}, err
}
// The guard is sent as the caller spelled it and the ARITY rule that comes
// with it is left to the server. The wire refuses a guard beside more than
// one DISTINCT id, and distinctness there is measured after trimming and
// collapsing duplicates — the same normalization this method sends its ids
// verbatim to avoid owning a second copy of.
body := apigen.DeleteIssuesRequest{
Ids: append([]string(nil), req.IDs...),
Cascade: &req.Cascade,
Force: &req.Force,
DryRun: &req.DryRun,
ExpectedVersion: revisionGuard(req.ExpectedVersion),
}
if strings.TrimSpace(req.Actor) != "" {
// Omitted rather than sent blank, for SweepRequest.Actor's reason: the
// role accepts an empty Actor and the server refuses one that is empty
// after trimming.
body.Actor = &req.Actor
}
res, err := d.wire.DeleteIssues(ctx, body)
if err != nil {
return issueops.DeleteResult{}, err
}
out := issueops.DeleteResult{
DryRun: res.DryRun,
Deleted: res.Deleted,
Dependencies: res.Dependencies,
Labels: res.Labels,
Events: res.Events,
ReferencesUpdated: res.ReferencesUpdated,
}
if res.Orphaned != nil {
out.Orphaned = append([]string(nil), *res.Orphaned...)
}
return out, nil
}
// checkDeleteIDs applies the request-intrinsic refusals before the dial.
//
// Every one of them is decidable from the request alone and every one is a
// refusal the role's own contract states, so they must not cost a round trip to
// a shared server — and the empty case must not be answered as a cheerful
// "deleted 0", which is how a caller whose id list came out empty learns
// nothing at all.
func checkDeleteIDs(ids []string) error {
if len(ids) == 0 {
return invalid("a delete names no beads")
}
for i, id := range ids {
if strings.TrimSpace(id) == "" {
return invalid("ids[%d] is blank", i)
}
}
if len(ids) > maxDeleteIDs {
return refuse(encode.OpDeleteIssues, "L-delete-bound")
}
return nil
}

View file

@ -0,0 +1,139 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/dependencyeditor.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/issueops"
)
// maxAddDependencyEdges mirrors the wire's own bound (internal/httpapi's
// dependency_edit.go). It is checked HERE as well as there so the refusal names
// the bound instead of arriving as a 400 the user has to decode — and, more
// importantly, so nothing is ever tempted to chunk a larger request: chunking is
// the one path that silently breaks the request's one-transaction,
// one-history-entry contract (L16).
const maxAddDependencyEdges = 100
// httpDependencyEditor serves issueops.DependencyEditor from the two dependency
// custom methods (design D8 row 18).
//
// The role's whole difficulty is its refusal vocabulary, and the wave that
// landed these operations published the typed discriminators this client asked
// for: dependency_cycle carries issue_id/blocker_id/blocker_is_ancestor, so
// *DependencyHierarchyConflictError reconstructs in BOTH polarities with no
// prose parsing, and dependency_exists carries existing_type/requested_type. The
// mapping lives in the wire's problem table; what lives here is the request
// half and the members the wire cannot carry.
type httpDependencyEditor struct {
store *Store
wire WriteWire
}
var _ issueops.DependencyEditor = (*httpDependencyEditor)(nil)
// AddDependencies asserts a set of edges as one server-side transaction.
//
// Atomicity is the SERVER's and stays whole because the request does: the
// operation is all-or-nothing, so a client that split a graph across two
// requests would turn one atomic assertion into two and let a cycle gate that
// can only see one request at a time pass a graph that closes a loop across
// both. Hence the bound below refuses rather than chunks.
func (d *httpDependencyEditor) AddDependencies(ctx context.Context, req issueops.AddDependenciesRequest) (result issueops.AddDependenciesResult, err error) {
// 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.
defer func() { err = d.store.inexpressible("DependencyEditor.AddDependencies", err) }()
if err := requireActor(req.Actor); err != nil {
return issueops.AddDependenciesResult{}, err
}
if len(req.Edges) == 0 {
return issueops.AddDependenciesResult{}, invalid("a dependency add names no edges")
}
if req.SkipPerEdgeCycleCheck {
return issueops.AddDependenciesResult{}, refuse(encode.OpAddDependencies, "W-AddDependenciesRequest.SkipPerEdgeCycleCheck")
}
if len(req.Edges) > maxAddDependencyEdges {
return issueops.AddDependenciesResult{}, refuse(encode.OpAddDependencies, "L16")
}
edges := make([]apigen.DependencyEdge, 0, len(req.Edges))
for i, edge := range req.Edges {
if err := checkEdge(i, edge); err != nil {
return issueops.AddDependenciesResult{}, err
}
edges = append(edges, apigen.DependencyEdge{
IssueId: edge.IssueID,
DependsOnId: edge.DependsOnID,
Type: string(edge.Type),
})
}
res, err := d.wire.AddDependencies(ctx, apigen.AddDependenciesRequest{Actor: req.Actor, Edges: edges})
if err != nil {
return issueops.AddDependenciesResult{}, err
}
// The response echoes the request in request order, because all-or-nothing
// means it is either every edge or the call failed. Reading it back rather
// than re-echoing the request is what would catch a server that ever
// answered something else.
added := make([]issueops.DependencyEdge, 0, len(res.Added))
for _, edge := range res.Added {
added = append(added, issueops.DependencyEdge{
IssueID: edge.IssueId,
DependsOnID: edge.DependsOnId,
Type: issueops.DependencyType(edge.Type),
})
}
return issueops.AddDependenciesResult{Added: added}, nil
}
// RemoveDependency removes exactly the named edge. A missing edge is Removed
// false with a nil error — a success, not a refusal, and the wire says the same.
func (d *httpDependencyEditor) RemoveDependency(ctx context.Context, req issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) {
if err := requireActor(req.Actor); err != nil {
return issueops.RemoveDependencyResult{}, err
}
if err := requireID("issue id", req.IssueID); err != nil {
return issueops.RemoveDependencyResult{}, err
}
if err := requireID("depends-on id", req.DependsOnID); err != nil {
return issueops.RemoveDependencyResult{}, err
}
res, err := d.wire.RemoveDependency(ctx, apigen.RemoveDependencyRequest{
Actor: req.Actor,
IssueId: req.IssueID,
DependsOnId: req.DependsOnID,
})
if err != nil {
return issueops.RemoveDependencyResult{}, err
}
return issueops.RemoveDependencyResult{Removed: res.Removed}, nil
}
// checkEdge applies the request-intrinsic refusals before the dial.
//
// The self-dependency check is the one worth naming: the server refuses it too,
// but as a 400 that reaches a client as ErrValidation, while the role's contract
// promises ErrSelfDependency — and that sentinel is one the caller can act on.
// It is decidable from the request alone, so deciding it here loses nothing and
// keeps the vocabulary the role documents.
func checkEdge(i int, edge issueops.DependencyEdge) error {
switch {
case edge.IssueID == "":
return invalid("edges[%d].issue_id is required", i)
case edge.DependsOnID == "":
return invalid("edges[%d].depends_on_id is required", i)
case edge.Type == "":
return invalid("edges[%d].type is required", i)
case edge.IssueID == edge.DependsOnID:
return fmt.Errorf("%s: %w", edge.IssueID, issueops.ErrSelfDependency)
}
return nil
}

View file

@ -0,0 +1,139 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/detail_reads.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The four off-role detail reads that ride getIssue, each beside the surface it
// belongs to now that its operation is on the synced wire (design D8, the flip
// mechanics offrole.go's header states). They moved OUT of offrole.go the way
// resolve.go and bridge.go's reads did: a served method sits with its surface,
// and what stays in offrole.go is the tombstone.
//
// All four are the `bd show` text path's off-role reads. getIssue carries the
// labels and the default dependencies without a parameter; the dependents and
// comments arms travel through include_dependents and include_comments (D4; L4
// retired). Each answers the same value the local method does, so a caller
// reading `issue.Labels`, the dependency list, the dependents or the comment
// thread cannot tell the two apart.
//
// A MISS IS (nil, nil), NOT AN ERROR, for every one of them, and it is the raw
// method's own contract: getIssue answers a nonexistent id with a 404 that the
// wire maps to issueops.ErrNotFound, and the local reads answer a nonexistent id
// with an empty result and a nil error (dolt/labels.go, dolt/dependencies.go,
// dolt/events.go). Reporting the miss as an error would print the transport's
// vocabulary where the local answer is silence.
// getIssueDetails is the shared dial behind the three include-bearing reads: GET
// the issue-detail path with the caller's query and decode types.IssueDetails,
// exactly as bridge.go's GetIssue does. A 404 is (nil, nil) rather than an
// error, so each read maps its own empty answer onto it.
func (s *Store) getIssueDetails(ctx context.Context, id string, query url.Values) (*types.IssueDetails, error) {
if id == "" {
return nil, nil
}
path, err := wire.IssuePath(id)
if err != nil {
return nil, err
}
var details types.IssueDetails
err = s.dispatch(ctx, wire.Request{
Op: wire.OpGetIssue,
Method: http.MethodGet,
Path: path,
Query: query,
IssueID: id,
}, &details)
if errors.Is(err, issueops.ErrNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &details, nil
}
// GetLabels serves getIssue's label list; `bd show`'s text path discards its
// error today (D4).
//
// It delegates to the raw GetIssue probe rather than re-dialing, because that
// probe already performs the lift the detail view needs — the labels arrive in a
// field of the envelope's OWN rather than on the embedded issue, and GetIssue
// hoists them onto issue.Labels so the two backends answer the same value. A
// second dial here would be a second copy of that correction.
func (s *Store) GetLabels(ctx context.Context, id string) ([]string, error) {
issue, err := s.GetIssue(ctx, id)
if err != nil || issue == nil {
return nil, err
}
return issue.Labels, nil
}
// GetDependenciesWithMetadata answers getIssue's default-carried dependency
// list. No parameter asks for it — dependencies ride every detail read, and
// brief_deps defaults false so the rows arrive whole.
func (s *Store) GetDependenciesWithMetadata(ctx context.Context, id string) ([]*types.IssueWithDependencyMetadata, error) {
details, err := s.getIssueDetails(ctx, id, url.Values{})
if err != nil || details == nil {
return nil, err
}
return details.Dependencies, nil
}
// GetDependentsWithMetadata answers getIssue's dependents arm, which is carried
// only when asked: include_dependents is the parameter D4 landed for it.
//
// The rows come back in the collectDependents SHALLOW projection (be-4d36f2:
// id, status, type, priority, title and the edge type only), because a hub bead
// with thousands of dependents would otherwise marshal gigabytes. That is the
// field set `bd show`'s dependents section and its reader-accessor JSON consume,
// so those paths are full-parity — but a caller reading any field OUTSIDE it
// over http reads a zero. `bd show --thread/--refs/--children` are exactly such
// callers (the message thread reads a reply's sender/recipient/body/timestamp,
// --refs/--children --json marshal the row whole), so they refuse against an
// http workspace rather than render a silently gutted answer (the show entry in
// enterprise_http_refusal.go carries the flag refusals and the citation). A
// full-dependent wire shape would retire those refusals and is a server-side ask.
func (s *Store) GetDependentsWithMetadata(ctx context.Context, id string) ([]*types.IssueWithDependencyMetadata, error) {
q := url.Values{}
q.Set("include_dependents", "true")
details, err := s.getIssueDetails(ctx, id, q)
if err != nil || details == nil {
return nil, err
}
return details.Dependents, nil
}
// GetIssueComments answers getIssue's comment thread, carried only when
// include_comments asks for it.
//
// comments_omitted MUST be absent or false on the answer, and this checks it:
// the server sets that marker only in count-only mode, where a positive
// CommentCount sits beside a nil Comments (ga-clgh). A caller that read those nil
// Comments as an empty thread would mistake a withheld read for "no comments" —
// the exact confusion the marker exists to prevent — so a truthy marker beside a
// request that explicitly asked for the bodies is a server answering a different
// question, and it fails loudly rather than returning a silent empty.
func (s *Store) GetIssueComments(ctx context.Context, id string) ([]*types.Comment, error) {
q := url.Values{}
q.Set("include_comments", "true")
details, err := s.getIssueDetails(ctx, id, q)
if err != nil || details == nil {
return nil, err
}
if details.CommentsOmitted != nil && *details.CommentsOmitted {
return nil, fmt.Errorf("bd serve withheld the comment thread for %q despite include_comments: "+
"comments_omitted is set, which the operation reserves for count-only mode", id)
}
return details.Comments, nil
}

322
internal/httpclient/dial.go Normal file
View file

@ -0,0 +1,322 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/dial.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
)
// WireUserAgentSuffix identifies the backend inside a stamped User-Agent, so a
// server log line says both which binary and which client spoke to it.
const WireUserAgentSuffix = wire.DefaultUserAgent
// DialOptions tunes the production transport.
type DialOptions struct {
// UserAgent identifies the build. wire's own default names the backend only,
// because the version stamp lives in package main and nothing under this
// tree may import it; the activation layer passes the stamped one down.
UserAgent string
// HTTPClient replaces the transport. Tests use it to reach an httptest
// server or to inject a round tripper; production leaves it nil.
//
// Leaving this nil is what lets DialWith apply a target's CA trust
// (BEADS_HTTP_CA_FILE, or the sidecar's ca_file) automatically, and raise
// MaxIdleConnsPerHost even when no CA is configured — see TransportFor and
// baselineTransport.
//
// A caller that supplies an HTTPClient whose Transport is nil is not
// silently skipped: DialWith injects the resolved CA transport (if any)
// on a COPY of that client, leaving the caller's own *http.Client
// untouched, exactly as if HTTPClient had been left nil except that the
// other fields (Timeout, CheckRedirect, Jar) are the caller's.
//
// A caller that supplies an HTTPClient with a NON-NIL Transport has taken
// the transport over completely. If the target has no CA configured, it
// is used verbatim — DialWith has nothing to add. If the target DOES have
// a CA configured, DialWith refuses rather than silently using a
// transport that may not trust it: the caller must either leave
// Transport nil (and let DialWith inject), or compose TransportFor(target)
// (or TransportForFile, for the embedder door) into its own Transport
// itself before calling.
HTTPClient *http.Client
// caOverride, when non-nil, replaces resolveCAFile's own env/sidecar
// resolution entirely: DialWith uses *caOverride verbatim (which may
// itself report "no CA configured" via its own configured() == false).
//
// It is set two ways, both of which need CAFileEnv taken completely out
// of the loop rather than merely out-prioritized:
//
// - DialOptionsForFile, which has already built HTTPClient's Transport
// from exactly one explicit file. Without this, DialWith's own
// env-scoped resolveCAFile would run anyway and could trip the
// caller-supplied-Transport refusal below the moment CAFileEnv
// happens to be set (and host-scoped-match) for the same target
// being verified.
// - DialOptionsForTarget, which backend/http's embedder door uses for
// EVERY dial: an embedder juggling several targets in one process
// must not have any of them silently renarrowed, or blocked, by an
// ambient CAFileEnv value a completely unrelated invocation
// exported — only Target.CAFile, passed explicitly, may ever apply
// on that door.
//
// Unexported: a caller outside this package can never set it directly, so
// an external HTTPClient always goes through one of the two constructors
// above, or the normal env-aware resolution.
caOverride *resolvedCA
}
// Conn is the store's view of one wire client.
//
// It exists to answer the WireClient seam's ServerContext with the GATED
// handshake rather than the raw fetch: api_version equality and, when the
// workspace recorded one, project identity are the two checks a snapshot must
// pass before anything is served from it (design D6). GetContext would return a
// body from any server that answered.
type Conn struct {
*wire.Client
}
func (c *Conn) ServerContext(ctx context.Context) (*apigen.ContextResponse, error) {
snap, err := c.Handshake(ctx)
if err != nil {
return nil, err
}
body := snap.Context
return &body, nil
}
// Dial builds the transport for one resolved target: the default credential
// ladder plus a wire client bound to it.
func Dial(target Target, opts DialOptions) (*Conn, error) {
return DialWith(target, NewBearerProvider(target.BaseURL), opts)
}
// DialWith is Dial with the credential source chosen by the caller — the other
// half of the D5 seam, for the layers that ride it: a gateway dialer outside
// this repo and the public registrant (backend/http), each of
// which binds a provider this package does not know about.
//
// It exists so the target-to-client mapping has ONE body. The gateway dialer
// used to build the wire client itself, and the registrant would have been the
// second copy of the same six lines; what a copy really duplicates is
// ExpectProjectID, the identity pin that travels on the Target and is applied
// through the wire Options — a caller that dropped it would dial a client whose
// handshake silently skips the wrong-server gate.
//
// creds may be nil, which is the tip OSS server's loopback-trust posture: no
// Authorization header is sent and a 401 is never retried.
//
// When opts.HTTPClient is nil, or has a nil Transport, DialWith resolves
// target's CA trust (the same env-scoped resolution TransportFor does) and
// dials with a transport scoped to it — see DialOptions.HTTPClient for the
// exact rules, including the refusal when a caller-supplied HTTPClient
// already has its own Transport and the target has a CA configured. This is
// what lets `bd connect --ca-file` verify a server during its own Handshake
// call, before anything is written, and what lets the default and gateway
// dialers honor BEADS_HTTP_CA_FILE with no further plumbing. Every dial also
// gets the raised MaxIdleConnsPerHost ceiling (baselineTransport), whether or
// not a CA is configured — the RTT cost of an under-pooled host is the same
// either way.
func DialWith(target Target, creds CredentialProvider, opts DialOptions) (*Conn, error) {
var resolved resolvedCA
if opts.caOverride != nil {
resolved = *opts.caOverride
} else {
var err error
resolved, err = resolveCAFile(target)
if err != nil {
return nil, err
}
}
switch {
case opts.HTTPClient == nil:
transport, terr := dialTransport(resolved)
if terr != nil {
return nil, terr
}
opts.HTTPClient = &http.Client{Transport: transport, Timeout: wire.DefaultTimeout}
case opts.HTTPClient.Transport == nil:
// The SAME transport the opts.HTTPClient == nil arm above builds
// through dialTransport — the CA-scoped one when resolved names a
// file, the shared raised-ceiling baseline otherwise — because the
// doc comment above promises that ceiling on EVERY dial "whether or
// not a CA is configured", and a caller-supplied client with a nil
// Transport is still a dial this package owns the Transport for.
// Leaving it nil here would let it default to
// http.DefaultTransport's own unraised ceiling at request time
// instead, silently exempting this one caller-supplied-client shape
// from that promise. Injected onto a COPY, so the caller's own
// *http.Client (Timeout, CheckRedirect, Jar) is left untouched.
transport, terr := dialTransport(resolved)
if terr != nil {
return nil, terr
}
clientCopy := *opts.HTTPClient
clientCopy.Transport = transport
opts.HTTPClient = &clientCopy
default:
if resolved.configured() {
matched, verifyErr := matchesCachedTransport(opts.HTTPClient.Transport, resolved.path)
if !matched {
if errors.Is(verifyErr, errCAFileChangedSinceTransportBuilt) {
return nil, fmt.Errorf(
"%s configures a CA for %s, and the supplied HTTPClient's Transport was built by this package for the same file, but that file has changed since: %w",
resolved.label, target, verifyErr)
}
if verifyErr != nil {
return nil, fmt.Errorf(
"%s configures a CA for %s, but verifying the supplied HTTPClient's Transport against the current file failed: %w",
resolved.label, target, verifyErr)
}
return nil, fmt.Errorf(
"%s configures a CA for %s, but the supplied HTTPClient's Transport is not the CA-scoped one this package builds for it; leave DialOptions.HTTPClient nil (or its Transport nil) to let DialWith inject it, or build the Transport from TransportFor(target) (or TransportForFile) so DialWith can recognize it as exactly that CA's transport — or, if you deliberately want a transport of your own choosing, clear the CA (Target.CAFile, and any %s pattern that matches this target) and own trust yourself",
resolved.label, target, CAFileEnv)
}
}
// Either no CA is configured for this target, or the caller's
// Transport IS the cached CA-scoped transport TransportFor(target)
// (or TransportForFile) builds for resolved.path — the documented
// embedder recipe of composing that transport into HTTPClient before
// calling. Either way there is nothing to inject and nothing to
// refuse.
}
client, err := wire.New(target.BaseURL, creds, wire.Options{
HTTPClient: opts.HTTPClient,
UserAgent: opts.UserAgent,
ExpectProjectID: target.ExpectProjectID,
})
if err != nil {
return nil, err
}
return &Conn{Client: client}, nil
}
// dialTransport builds the transport DialWith uses when the caller left
// HTTPClient nil entirely: the CA-scoped one when resolved names a file, or
// the shared baseline (system roots, raised MaxIdleConnsPerHost) otherwise.
func dialTransport(resolved resolvedCA) (http.RoundTripper, error) {
if resolved.configured() {
return transportForFile(resolved.path, resolved.label)
}
return baselineTransport(), nil
}
var (
baselineTransportOnce sync.Once
baselineTransportRT http.RoundTripper
)
// baselineTransport is the http.RoundTripper DialWith uses for a target with
// no CA configured: http.DefaultTransport's own system-roots TLS trust,
// completely unchanged, but with MaxIdleConnsPerHost raised the same way
// TransportFor raises it for a CA-scoped target (see maxIdleConnsPerHost in
// ca.go) — applied to every http-backend target, not only CA-configured ones,
// since the RTT cost of an under-pooled host is identical either way. Built
// once and reused for the life of the process: nothing about it depends on
// per-target state, so there is nothing to key a cache on and no reason to
// pay Clone() on every dial.
func baselineTransport() http.RoundTripper {
baselineTransportOnce.Do(func() {
transport := http.DefaultTransport.(*http.Transport).Clone() //nolint:errcheck // http.DefaultTransport is always *http.Transport
transport.MaxIdleConnsPerHost = maxIdleConnsPerHost
baselineTransportRT = transport
})
return baselineTransportRT
}
// DefaultDialer is the WireDialer the enterprise distribution registers.
//
// It performs no handshake: design D6 makes the context fetch lazy, on the first
// post-baseline dispatch, so opening a workspace to run `bd ready` costs one
// round trip rather than two. The store owns that fetch and caches it.
func DefaultDialer(opts DialOptions) WireDialer {
return func(_ context.Context, target Target) (WireClient, error) {
return Dial(target, opts)
}
}
// RegisterDefaultDialer installs the production transport. Init-time wiring
// only, the same rule as RegisterWireDialer itself.
func RegisterDefaultDialer(opts DialOptions) {
RegisterWireDialer(DefaultDialer(opts))
}
// Handshake dials target once and returns its gated startup snapshot.
//
// It is the connect path's probe: `bd connect` verifies a server before it
// writes anything, and it must do so without opening a store, because the
// workspace it is about to describe may not select this backend yet. A project
// mismatch comes back as *wire.ProjectMismatchError, which names both ids plus
// the server's own database and repo root.
func Handshake(ctx context.Context, target Target, opts DialOptions) (*apigen.ContextResponse, error) {
conn, err := Dial(target, opts)
if err != nil {
return nil, err
}
return conn.ServerContext(ctx)
}
// DialOptionsForFile returns base with HTTPClient set to a transport scoped
// to EXACTLY caFile, bypassing CAFileEnv and any sidecar entirely.
//
// It exists for `bd connect --ca-file X`: X must be verified for itself,
// before it is written anywhere, regardless of what BEADS_HTTP_CA_FILE
// currently resolves to for the same host — otherwise a `bd connect` run with
// the env var set to a good CA and --ca-file pointed at a wrong one would
// verify against the env's CA while writing the flag's unverified one to the
// sidecar. Passing the returned DialOptions (with Target.CAFile left "" for
// this call) to Handshake or Dial makes the verification match exactly what
// the flag names.
func DialOptionsForFile(caFile string, base DialOptions) (DialOptions, error) {
transport, err := TransportForFile(caFile)
if err != nil {
return DialOptions{}, err
}
base.HTTPClient = &http.Client{Transport: transport, Timeout: wire.DefaultTimeout}
// This transport was just built from exactly caFile, deliberately
// bypassing CAFileEnv and any sidecar. DialWith must not re-resolve the
// CA from the ambient environment for this call, nor refuse the
// Transport just assigned above as an unrecognized caller-supplied one —
// an empty override reports "no CA configured" to DialWith's default
// branch, which is exactly right: this HTTPClient's Transport is already
// final. See DialOptions.caOverride.
empty := resolvedCA{}
base.caOverride = &empty
return base, nil
}
// DialOptionsForTarget returns base with CA resolution pinned to EXACTLY
// target.CAFile, bypassing CAFileEnv entirely — never consulting it, not even
// to prefer the sidecar over a non-matching pattern.
//
// It exists for backend/http's embedder door (newDialer), which must compute
// this FRESH for every target it dials: an embedder juggling several targets
// in one process must not have any of them silently renarrowed to a private
// CA, or blocked from a legitimate one, because an unrelated invocation
// exported CAFileEnv for a completely different target. Unlike
// DialOptionsForFile, this does not build a transport itself — base.HTTPClient
// is left exactly as the caller supplied it (nil, a client with a nil
// Transport for DialWith to inject into on a copy, or a client whose
// Transport the caller already built via TransportFor(target)), and DialWith
// resolves and injects, or recognizes and accepts, from this override alone.
func DialOptionsForTarget(target Target, base DialOptions) DialOptions {
resolved := resolvedCA{}
if caFile := strings.TrimSpace(target.CAFile); caFile != "" {
resolved = resolvedCA{path: caFile, label: "ca_file"}
}
base.caOverride = &resolved
return base
}

View file

@ -0,0 +1,221 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/dial_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"net/http"
"net/http/httptrace"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
)
// TestBaselineTransportRaisesMaxIdleConnsPerHost is finding 9: the ceiling
// TransportFor already applies to a CA-scoped target must ALSO apply to an
// ordinary target with no CA configured, since the RTT cost of an
// under-pooled host is the same either way.
func TestBaselineTransportRaisesMaxIdleConnsPerHost(t *testing.T) {
rt := baselineTransport()
transport, ok := rt.(*http.Transport)
if !ok {
t.Fatalf("baselineTransport returned %T, want *http.Transport", rt)
}
if transport.MaxIdleConnsPerHost != maxIdleConnsPerHost {
t.Errorf("MaxIdleConnsPerHost = %d, want %d", transport.MaxIdleConnsPerHost, maxIdleConnsPerHost)
}
}
// TestBaselineTransportIsSharedAcrossCalls confirms baselineTransport is built
// once and reused (sync.Once), not cloned per dial: a long-lived process must
// not leak a fresh transport, and its connection pool, on every dial of a
// target that never configured a CA.
func TestBaselineTransportIsSharedAcrossCalls(t *testing.T) {
first := baselineTransport()
second := baselineTransport()
if first != second {
t.Error("baselineTransport returned a different instance on a second call; it should be built once and reused")
}
}
// TestDialTransportUsesBaselineWhenNoCAConfigured is finding 9's unit test on
// the exact seam DialWith uses when the caller leaves HTTPClient nil: an
// unconfigured resolvedCA must produce the shared baselineTransport, not a
// freshly cloned one, and it must carry the raised ceiling.
func TestDialTransportUsesBaselineWhenNoCAConfigured(t *testing.T) {
rt, err := dialTransport(resolvedCA{})
if err != nil {
t.Fatalf("dialTransport: %v", err)
}
if rt != baselineTransport() {
t.Error("dialTransport did not return the shared baselineTransport for an unconfigured CA")
}
}
// TestDialWithNoCARaisesMaxIdleConnsPerHost is finding 9's end-to-end case: a
// target with no CA configured, dialed through DialWith with HTTPClient left
// nil, still reaches a real server through the raised-ceiling baseline
// transport.
func TestDialWithNoCARaisesMaxIdleConnsPerHost(t *testing.T) {
clearCAEnvironment(t)
server := &contextServer{body: v0Context("proj-baseline")}
srv := server.start(t)
target := Target{BaseURL: mustParseURL(t, srv.URL)}
snap, err := Handshake(context.Background(), target, DialOptions{})
if err != nil {
t.Fatalf("Handshake: %v", err)
}
if snap.ProjectId != "proj-baseline" {
t.Errorf("project_id = %q, want proj-baseline", snap.ProjectId)
}
}
// TestDialWithSuppliedClientNilTransportNoCARaisesMaxIdleConnsPerHost covers
// the OTHER shape DialWith's own doc comment promises the raised ceiling for
// ("Every dial also gets the raised MaxIdleConnsPerHost ceiling... whether or
// not a CA is configured"): a caller that supplies its own *http.Client with
// a nil Transport, dialed against a target with no CA configured. The
// opts.HTTPClient == nil branch above (TestDialWithNoCARaisesMaxIdleConnsPerHost)
// does not exercise this branch at all — a caller-supplied client with a nil
// Transport used to fall through to http.DefaultTransport's own unraised
// MaxIdleConnsPerHost of 2 instead, silently exempting this one shape from
// the doc's "every dial" promise, and forcing a fresh connection (a fresh TLS
// handshake, over a real network) on most of a concurrent burst even once the
// pool is warm.
//
// This asserts it end to end, through wire.Client.Do rather than by reaching
// into the transport this package's *Conn hands wire.New (wire.Client keeps
// it unexported, and rightly so): a burst of concurrent requests through the
// resulting Conn, traced with httptrace the way
// TestTransportForRaisesMaxIdleConnsPerHostForBursts traces a raw
// *http.Transport, must settle into reusing every connection once the pool
// has gone idle — which the default ceiling of 2 cannot do at this burst
// size.
func TestDialWithSuppliedClientNilTransportNoCARaisesMaxIdleConnsPerHost(t *testing.T) {
clearCAEnvironment(t)
server := &contextServer{body: v0Context("proj-supplied-client")}
srv := server.start(t)
target := Target{BaseURL: mustParseURL(t, srv.URL)}
supplied := &http.Client{}
conn, err := DialWith(target, nil, DialOptions{HTTPClient: supplied})
if err != nil {
t.Fatalf("DialWith: %v", err)
}
if supplied.Transport != nil {
t.Error("DialWith mutated the caller's own *http.Client in place; it must inject onto a copy")
}
const burst = 8
req := wire.Request{Op: "test.burst", Method: http.MethodGet, Path: "/v0/test-burst"}
runBurst := func() int64 {
var wg sync.WaitGroup
var newConns int64
for i := 0; i < burst; i++ {
wg.Add(1)
go func() {
defer wg.Done()
reused := make(chan bool, 1)
trace := &httptrace.ClientTrace{
GotConn: func(info httptrace.GotConnInfo) { reused <- info.Reused },
}
ctx := httptrace.WithClientTrace(context.Background(), trace)
if err := conn.Do(ctx, req, &apigen.ContextResponse{}); err != nil {
t.Errorf("Do: %v", err)
return
}
if !<-reused {
atomic.AddInt64(&newConns, 1)
}
}()
}
wg.Wait()
return newConns
}
if warm := runBurst(); warm == 0 {
t.Fatal("first burst reused connections that could not have existed yet")
}
var steady int64
for attempt := 0; attempt < 5; attempt++ {
time.Sleep(50 * time.Millisecond)
steady = runBurst()
if steady == 0 {
break
}
}
if steady != 0 {
t.Errorf("repeat burst dialed %d/%d fresh connections after warm-up; the supplied-client-nil-Transport branch is not getting the raised MaxIdleConnsPerHost ceiling", steady, burst)
}
}
// --- finding 2: DialOptionsForFile ---
// TestDialOptionsForFileBypassesEnvEntirely is finding 2's core unit: a
// DialOptions built from an explicit file must verify against EXACTLY that
// file, never BEADS_HTTP_CA_FILE, even when the env is set to a DIFFERENT,
// otherwise-valid CA for the same host. This is what lets `bd connect
// --ca-file X` check X for itself before writing it, regardless of what the
// env currently resolves to.
func TestDialOptionsForFileBypassesEnvEntirely(t *testing.T) {
clearCAEnvironment(t)
right := newTestCA(t)
wrong := newTestCA(t)
h := &caContextHandler{body: v0Context("proj-connect-check")}
u := wrong.startServer(t, h.handler())
// The env is set to a CA that would NOT verify this server; if
// DialOptionsForFile consulted it, the handshake below would fail for the
// wrong reason, or a matching-host env could mask the flag's own file
// entirely.
t.Setenv(CAFileEnv, u.Host+"="+right.writePEM(t))
opts, err := DialOptionsForFile(wrong.writePEM(t), DialOptions{})
if err != nil {
t.Fatalf("DialOptionsForFile: %v", err)
}
// Target.CAFile is deliberately left empty, mirroring cmd/bd's connect
// verification call.
target := Target{BaseURL: u}
snap, err := Handshake(context.Background(), target, opts)
if err != nil {
t.Fatalf("Handshake verifying exactly the flag's CA file: %v", err)
}
if snap.ProjectId != "proj-connect-check" {
t.Errorf("project_id = %q, want proj-connect-check", snap.ProjectId)
}
}
// TestDialOptionsForFileRefusesTheWrongCAEvenWithAGoodEnv is finding 2's exact
// regression scenario: "With the env var set to the good CA and --ca-file set
// to a wrong CA, connect succeeded" (the bug). DialOptionsForFile must make
// the handshake fail here, since --ca-file's own file is the wrong one.
func TestDialOptionsForFileRefusesTheWrongCAEvenWithAGoodEnv(t *testing.T) {
clearCAEnvironment(t)
right := newTestCA(t)
wrong := newTestCA(t)
h := &caContextHandler{body: v0Context("proj-should-not-verify")}
u := right.startServer(t, h.handler())
t.Setenv(CAFileEnv, u.Host+"="+right.writePEM(t))
opts, err := DialOptionsForFile(wrong.writePEM(t), DialOptions{})
if err != nil {
t.Fatalf("DialOptionsForFile: %v", err)
}
target := Target{BaseURL: u}
_, err = Handshake(context.Background(), target, opts)
if err == nil {
t.Fatal("Handshake succeeded with --ca-file's own wrong CA, despite a good env CA for the same host; DialOptionsForFile must check exactly the flag's file")
}
if h.sawRequest() {
t.Error("server saw a request; TLS verification against the wrong CA should have failed first")
}
}

View file

@ -0,0 +1,113 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/dispatch.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/steveyegge/beads/internal/httpclient/wire"
)
const (
// maxIdempotentRetries bounds how many times dispatch comes back to a busy
// server for one idempotent read. Three attempts total: a 503 is transient
// slot pressure, and a client that hammered past this would BE the contention
// it is waiting out.
maxIdempotentRetries = 2
// baseRetryBackoff is the wait before the first retry when the server named no
// Retry-After. It doubles each attempt, capped at maxRetryBackoff.
baseRetryBackoff = 200 * time.Millisecond
// maxRetryBackoff caps a COMPUTED backoff. A server's own Retry-After is
// already bounded by wire.Options.MaxRetryAfter and is honored as it is given.
maxRetryBackoff = 5 * time.Second
)
// dispatch is this store's ONE door to the wire, and the only place the
// two-speed policy of D6 is spelled.
//
// Every operation goes through Preflight first — the policy itself lives in the
// wire package, which knows that five baseline operations return immediately and
// that every other one forces the handshake and consults the advertised token.
// Putting the call here rather than at each role method is what makes "every
// dispatch site honors the two-speed policy" a property of the code rather than
// of a reviewer's memory: a role that wants to reach the server has no other
// route to it.
//
// It is also the one place that knows an operation's HTTP method, so the bounded
// 503 retry lives here: the wire layer bounds Retry-After and hands it back but
// never sleeps or resends, precisely because whether a 503 is safe to come back
// to is a question only the method answers, and only a GET's answer is yes.
//
// A store with no transport is a build-wiring fault (ErrNoTransport), not the
// user's: the workspace and the server may both be fine.
func (s *Store) dispatch(ctx context.Context, req wire.Request, out any) error {
if s.wire == nil {
return fmt.Errorf("%w: cannot dial %s", ErrNoTransport, s.target)
}
if err := s.wire.Preflight(ctx, req.Op); err != nil {
return err
}
err := s.wire.Do(ctx, req, out)
// Only an idempotent GET is retried. A 503 can interrupt a non-idempotent
// write whose first attempt already committed before the server ran out of
// slots, so resending a POST/PATCH/DELETE could double-apply it — DELETE
// included, since forgetMemory is a mutation the wire happens to spell as one.
if req.Method != http.MethodGet {
return err
}
for attempt := 0; attempt < maxIdempotentRetries; attempt++ {
wait, retry := retryBackoff(err, attempt)
if !retry {
return err
}
if sleepErr := sleepWithContext(ctx, wait); sleepErr != nil {
// The caller's deadline won out mid-backoff. Surface the server's busy
// answer rather than the context error: "bd serve is busy" is the
// actionable diagnosis, and the deadline is downstream of it.
return err
}
err = s.wire.Do(ctx, req, out)
}
return err
}
// retryBackoff reports whether err is a 503-class busy answer worth coming back
// to, and how long to wait first. It honors the server's already-bounded
// Retry-After when present, and otherwise backs off exponentially from
// baseRetryBackoff. A nil error, a non-ProblemError, or any non-retryable
// problem stops the loop.
func retryBackoff(err error, attempt int) (time.Duration, bool) {
var prob *wire.ProblemError
if !errors.As(err, &prob) || !prob.Retryable() {
return 0, false
}
if prob.RetryAfter > 0 {
return prob.RetryAfter, true
}
backoff := baseRetryBackoff << attempt
if backoff > maxRetryBackoff {
backoff = maxRetryBackoff
}
return backoff, true
}
// sleepWithContext waits for d or until ctx is done, whichever comes first. A
// non-positive d is not a sleep at all, so it returns at once.
func sleepWithContext(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}

View file

@ -0,0 +1,139 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/dispatch_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"net/http"
"testing"
"time"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
)
// busyThenOK answers with a 503 for the first busyCount Do calls and succeeds
// after, recording how many times it was dialed. It is the dispatch retry's
// double: a real server's slot pressure clears the same way.
type busyThenOK struct {
busyCount int
retryAfter time.Duration
calls int
}
func (b *busyThenOK) do(_ context.Context, req wire.Request, _ any) error {
b.calls++
if b.calls <= b.busyCount {
return &wire.ProblemError{
Op: req.Op,
Status: http.StatusServiceUnavailable,
Err: wire.ErrBusy,
RetryAfter: b.retryAfter,
}
}
return nil
}
func retryTestStore(t *testing.T, do func(context.Context, wire.Request, any) error) *Store {
t.Helper()
w := &fakeWire{
res: &apigen.ContextResponse{},
preflight: func(context.Context, string) error { return nil },
do: do,
}
return New(testTarget(t), w, nil)
}
func readRequest() wire.Request {
return wire.Request{Op: wire.OpListReadyWork, Method: http.MethodGet, Path: wire.PathReady}
}
// TestDispatchRetriesIdempotentReadsOnBusy: a GET that a 503 turned away comes
// back, honors the server's Retry-After, and succeeds once the slot frees.
func TestDispatchRetriesIdempotentReadsOnBusy(t *testing.T) {
server := &busyThenOK{busyCount: 2, retryAfter: time.Millisecond}
s := retryTestStore(t, server.do)
if err := s.dispatch(context.Background(), readRequest(), nil); err != nil {
t.Fatalf("dispatch: %v, want the retry to succeed", err)
}
if server.calls != 3 {
t.Errorf("Do called %d times, want 3 (one dial plus two retries)", server.calls)
}
}
// TestDispatchCapsIdempotentRetries: a server that stays busy is not dialed
// forever. The bound is one dial plus maxIdempotentRetries, and the 503 is what
// the caller finally sees.
func TestDispatchCapsIdempotentRetries(t *testing.T) {
server := &busyThenOK{busyCount: 100, retryAfter: time.Millisecond}
s := retryTestStore(t, server.do)
err := s.dispatch(context.Background(), readRequest(), nil)
if !errors.Is(err, wire.ErrBusy) {
t.Fatalf("dispatch = %v, want the busy error once the retries are spent", err)
}
if server.calls != 1+maxIdempotentRetries {
t.Errorf("Do called %d times, want %d (one dial plus the capped retries)", server.calls, 1+maxIdempotentRetries)
}
}
// TestDispatchDoesNotRetryWrites: a non-idempotent write is dialed exactly once
// on a 503, because its first attempt may have committed before the server ran
// out of slots and a resend would double-apply it.
func TestDispatchDoesNotRetryWrites(t *testing.T) {
server := &busyThenOK{busyCount: 1, retryAfter: time.Millisecond}
s := retryTestStore(t, server.do)
write := wire.Request{Op: wire.OpClaimIssue, Method: http.MethodPost, Path: "/v0/beads/issues/bd-1:claim"}
err := s.dispatch(context.Background(), write, nil)
if !errors.Is(err, wire.ErrBusy) {
t.Fatalf("dispatch = %v, want the busy error unretried", err)
}
if server.calls != 1 {
t.Errorf("a write was dialed %d times on a 503, want exactly 1", server.calls)
}
}
// TestDispatchDoesNotRetryNonBusyReads: a read is retried only for the 503 busy
// class. A 500 fault is the same request earning the same answer, so it is not
// retried.
func TestDispatchDoesNotRetryNonBusyReads(t *testing.T) {
var calls int
s := retryTestStore(t, func(_ context.Context, req wire.Request, _ any) error {
calls++
return &wire.ProblemError{Op: req.Op, Status: http.StatusInternalServerError, Err: wire.ErrServerFault}
})
err := s.dispatch(context.Background(), readRequest(), nil)
if !errors.Is(err, wire.ErrServerFault) {
t.Fatalf("dispatch = %v, want the server fault unretried", err)
}
if calls != 1 {
t.Errorf("a 500 was dialed %d times, want exactly 1", calls)
}
}
// TestDispatchRetryStopsWhenTheContextIsDone: a caller whose deadline expires
// mid-backoff stops retrying and gets the server's busy answer, not a wait that
// outlives the request.
func TestDispatchRetryStopsWhenTheContextIsDone(t *testing.T) {
server := &busyThenOK{busyCount: 100, retryAfter: time.Hour} // never clears in time
s := retryTestStore(t, server.do)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
start := time.Now()
err := s.dispatch(ctx, readRequest(), nil)
if !errors.Is(err, wire.ErrBusy) {
t.Fatalf("dispatch = %v, want the busy error when the deadline cut the wait short", err)
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Errorf("dispatch honored the hour-long Retry-After past the caller's deadline (%s)", elapsed)
}
if server.calls != 1 {
t.Errorf("Do called %d times; the deadline should have stopped the first backoff", server.calls)
}
}

View file

@ -0,0 +1,160 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/divergence_citation_gate_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/steveyegge/beads/internal/httpclient/encode"
)
// The invariant this gate holds is "nothing skips without a ledger row": every
// served-tier park calls skipKnownDivergence(t, <row>, ...) naming the
// divergence-ledger id (encode/ledger.go) that says WHAT the wire cannot carry.
//
// Until now that binding was a STRING and nothing more. The row a park cites
// was checkable only by a reader who went and looked, so a row renamed or
// deleted in encode/ledger.go left its parks citing a coordinate that resolves
// to nothing — the exact drift the ledger's own RowByID panic and bijection
// gate exist to make impossible on the ENCODER side, but which the park side
// had no counterpart for. A park that cites a dead row still skips, still reads
// as "known divergence", and no test notices.
//
// This gate closes that gap by machine-binding each citation to a LIVE row.
// It parses the served test sources, collects every skipKnownDivergence park's
// cited id, and resolves each through the encoder's own lookup — the same
// RowByID a refusal raises through — failing on any id no live row carries. A
// park resolves here iff a refusal citing the same id would; the two can no
// longer disagree.
//
// It binds the row's KIND as well as its existence, because existence alone
// leaves the more likely rot: a row is far more often RETIRED than deleted, and
// a park citing a retired row resolves cleanly while skipping a case whose
// divergence upstream already closed. Retirement is the moment those cases must
// come back, so it is the moment this fails.
//
// It is deliberately UNTAGGED, for the reason divergence_test.go states about
// the helper it guards: the parks live behind //go:build cgo, but a gate that
// reads them as TEXT needs no build tag to do so, and one that carried the cgo
// tag would go blind in exactly the no-cgo build where a citation could rot
// unobserved. The encode package it resolves against is pure Go.
const parkHelperName = "skipKnownDivergence"
// parkCitation is one skipKnownDivergence call site: the ledger row it cites and
// where it cites it, so a failure names the park rather than just the id.
type parkCitation struct {
row string
pos string
}
func TestDivergenceParkCitationsResolveToLiveLedgerRows(t *testing.T) {
cites := collectParkCitations(t, ".")
if len(cites) == 0 {
// Finding nothing is itself a failure: the helper was renamed or moved
// out of this package and the gate now guards an empty set.
t.Fatalf("found no %s parks to bind; the helper was renamed or moved and this gate now guards nothing", parkHelperName)
}
for _, c := range cites {
row, ok := resolveLedgerRow(c.row)
if !ok {
t.Errorf("%s: %s parks on ledger row %q, which no live encoder-ledger row resolves (encode/ledger.go) — the row was renamed or deleted and this park now cites nothing",
c.pos, parkHelperName, c.row)
continue
}
// RESOLVING IS NOT ENOUGH, and the gap between the two is a park that
// keeps skipping forever. A row's KIND is what says whether the wire
// still cannot carry the thing: refuse and degrade are live divergences,
// and KindRetired means the divergence is GONE — upstream published the
// member, or the client started sending it. A case parked on a retired
// row is a case whose reason expired, and because the park is a
// t.Skipf it goes on reporting itself as a known divergence rather than
// as coverage that should have come back. Retiring a row is exactly when
// its parks must be re-run, so it is exactly when this has to fail.
if row.Kind == encode.KindRetired {
t.Errorf("%s: %s parks on ledger row %q, which is RETIRED — the divergence it cites no longer exists, so this case is skipping for a reason that expired. Unpark it (and delete the citation), or move the park onto the row that describes what still diverges",
c.pos, parkHelperName, c.row)
}
}
}
// resolveLedgerRow returns the row an id names through the encoder's own lookup —
// the one every refusal raises through.
//
// RowByID panics on an unknown id, which encode/ledger.go documents as the
// correct severity for a refusal. The gate recovers it so a dead citation reads
// as a located test failure instead of a raw stack trace, and so one dead park
// does not hide the next.
func resolveLedgerRow(id string) (row encode.Row, ok bool) {
defer func() {
if recover() != nil {
row, ok = encode.Row{}, false
}
}()
return encode.RowByID(id), true
}
// collectParkCitations reads the row every skipKnownDivergence park cites out of
// the sources rather than from a hand-kept list, for the reason the ledger's own
// gates are derived rather than restated: a second copy is a second thing that
// can be wrong. It scans this package's test files only, because the helper is
// package-private and a park elsewhere could not call it by bare name.
func collectParkCitations(t *testing.T, dir string) []parkCitation {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read %s: %v", dir, err)
}
fset := token.NewFileSet()
var cites []parkCitation
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), "_test.go") {
continue
}
path := filepath.Join(dir, entry.Name())
file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
if err != nil {
t.Fatalf("parse %s: %v", path, err)
}
ast.Inspect(file, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
fn, ok := call.Fun.(*ast.Ident)
if !ok || fn.Name != parkHelperName {
return true
}
pos := fset.Position(call.Pos()).String()
// The signature is skipKnownDivergence(t, row, beadID, reason): the
// receiver comes first and the cited row is the second argument.
if len(call.Args) < 2 {
t.Errorf("%s: %s(...) has too few arguments to carry a ledger-row citation", pos, parkHelperName)
return true
}
lit, ok := call.Args[1].(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
// A citation the gate cannot read statically defeats the whole
// invariant: the row a park names has to be a fact this test can
// resolve, not one computed at runtime.
t.Errorf("%s: %s cites a non-literal ledger row (%T); the citation must be a string literal so it can be bound to a live row",
pos, parkHelperName, call.Args[1])
return true
}
row, err := strconv.Unquote(lit.Value)
if err != nil {
t.Errorf("%s: cannot read ledger-row citation %s: %v", pos, lit.Value, err)
return true
}
cites = append(cites, parkCitation{row: row, pos: pos})
return true
})
}
return cites
}

View file

@ -0,0 +1,35 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/divergence_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import "testing"
// skipKnownDivergence parks one conformance case on the backend that cannot
// express what the leaf contract asserts.
//
// It takes BOTH coordinates a park has, because they answer different
// questions and neither implies the other:
//
// - row is the divergence-ledger id (encode/ledger.go). It says WHAT the wire
// cannot carry and is the join back to the reason, the design decision and
// the pin. It used to be spelled inside the reason prose, in parentheses,
// which made it unfindable by anything but a reader.
// - beadID names the bead that records the shape and owns its retirement. It
// says WHO unparks the case, which is a different fact from why it is
// parked: several rows retire with one bead, and one row can outlive the
// bead that found it.
//
// The literal "KNOWN DIVERGENCE" prefix is how `grep -r "KNOWN DIVERGENCE"`
// finds every parked case in the tree. Parking at the WIRING site rather than
// inside the shared Run function is what keeps the case honest elsewhere: it
// still runs, and still passes, on every backend that agrees.
//
// THIS FILE CARRIES NO BUILD TAG, and that is deliberate. Every call site today
// is cgo-tagged, because the served composition needs the embedded engine — but
// a helper declared behind the tag is a helper the no-cgo build cannot see, so
// the first untagged park would not compile. An unused function costs nothing;
// a declaration that has to move the day someone needs it costs a merge.
func skipKnownDivergence(t *testing.T, row, beadID, reason string) {
t.Helper()
t.Skipf("KNOWN DIVERGENCE %s (%s): %s", row, beadID, reason)
}

View file

@ -85,7 +85,8 @@ func TestEncoderTableClassifiesEveryRequestField(t *testing.T) {
if !classified[name] {
t.Errorf("%s.%s is populatable and UNCLASSIFIED.\n"+
"Add it to the %s table with a disposition, or refuse it with a divergence-ledger row.\n"+
"An unclassified field is a filter this client would drop silently — see engdocs/design/http-client-backend.md D7 and D9 L12.",
"An unclassified field is a filter this client would drop silently — see L12 in the in-repo "+
"divergence ledger, engdocs/design/http-divergence-ledger.md.",
table.Source.Name(), name, tableName(table))
}
}

View file

@ -21,9 +21,11 @@
// stays hand-written is the value rendering, which is exactly what the
// round-trip gate drives through the server's own decoder.
//
// See engdocs/design/http-client-backend.md — D7 (the refusal taxonomy), D8
// (the role dispositions and the refuse-not-drop enumeration), D9 (the
// divergence ledger), D11 (id resolution) and D12 (MaxRows).
// The refusal taxonomy, the role dispositions and refuse-not-drop
// enumeration, id resolution and MaxRows all trace back to the original
// (bd-enterprise-internal) design's decision log; the divergence ledger
// itself (D9 there) is reproduced in-repo at
// engdocs/design/http-divergence-ledger.md, generated from ledger.go below.
package encode
import (

View file

@ -13,11 +13,13 @@ import (
// The divergence ledger, v1.
//
// engdocs/design/http-client-backend.md D9 states the discipline this file
// instantiates: "Every knowingly-degraded behavior is a ledger row with a
// pinned test... A degradation not in this table is a bug." The prose table
// lives in the design; this is the machine-readable copy the client actually
// consults, and it carries three populations rather than one:
// The original (bd-enterprise-internal) design's decision log, D9, states the
// discipline this file instantiates: "Every knowingly-degraded behavior is a
// ledger row with a pinned test... A degradation not in this table is a
// bug." That design doc is not included in this repository; this is the
// machine-readable copy the client actually consults, rendered to
// engdocs/design/http-divergence-ledger.md (see ledger_render.go), and it
// carries three populations rather than one:
//
// - The D9 rows themselves (L1-L18, with L17 deleted rather than skipped —
// see the L-sequence note in designRows), which describe whole behaviors rather
@ -110,7 +112,10 @@ type Row struct {
// Why is the reason the wire cannot carry it, or the reason the
// degradation is the right answer.
Why string
// SpecRow cites the decision in engdocs/design/http-client-backend.md.
// SpecRow cites the decision in the original design's decision log (D-rows
// and D9 L-row numbers; the log itself is not in this repository — a D9
// L-row resolves in-repo to the same L-row in
// engdocs/design/http-divergence-ledger.md, generated from this file).
SpecRow string
// PinnedBy names the test that holds this row honest, or carries a
// TODO(<bead>) when the pinning test is another bead's deliverable. It is
@ -143,7 +148,7 @@ type Row struct {
// TestEncoderHonorsEveryTableDisposition,
// TestEncodedParametersRoundTripThroughTheServerDecoder, and friends); this
// sentinel covers only the rows whose evidence is a layer S2 never touches.
const pinnedByS3Conformance = "TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the S2 handoff notes for the full list of rows re-pinned here and engdocs/design/http-client-backend.md D9 for the discipline"
const pinnedByS3Conformance = "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"
// Ledger returns divergence ledger v1, in citation order.
//
@ -207,6 +212,10 @@ var (
tyCreateDep = reflect.TypeOf(issueops.CreateDependency{})
tyApplyCreateItem = reflect.TypeOf(issueops.CreateItem{})
tyApplyDepAddItem = reflect.TypeOf(issueops.DepAddItem{})
tyCloseBatchRequest = reflect.TypeOf(issueops.CloseBatchRequest{})
tySweepRequest = reflect.TypeOf(issueops.SweepRequest{})
)
// designRows are D9's own table, transcribed. They describe behaviors rather
@ -218,22 +227,22 @@ func designRows() []Row {
// auto-load (L5), auto-import (L6), the ready view's parent-epic map (L13) —
// whose observable behavior is a cmd/bd invocation's, not a store call's.
// They are the subprocess parity tier's, and that tier is the one this wiring
// did not build. ga-b8ddd.12 (per-request project-id enforcement) closed the
// read-display ESCALATION — every read now carries the stamp, so a drifted
// server refuses it rather than rendering another project's rows — but the
// remaining fixture corpus that would PIN these pre-run displays is its
// follow-up, ga-b8ddd.23, which owns them.
// did not build. A since-closed per-request project-id enforcement follow-up
// closed the read-display ESCALATION — every read now carries the stamp, so a
// drifted server refuses it rather than rendering another project's rows —
// but the remaining fixture corpus that would PIN these pre-run displays is
// a separate, still-open follow-up that owns them.
//
// L17 (the conditional dep-remove guard) used to be the one remaining TODO row
// that was NOT subprocess-owned. It carried no row of its own once its
// condition resolved: the dual run ga-b8ddd.30 wrote
// condition resolved: a dual run
// (TestServedDependencyRecordsSurfaceUnresolvedRowsVerbatim) showed the wire
// surfaces unresolved depends_on_id rows VERBATIM, so the guard does not
// degrade and there was nothing to ledger. It is DELETED rather than retired,
// because a retirement records a divergence that once existed and this one
// never did. L1 is the retirement beside it — a row that WAS live and is kept
// as KindRetired for exactly that reason.
const pinnedElsewhere = "TODO(ga-b8ddd.23): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it"
const pinnedElsewhere = "TODO(S3): a pre-run degradation, observable only through a cmd/bd invocation; the subprocess parity corpus pins it"
return []Row{
{
// IT WAS DELETED OUTRIGHT for a while, against this file's own
@ -466,6 +475,15 @@ func designRows() []Row {
// refuse, and the refusal never dials.
PinnedBy: pinnedByS3Conformance,
},
{
ID: "L-cycles-tracks", Kind: KindRefuse,
Type: reflect.TypeOf(issueops.DetectCyclesRequest{}), Field: "IncludeTracks",
What: "issueops.CycleDetector.DetectCycles refuses a request with IncludeTracks set, rather than silently answering the narrower (tracks-excluded) walk",
Why: "listDependencyCycles (wire.OpListDependencyCycles) publishes no include_tracks parameter at all — there is no wire member to widen the walk onto, not merely one this client chose not to send. Honoring the request field anyway (by just not sending it, the way a dropped filter would) would answer the DEFAULT walk to a caller who explicitly asked for the wider one that also follows `tracks` edges: a narrower answer with no error, exactly the failure mode ErrUnsupported exists to make loud instead of silent (see its own doc). " +
"Upstream ask: an include_tracks query parameter on listDependencyCycles, which retires this row",
SpecRow: "D8 (refuse-not-drop), D9 L16 (the same argument, on a read)",
PinnedBy: pinnedByS3Conformance,
},
{
ID: "L-batchcreate-target", Kind: KindDegrade,
What: "a batch create whose edge target names no issue refuses as issueops.ErrValidation alone, not as ErrValidation WRAPPING ErrNotFound",
@ -482,7 +500,7 @@ func designRows() []Row {
PinnedBy: pinnedByS3Conformance,
},
// L17 (the conditional GH#5005 dep-remove guard) is DELETED, not present as a
// row: ga-b8ddd.30's dual run proved the wire surfaces unresolved
// row: a dual run proved the wire surfaces unresolved
// depends_on_id rows verbatim (see pinnedElsewhere above), so the
// degradation it was contingent on never materialized. The L-sequence skips
// from L16 to L18 for that reason.
@ -521,12 +539,12 @@ func writeSideRows() []Row {
const pinned = pinnedByS3Conformance
return []Row{
{
ID: "W-UpdateRequest.Claim", Kind: KindRefuse,
ID: "W-UpdateRequest.Claim", Kind: KindRetired,
Type: tyUpdateRequest, Field: "Claim",
What: "a claim combined with any other UpdateRequest member refuses; a claim ALONE does not — it dials claimIssue directly (see httpLifecycle.claimOnlyUpdate)",
Why: "a claim is claimIssue's own operation and updateIssue cannot perform one, on this wire or on any other; it is the one row here that upstream #5484 did not touch. " +
"claimIssue's own request is the actor alone, so a claim-only UpdateRequest IS that request and is served through the Claimer role instead of refusing — that is gc's exclusive claim path, `bd update <id> --claim --json`. " +
"What still refuses is PATCH claim: a claim folded into one atomic transaction WITH a patch, a guard or a force override, which no operation on this wire publishes and which is not synthesized as two calls (claimIssue then updateIssue), since that would let a caller observe an issue claimed but not yet patched. Upstream gastownhall/beads#6890 tracks the capability that would carry both in one call",
What: "a claim combined with a patch, a guard or a force override used to refuse",
Why: "RETIRED by the #7247 review port. The refusal stood on 'updateIssue cannot perform a claim, on this wire or on any other' — and upstream gastownhall/beads#6890, the capability the row itself named, had already published `claim` on updateIssue: the claim and the patch applied by the same role in one transaction, so PATCH claim was the server's shape and only this client's refusal. " +
"The body now sends `claim` as a pointer set true only on request, so a claim alone, a claim with a patch and a claim with a version guard are each ONE updateIssue call, answered with the post-write `revision` like every other update. " +
"The claimIssue route survives as the fallback for a claim ALONE against a server that predates the member, which refuses it as an unknown parameter before any database work; a combination against such a server returns that skew refusal rather than splitting into two calls",
SpecRow: updateSpec,
PinnedBy: pinned,
},
@ -537,49 +555,55 @@ func writeSideRows() []Row {
// http workspace — so this is user-facing prose, not an internal
// engineering note, and it should read that way.
//
// The engineering rationale, for a future reader of this file: the v0
// wire's claimIssue operation (issueops.Claimer's own contract)
// answers a wisp id with ErrNotFound on every backend, including the
// direct route's own claim-by-id — the wisp plane is not claimable
// through that role at all. But claimOnlyUpdate's caller is
// `bd update <id> --claim`, whose Lifecycle.Update DOES claim wisps
// locally (issue-or-wisp routing). Over http, that command is served
// through claimIssue rather than through updateIssue's general
// wisp-aware routing, so a wisp id would otherwise surface the wire's
// generic not-found — a live row reported as though it does not
// exist, indistinguishable from an id naming nothing at all, which a
// not-found-sensitive caller (gc's Claim among them) would read as
// missing rather than as an unclaimable wisp. This refuses by name
// instead, once the client itself recognizes the id names a wisp —
// which it learns only AFTER claimIssue itself answers not_found (see
// claimOnlyUpdate), so an ordinary claim of a real, non-wisp issue
// never pays this probe. Serving a wisp-aware claim (a server-side
// ClaimWisp capability) is tracked as a pending decision, not
// implemented here.
// The engineering rationale, for a future reader of this file: a
// current server claims a wisp through updateIssue, which resolves
// both planes exactly as the direct route's Lifecycle.Update does, so
// this row is reached ONLY on claimOnlyUpdate's fallback — a server
// that predates `claim` on updateIssue (upstream #6890), where the
// claim is dialed as claimIssue instead. That operation
// (issueops.Claimer's own contract) answers a wisp id with ErrNotFound
// on every backend — the wisp plane is not claimable through that
// role at all — so a wisp id would otherwise surface the wire's
// generic not-found: a live row reported as though it does not
// exist, which a not-found-sensitive caller (gc's Claim among them)
// would read as missing rather than as an unclaimable wisp. This
// refuses by name instead, once the client itself recognizes the id
// names a wisp — which it learns only AFTER claimIssue answers
// not_found, so an ordinary claim of a real, non-wisp issue never
// pays the probe.
ID: "W-ClaimRequest.Wisp", Kind: KindRefuse,
What: "claiming a wisp is not supported over http",
Why: "the v0 wire's claim operation excludes the wisp plane on every backend; claim this issue from a local workspace instead",
What: "claiming a wisp is not supported by this bd serve",
Why: "the server predates claiming through its update operation, and its separate claim operation excludes the wisp plane; upgrade bd serve, or claim this issue from a local workspace",
SpecRow: updateSpec,
PinnedBy: pinnedByS3Conformance,
},
{
ID: "W-UpdateRequest.ForceAssigneeTransfer", Kind: KindRefuse, Flag: "--force",
ID: "W-UpdateRequest.ForceAssigneeTransfer", Kind: KindRetired, Flag: "--force",
Type: tyUpdateRequest, Field: "ForceAssigneeTransfer",
What: "bypassing the anti-steal assignee fence refuses",
Why: "the wire publishes `force_assignee_transfer` (upstream #5484) and this client does not send it. What the refusal STANDS ON changed with client wave ga-7i6by and the row is narrower for it: the `assignee` the fence guards IS now sent (W-IssuePatch.Assignee), so what is left is the bypass alone. " +
"The fence itself is unbypassable rather than absent — a transfer away from a live foreign in-progress owner refuses with already_claimed, and a matched `expected_assignee` is the OTHER bypass, which this client does send. Carrying this one is a two-member port tracked as ga-2ltro.15",
What: "bypassing the anti-steal assignee fence used to refuse",
Why: "RETIRED by the #7247 review port, the two-member port ga-2ltro.15 named. The wire publishes `force_assignee_transfer` (upstream #5484) and the refusal was always this client's: client wave ga-7i6by had already narrowed it to the bypass alone by sending the `assignee` the fence guards, and issues:batchApply's update item already carried the same flag. " +
"The body now sends it as a pointer set true only on request. The fence itself is unchanged — a transfer away from a live foreign in-progress owner refuses with already_claimed unless one of the two bypasses rides with it, this one or a matched `expected_assignee` — and the server refuses the bypass without a `patch.assignee` or beside `expected_assignee` or `claim`",
SpecRow: updateSpec,
PinnedBy: pinned,
},
{
ID: "W-UpdateRequest.ForceClosePolicy", Kind: KindRefuse, Flag: "--force",
ID: "W-UpdateRequest.ForceClosePolicy", Kind: KindRetired, Flag: "--force",
Type: tyUpdateRequest, Field: "ForceClosePolicy",
What: "bypassing close policy on a status-crossing update refuses",
Why: "the wire publishes `force_close_policy` (upstream #5484) and this client does not send it; see W-UpdateRequest.ForceAssigneeTransfer for what the refusal now stands on, since client wave ga-7i6by sends the `status` whose crossing the policy gates. " +
"The policy is therefore enforced and not bypassable here: a status crossing into the done category with open children or a live blocker refuses with not_closable, typed, and writes nothing. Tracked as ga-2ltro.15",
What: "bypassing close policy on a status-crossing update used to refuse",
Why: "RETIRED with W-UpdateRequest.ForceAssigneeTransfer, the other half of ga-2ltro.15's port. The wire publishes `force_close_policy` (upstream #5484), client wave ga-7i6by sends the `status` whose crossing the policy gates, and issues:batchApply's update item already carried the flag. " +
"The body now sends it as a pointer set true only on request; unforced, a status crossing into the done category with open children or a live blocker still refuses with not_closable, typed, and writes nothing",
SpecRow: updateSpec,
PinnedBy: pinned,
},
{
ID: "W-UpdateRequest.ForceNotesOverwrite", Kind: KindRetired,
Type: tyUpdateRequest, Field: "ForceNotesOverwrite",
What: "bypassing the notes-overwrite fence on a single update used to refuse",
Why: "RETIRED by the S3 reconciliation that found it (2026-10). It was discovered refused on the single-patch updateIssue path while the identical flag was already carried on issues:batchApply's update item (W table entry applyBatch/item/update) — the same trio member, wired on one shape and not the other with no decision on record for the gap. " +
"Flipping it was a port, not a decision, same as W-UpdateRequest.ExpectedVersion's: the body now sends `force_notes_overwrite` as a pointer set true only on request, so a Patch.Notes that would replace existing non-empty notes with different non-empty content is bypassable here exactly as it already was on the batch path",
SpecRow: updateSpec,
PinnedBy: pinnedByS3Conformance,
},
{
ID: "W-UpdateRequest.ExpectedVersion", Kind: KindRetired,
What: "the compare-and-set row-version precondition used to refuse",
@ -671,7 +695,7 @@ func writeSideRows() []Row {
ID: "W-IssuePatch.Assignee", Kind: KindRetired,
What: "assignment and unassignment through update used to refuse",
Why: "RETIRED with W-IssuePatch.Status (ga-7i6by). The EMPTY STRING is the half that makes this member more than a rename: it UNASSIGNS, so a client that skipped an empty value would turn a real edit into no edit at all. " +
"The anti-steal fence around it is the server's and is unchanged — a transfer away from a live foreign in-progress owner still refuses with already_claimed, and the two bypasses (`force_assignee_transfer` and a matched `expected_assignee`) are W-UpdateRequest.ForceAssigneeTransfer and the guard wave's own",
"The anti-steal fence around it is the server's and is unchanged — a transfer away from a live foreign in-progress owner still refuses with already_claimed, and the two bypasses (`force_assignee_transfer` and a matched `expected_assignee`) are both sent — the first since W-UpdateRequest.ForceAssigneeTransfer retired, the second since the guard wave",
SpecRow: "D8 refuse-not-drop",
PinnedBy: patchMemberPin,
},
@ -725,7 +749,8 @@ func writeSideRows() []Row {
What: "an item whose Issue populates any member outside the wire's eight refuses, naming the member",
Why: "apigen.BatchCreateItem carries title, description, design, acceptance_criteria, priority, issue_type, assignee and labels and nothing else, while the role accepts far more of a types.Issue: an explicit id, the wisp flags, metadata, the storage class, every timestamp, the gate/molecule/event fields. " +
"ONE row rather than one per member because the reason is one reason — the wire's item vocabulary — and forty rows repeating it would say nothing a reader does not learn here. Exhaustiveness is held by REFLECTION instead: the client's carried and role-ignored tables are checked against types.Issue field by field, so a member added upstream is refused the day it lands rather than dropped until someone notices. " +
"The members the role ITSELF ignores on a create (ContentHash, RowVersion, lease, compaction, routing overrides, hydration flags) are not in this population and are not refused: a local create drops them too",
"The members the role ITSELF ignores on a create (ContentHash, RowVersion, lease, compaction, routing overrides, hydration flags) are not in this population and are not refused: a local create drops them too. " +
"Nor is a CreatedBy that names the request's actor: the server stamps every item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses",
SpecRow: "D8 row 14 refuse-not-drop",
PinnedBy: batchCreatePin,
},
@ -744,9 +769,10 @@ func writeSideRows() []Row {
{
ID: "W-CreateRequest.IDPrefix", Kind: KindRefuse,
Type: tyCreateRequest, Field: "IDPrefix",
What: "overriding the prefix an explicit id is checked against refuses",
What: "overriding the prefix an explicit, unforced id is checked against refuses",
Why: "createIssue publishes no `id_prefix`, and the omission is the SERVER's decision rather than a gap (internal/httpapi/create.go): the field exists because a workspace's own config.yaml prefix wins over the database's and only a local front door can read that file, so a remote caller's config.yaml describes a workspace this server does not serve. " +
"Publishing it would let a caller override the served workspace's prefix rule from outside it. Dropping it instead would check the id against the SERVER's prefix while the caller believed it was checked against theirs — the same request, two different answers to 'may this workspace mint this id'",
"Publishing it would let a caller override the served workspace's prefix rule from outside it. Dropping it instead would check the id against the SERVER's prefix while the caller believed it was checked against theirs — the same request, two different answers to 'may this workspace mint this id'. " +
"It refuses only where it would ACT: the role reads the override for nothing but an explicit id it was not told to force, so a create that mints its id, or sets ForceIDPrefix, is the same request with or without it and is sent without it. That matters because `bd create` sends the workspace's prefix on EVERY create, so an unconditional refusal would refuse every create in a workspace whose config.yaml names one",
SpecRow: "D8 row 16 refuse-not-drop",
PinnedBy: createPin,
},
@ -754,9 +780,10 @@ func writeSideRows() []Row {
ID: "W-CreateRequest.Issue", Kind: KindRefuse,
Type: tyCreateRequest, Field: "Issue",
What: "a create whose Issue populates any member outside the wire's twenty refuses, naming the member",
Why: "createIssue publishes the whole create VOCABULARY — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue: the creation stamp (created_at, created_by), because a caller-supplied creation time makes the row disagree with the journal entry that records it and re-dating history is what an import is for; and spec_id, await_*, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface publishes on no operation, read or write. " +
Why: "createIssue publishes the whole create VOCABULARY — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue: the creation time (created_at), because a caller-supplied creation time makes the row disagree with the journal entry that records it and re-dating history is what an import is for; and spec_id, await_*, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface publishes on no operation, read or write. " +
"ONE row rather than one per member for W-BatchCreateItem.Issue's reason — the reason is one reason — and exhaustiveness is held by the same REFLECTION over types.Issue, sharing the role-ignored table with the batch so the two operations cannot disagree about what the ROLE drops. " +
"Issue.Comments and Issue.Dependencies are not in this population: the role itself refuses them, so a local create fails too and this is validation rather than divergence",
"Issue.Comments and Issue.Dependencies are not in this population: the role itself refuses them, so a local create fails too and this is validation rather than divergence. " +
"created_by is published on no create shape either, but every one of them STAMPS it from the request's actor (internal/httpapi's create.go, batch_create.go and batch_apply.go) — the local front doors' own rule, since the role copies the member rather than stamping it. So a CreatedBy that names the actor, which is what every CLI create sends, arrives as written, and only one naming someone else refuses: the stamp would silently replace it. A server that predates the stamp stores an empty created_by for that one member",
SpecRow: "D8 row 16 refuse-not-drop",
PinnedBy: createPin,
},
@ -765,7 +792,7 @@ func writeSideRows() []Row {
What: "a create whose dependency or waits-for target names no row refuses as issueops.ErrValidation ALONE — not as ErrValidation wrapping ErrNotFound — and does not name the target",
Why: "the wire answers a dangling target with a 400 invalid_argument naming `dependencies` and a FIXED detail (internal/httpapi's failCreateIssue), which deliberately does not quote the role's own message: that message arrives as a driver error naming tables and constraints, and 4xx details on this surface reflect the caller's own input back rather than server internals. " +
"The refusal still fails the whole request and creates NOTHING — the promise the row is about — and only the second sentinel and the target's name are lost. It is batchCreateIssues' L-batchcreate-notfound on the single create, and it retires the same way: an upstream code that distinguishes the absent-target refusal and carries the target. " +
"A missing --parent target already retired out of this row: failCreateIssue's errors.As(&parentNotFound) arm answers it with a distinguishing 404 not_found that names the target, and the client maps that to issueops.ErrNotFound (see TestServedCreateRefusesAnAbsentParentAsNotFound) — the row now covers only dependency and waits-for targets",
"A missing --parent target stays on this row beside dependency and waits-for targets, not ahead of them: OpCreateIssue's problem-code table documents NO 404 for ANY edge target on purpose (internal/httpapi/problem.go) — there is no id in the path for parent_id to have missed any more than dependencies[i].target_id or waits_for.spawner_id has, so carving a parent-only not_found out of this row would contradict that design rather than follow it. A prior draft of this row and its pin (TestServedCreateRefusesAnAbsentParentAsNotFound) described that carve-out as already shipped; it never was, and the S3 review that found the drift retired the draft rather than the design",
SpecRow: "D8 row 16",
PinnedBy: pinnedByS3Conformance,
},
@ -780,17 +807,19 @@ func writeSideRows() []Row {
// The issues:batchApply population, from client wave ga-mijra. It is
// SMALL, and that is the operation rather than an oversight: the create
// item publishes createIssue's whole twenty, the close item maps whole,
// the edge item maps whole, and the update item's patch is WIDER than
// updateIssue's in the two places that matter to a plan (a full label
// patch, and `owner`). What is left is one patch member and two facts
// about the RESULT.
// the edge item maps whole but for the spawner flag and the thread the
// role gained after the wire was written, and the update item's patch
// is WIDER than updateIssue's in the two places that matter to a plan (a
// full label patch, and `owner`). What is left is one patch member, those
// two edge members and two facts about the RESULT.
{
ID: "W-CreateItem.Issue", Kind: KindRefuse,
Type: tyApplyCreateItem, Field: "Issue",
What: "a create ITEM whose Issue populates any member outside the wire's twenty refuses, naming the member",
Why: "ApplyCreateItem publishes exactly createIssue's create vocabulary — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue, for the reasons W-CreateRequest.Issue gives in full. " +
"It is a row of its OWN rather than a citation of that one because the operations are different: a caller auditing why their PLAN refuses must not be sent to a row about a single create, and the two can diverge the day either vocabulary moves. The partition itself is SHARED — one carried table, one role-ignored table, held against types.Issue by the same reflection — so they cannot disagree about what the wire carries or about what the role drops. " +
"Issue.Comments and Issue.Dependencies are not in this population and are refused as validation on both sides: edges in this role are ITEMS, so a create item has nowhere to put one at all",
"Issue.Comments and Issue.Dependencies are not in this population and are refused as validation on both sides: edges in this role are ITEMS, so a create item has nowhere to put one at all. " +
"Nor is a CreatedBy that names the request's actor: the server stamps every create item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses",
SpecRow: "D8 refuse-not-drop",
PinnedBy: applyPin,
},
@ -804,6 +833,24 @@ func writeSideRows() []Row {
SpecRow: "D8 refuse-not-drop",
PinnedBy: applyPin,
},
{
ID: "W-DepAddItem.HasSpawner", Kind: KindRefuse,
Type: tyApplyDepAddItem, Field: "HasSpawner",
What: "a waits-for edge ITEM that names its spawner refuses",
Why: "ApplyDepAddItem publishes source, target, type and metadata and no spawner member, and the flag asks for a write only the ROLE can make: metadata's spawner_id, stamped from the resolved target once every id in the batch exists, because a target named by key has no id before then. " +
"Dropping the flag would store the edge's gate-only metadata, so an edge whose caller named a spawner would carry none. On every other edge type the role ignores the flag and stores the same row either way, so there it is dropped rather than refused. Upstream ask: a spawner member on ApplyDepAddItem, which retires this row",
SpecRow: "D8 refuse-not-drop",
PinnedBy: applyPin,
},
{
ID: "W-DepAddItem.ThreadID", Kind: KindRefuse,
Type: tyApplyDepAddItem, Field: "ThreadID",
What: "associating an edge ITEM with a discussion thread refuses",
Why: "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",
SpecRow: "D8 refuse-not-drop",
PinnedBy: applyPin,
},
{
ID: "L-apply-snapshot", Kind: KindDegrade,
What: "every ItemResult of a batch apply comes back with Issue nil, where a local backend hydrates a post-item snapshot",
@ -918,6 +965,53 @@ func writeSideRows() []Row {
SpecRow: "D8 (Journal), D9",
PinnedBy: pinnedByS3Conformance,
},
{
// S3 reconciliation (2026-10): bd-enterprise's
// batchCloseIssues composed an atomic claim-after-close onto the
// same request; OSS's apigen.BatchCloseRequest and
// BatchCloseResponse publish no claim_next/claimed_next member at
// all, so there is no shape for this field to narrow INTO. A batch
// close without a folded claim is unaffected and stays served
// (BatchCloseIssues.go); this row is the ONE field that refuses.
ID: "W-CloseBatchRequest.ClaimNext", Kind: KindRefuse,
Type: tyCloseBatchRequest, Field: "ClaimNext",
What: "folding an atomic claim-after-close onto a batch close refuses",
Why: "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",
SpecRow: "D8 refuse-not-drop",
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,
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",
SpecRow: "D8 refuse-not-drop",
PinnedBy: pinnedByS3Conformance,
},
{
// 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,
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",
SpecRow: "D8 refuse-not-drop",
PinnedBy: pinnedByS3Conformance,
},
}
}
@ -990,11 +1084,11 @@ func commandRows() []Row {
row("F-ready-explain", "ready", "--explain", "`bd ready --explain` refuses",
"it dispatches onto raw GetBlockedIssues/GetIssuesByIDs/GetDependencyCounts/DetectCycles, three of which are on the unsupported allowlist"),
row("F-ready-mol", "ready", "--mol", "`bd ready --mol` refuses",
"its molecule subgraph load reaches findHierarchicalChildren, an IDPrefix SearchIssues shape the parent-walk bridge cannot express (E-IssueFilter.noShape). GetDependencyRecords and GetDependentsWithMetadata, which the same load also calls, stopped being the blocker when ga-b8ddd.30 flipped them onto the wire"),
"its molecule subgraph load reaches findHierarchicalChildren, an IDPrefix SearchIssues shape the parent-walk bridge cannot express (E-IssueFilter.noShape). GetDependencyRecords and GetDependentsWithMetadata, which the same load also calls, stopped being the blocker once they flipped onto the wire"),
row("F-ready-gated", "ready", "--gated", "`bd ready --gated` refuses",
"it dispatches onto a filtered SearchIssues shape the bridge cannot express, plus GetDependents"),
row("F-show-thread", "show", "--thread", "`bd show --thread` refuses",
"showMessageThread renders each reply's sender, recipient, body and timestamp off GetDependentsWithMetadata, but ga-b8ddd.30 flipped that read onto getIssue's include_dependents parameter, which carries the collectDependents SHALLOW projection (id/status/type/priority/title + edge type only, be-4d36f2). Those fields come back zeroed over http and zero-timestamp replies sort ahead of the root — a silent-wrong degrade the refuse-over-degrade doctrine forbids. Retires with a full-dependent wire shape, a server-side ask"),
"showMessageThread renders each reply's sender, recipient, body and timestamp off GetDependentsWithMetadata, but that read was flipped onto getIssue's include_dependents parameter, which carries the collectDependents SHALLOW projection (id/status/type/priority/title + edge type only, be-4d36f2). Those fields come back zeroed over http and zero-timestamp replies sort ahead of the root — a silent-wrong degrade the refuse-over-degrade doctrine forbids. Retires with a full-dependent wire shape, a server-side ask"),
row("F-show-refs", "show", "--refs", "`bd show --refs` refuses",
"showIssueRefs's --json marshals the full GetDependentsWithMetadata rows, but the wire answers the same collectDependents shallow projection, so created_at/assignee/description come back zeroed and the JSON differs from a local workspace. The text render consumes only the shallow fields, but the flag cannot be split from its --json mode, so the whole flag refuses rather than serve a divergent JSON silently"),
row("F-show-children", "show", "--children", "`bd show --children` refuses",

View file

@ -190,17 +190,17 @@ hand-edit it: change the ledger in Go and regenerate. Two gates keep it honest
the encoder's reflection **bijection gate** pins the ledger to the wire (a
request field added upstream lands here or fails CI), and the golden test
` + "`TestDivergenceLedgerDocMatchesLedger`" + ` pins this doc to the ledger. The prose
rationale, the decision numbers (D-rows) each entry cites, and the full test-lane
map live in the architecture spec, ` + "`http-client-backend.md`" + `, which is not
included in this repository.
rationale and the decision numbers (D-rows) each entry cites trace back to the
original (bd-enterprise-internal) design's decision log, which is not included
in this repository; the full test-lane map lives alongside each row below.
A handful of rows still carry a ` + "`TODO`" + ` pin: these are the read-display and
pre-run residuals (wisp-in-list, the pretty ` + "`bd ready`" + ` parent-epic map, the
molecule/auto-import pre-run degradations). The
client core is complete; ` + "`ga-b8ddd.12`" + ` (per-request project-id enforcement)
closed the read-display escalation, so pinning the remaining fixture corpus is
deferred work, tracked on ` + "`ga-b8ddd.23`" + ` (the read-display residual)
and ` + "`ga-b8ddd.19`" + ` (the per-id D7 taxonomy). They are refusals or degradations
client core is complete; a since-closed per-request project-id enforcement
follow-up closed the read-display escalation, so pinning the remaining
fixture corpus is deferred work (tracked as a read-display residual and a
per-id D7 taxonomy follow-up). They are refusals or degradations
already in force — the ` + "`TODO`" + ` is on the test that will hold each one, not on
the behavior.

View file

@ -64,6 +64,12 @@ const (
// all four published — so it is built inline beside the three graph reads
// that share its collection. Its refusal still has to name an operation.
OpCountDependencyEdges Op = "countDependencyEdges"
// listDependencyCycles carries no encoder table either: the request has
// exactly one member (IncludeTracks) and the wire has no parameter for it
// at all, so there is nothing to tabulate — the one refusal is built
// inline beside the role. See "L-cycles-tracks".
OpListDependencyCycles Op = "listDependencyCycles"
)
// Disposition is what becomes of one request field on its way to the wire.

View file

@ -0,0 +1,102 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/errors.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"fmt"
"sort"
"github.com/steveyegge/beads/internal/storage"
)
// ErrHTTPUnsupported is returned by every refused method of the http store. It
// unwraps to *storage.ErrUnsupported{Op: <method>, Backend: "http"} so that
// errors.Is/errors.As classification and backend/conformance's
// RunUnsupportedContract hold unchanged, and it carries what the refusal
// taxonomy needs to say about the server that refused.
//
// The taxonomy (design D7) renders these fields at the standard error path
// rather than letting a Go method name escape to a user; the shape here is the
// one D8 ("The sentinel") specifies.
type ErrHTTPUnsupported struct {
// Unsup is the portable sentinel: Op is the method name, Backend is "http".
Unsup *storage.ErrUnsupported
// ServerURL is the target this store speaks to. Empty for a backstop
// refusal raised before a target was resolved (see errUnsupported).
ServerURL string
// BdVersion is the serving binary's release, from the cached
// ContextResponse; empty before the handshake has run (D6).
BdVersion string
// Capabilities are the tokens the server advertises, sorted. Nil before the
// handshake.
Capabilities []string
}
func (e *ErrHTTPUnsupported) Error() string {
// D8 pins this shape for a refusal that knows its server. A backstop
// refusal has no URL to name, so it falls back to the portable sentinel's
// own rendering rather than printing "bd serve at " with nothing after it.
if e.ServerURL == "" {
return e.Unsup.Error()
}
return fmt.Sprintf("operation %q not supported by the http backend (bd serve at %s)",
e.Unsup.Op, e.ServerURL)
}
func (e *ErrHTTPUnsupported) Unwrap() error { return e.Unsup }
// errUnsupported is the constructor every generated stub in unsupported_gen.go
// calls. Those stubs hang off the generated empty value receiver and therefore
// cannot reach a store, so they are the backstop arm: Op and Backend only.
//
// Every HAND-WRITTEN refusal in this package goes through (*Store).unsupported
// instead, which fills in the server context D7 renders. That split is the
// reason the taxonomy's user-facing texts always have a URL: whole-command and
// flag-mode refusals are raised before RunE from the store, never from a
// promoted shell stub.
func errUnsupported(op string) error {
return &ErrHTTPUnsupported{Unsup: &storage.ErrUnsupported{Op: op, Backend: Backend}}
}
// unsupported is the store-bound refusal: the same typed sentinel, enriched
// with the target and the handshake snapshot so the D7 taxonomy can name the
// server, its version and what it does advertise.
func (s *Store) unsupported(op string) error {
e := &ErrHTTPUnsupported{Unsup: &storage.ErrUnsupported{Op: op, Backend: Backend}}
if s == nil {
return e
}
e.ServerURL = s.target.String()
if snap := s.cachedSnapshot(); snap != nil {
e.BdVersion = snap.BdVersion
e.Capabilities = append([]string(nil), snap.Capabilities...)
sort.Strings(e.Capabilities)
}
return e
}
// unsupportedCapability is unsupported's sibling for a BEHAVIOR-token refusal
// rather than a whole-operation one: the operation itself is fine (countIssues
// exists on every server this client speaks to), but one caller-supplied field
// requires a behavior the handshake snapshot does not advertise.
//
// It fills in Unsup.Capability, which (*Store).unsupported never sets — that
// one is for a method this build cannot express on this backend at all, and
// has no single token to name. errors.As(err, &unsupported) reaching
// unsupported.Capability == capability is what counter.go's pre-dial scope
// refusal promises the caller (S8's CLIENT-SKEW NOTE in
// internal/httpapi/routes.go, beside CapIssuesCountScope): refuse before
// dialing, never drop the fields and answer a wider count than asked for.
func (s *Store) unsupportedCapability(op, capability string) error {
e := &ErrHTTPUnsupported{Unsup: &storage.ErrUnsupported{Op: op, Backend: Backend, Capability: capability}}
if s == nil {
return e
}
e.ServerURL = s.target.String()
if snap := s.cachedSnapshot(); snap != nil {
e.BdVersion = snap.BdVersion
e.Capabilities = append([]string(nil), snap.Capabilities...)
sort.Strings(e.Capabilities)
}
return e
}

View file

@ -0,0 +1,213 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/journal.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/journalops"
)
// The DURABLE MUTATION JOURNAL, read over GET /v0/beads/events.
//
// THERE IS NO ACCESSOR HERE, and its absence is the role's design rather than an
// omission: journalops.Journal is not on storage.DoltStorage, so a backend
// publishes the journal by IMPLEMENTING the interface a caller type-asserts for.
// `bd serve` makes exactly that assertion (cmd/bd's serveJournalCursor), which
// is why this method sits on *Store beside the raw off-role reads rather than
// behind a Journal() accessor nothing would call.
//
// THIS CLIENT HOLDS THE READ AND NOT THE OPERATOR HALF, which is the split
// journalops states and the reason the role exists apart from
// storage.EventsJournalAccessor. Retention and per-instance activation are
// decisions about a workspace's own recording, and this process has no workspace
// and no engine — it is a client of one. So *Store implements
// EventsJournalCursor and deliberately implements neither EventsJournalAccessor
// (which prunes) nor EventsJournalConfigurer (which activates), and
// cmd/bd/enterprise_events_journal_refusal_test.go pins all three facts about
// the type.
//
// WHAT THAT COSTS AT THE FRONT DOOR is worth stating rather than discovering:
// `bd events tail|export|prune` resolve their accessor through journalAccessor,
// which asks for the WIDE interface, so they still refuse on this backend. That
// is not a gap this port left open — it is the narrow interface doing its job. A
// command that only reads would need a read-only resolution path of its own.
// eventsWireLimit is the cap the HANDLER puts on one page, redeclared here
// because importing internal/httpapi would drag the storage engine into a
// client. It is maxEventsLimit in internal/httpapi/events.go.
//
// IT IS THE HANDLER'S PROMISE TO ITS CLIENTS rather than the role's: the role
// imposes no ceiling of its own, because the caller that pages a hundred
// thousand records out to a file is as legitimate as the one polling for ten.
// This client is on the other side of that promise, so an uncapped read becomes
// the loop in readPages rather than a refusal.
const eventsWireLimit = 10000
var _ journalops.Journal = (*Store)(nil)
// ReadEventsJournalPage returns the journal records after the caller's
// checkpoint, with the head of the journal's history.
//
// A LIMIT OF 0 IS UNCAPPED TO THE ROLE AND A 400 ON THE WIRE, and reconciling
// those two is the whole of what this body adds over one request. The role's
// contract is explicit that an uncapped read is legitimate; the operation
// refuses `limit=0` by value, because a page it could not bound is a page it
// could not serve. So an uncapped read becomes a LOOP over the handler's own
// maximum, advancing the checkpoint to the last seq served, until a short page
// or a checkpoint that has reached the head.
//
// THE ONE PROMISE THAT LOOP CANNOT KEEP is the one the Page type exists for: the
// rows and the head come from ONE transaction, and a loop is N of them. What
// survives is what a consumer acts on — the rows are still contiguous and
// seq-ascending, because each page continues exactly where the last ended, and
// the head is the LAST page's, which is the freshest and can only be at or ahead
// of the last row served. What does not survive is atomicity across the whole
// answer: a mutation committing mid-loop appears in a later page of the same
// call rather than in the next call. That is ledgered (L-events-paging) and it
// is strictly better than the alternatives — refusing an uncapped read the role
// permits, or silently capping one at 10000 and reporting a head that says there
// is more, which is a caller stalling on a page it was never told was partial.
//
// A BOUNDED READ IS ONE REQUEST and nothing above applies to it: limit reaches
// the wire as it was given, the page comes back with the journal's head, and a
// caller learns there is more by comparing the last seq against it.
func (s *Store) ReadEventsJournalPage(ctx context.Context, since int64, limit int) (journalops.Page, error) {
if limit > 0 {
return s.readEventsPage(ctx, since, limit)
}
return s.readEventsPages(ctx, since)
}
// readEventsPages walks the journal from since to its end, one handler-sized
// page at a time.
//
// The loop stops on a SHORT page, which is the end of the journal by the
// operation's own contract — records are contiguous, so a page smaller than the
// bound cannot be followed by another — and on a page that served nothing, which
// is the caught-up answer. It also stops at the head it was told, so a server
// that answered a full page of rows it had already served cannot spin this
// forever.
func (s *Store) readEventsPages(ctx context.Context, since int64) (journalops.Page, error) {
page := journalops.Page{}
cursor := since
for {
next, err := s.readEventsPage(ctx, cursor, eventsWireLimit)
if err != nil {
// A TRUNCATION ON ANY PAGE IS THE WHOLE READ'S, never a shorter
// answer. The contract's bounded arm asserts the identical window
// from a capped read and an uncapped one, and a loop that returned
// the prefix it had already gathered would answer a gap with a
// plausible-looking suffix — the one failure a replay feed must
// never ship.
return journalops.Page{}, err
}
page.Head = next.Head
page.Rows = append(page.Rows, next.Rows...)
if len(next.Rows) < eventsWireLimit {
return page, nil
}
last := next.Rows[len(next.Rows)-1].Seq
if last <= cursor || last >= next.Head {
// The first arm is a server that did not advance; the second is a
// caller that has reached the history it was told about. Neither is
// a reason to ask again.
return page, nil
}
cursor = last
}
}
// readEventsPage is ONE request.
func (s *Store) readEventsPage(ctx context.Context, since int64, limit int) (journalops.Page, error) {
q := url.Values{}
// FormatInt rather than Itoa: `since` is an int64 and the conformance
// suite's own head probe reads with math.MaxInt64, which a 32-bit int
// conversion would silently wrap.
q.Set("since", strconv.FormatInt(since, 10))
if limit > 0 {
q.Set("limit", strconv.Itoa(limit))
}
var body apigen.EventsPage
if err := s.dispatch(ctx, wire.Request{
Op: wire.OpListEvents,
Method: http.MethodGet,
Path: wire.PathEvents,
Query: q,
}, &body); err != nil {
return journalops.Page{}, eventsJournalError(err)
}
rows := make([]journalops.Row, 0, len(body.Records))
for _, record := range body.Records {
rows = append(rows, journalRow(record))
}
return journalops.Page{Rows: rows, Head: body.Head}, nil
}
// eventsJournalError rebuilds the role's TYPED truncation from the problem
// document that carried it.
//
// It is the one place on this seam where a refusal has to become a Go value
// carrying DATA rather than a sentinel, and the contract checks it by
// errors.As against journalops.TruncatedError — a type no leg names, since
// storage.EventsJournalTruncatedError is an alias of it. A client that returned
// the wire's sentinel alone would satisfy errors.Is and fail every consumer,
// because the recovery is a decision made from the WINDOW: resume from Floor-1
// and accept the gap, or rebuild.
//
// ALL THREE MEMBERS TRAVEL TOGETHER and none is omitted to mean zero — a head of
// 0 is a real journal state — so a document missing any of them is a server this
// client cannot reconstruct a window from, and the wire's own error travels
// unchanged rather than a window with a fabricated bound in it.
//
// `since` IS NOT ECHOED BACK. On an interior hole the server reports the last
// seq it could serve CONTIGUOUSLY from the caller's checkpoint, which is
// strictly more useful and cannot be recovered by a client that assumed it was
// getting its own input back — so this reads the member rather than the request.
func eventsJournalError(err error) error {
if !errors.Is(err, wire.ErrEventsJournalTruncated) {
return err
}
var prob *wire.ProblemError
if !errors.As(err, &prob) || prob.Since == nil || prob.Floor == nil || prob.Head == nil {
return err
}
return &journalops.TruncatedError{Since: *prob.Since, Floor: *prob.Floor, Head: *prob.Head}
}
// journalRow projects one published record back onto the storage row the role
// answers with.
//
// It is the exact inverse of eventsjournal.NewRecord, and the payload members
// are the part worth reading twice. `issue` is ALWAYS present and carries the
// literal `null` on a delete — a consumer must be able to tell a delete from a
// payload the server failed to record — while `dep` and `comment` are ABSENT on
// the ops that have no such half. All three collapse to the empty string on the
// row, which is the row's own conflation and not one this client introduces:
// journalops.Row documents IssueJSON as empty when the op is a delete.
//
// The payloads travel as RAW BYTES in both directions. Re-encoding them would
// reorder members and renormalize numbers against a contract that promises the
// issue exactly as the mutation left it.
func journalRow(record apigen.EventRecord) journalops.Row {
row := journalops.Row{
Seq: record.Seq,
TS: record.TS,
Op: record.Op,
IssueID: record.IssueID,
}
if payload := string(record.Issue); payload != "" && payload != "null" {
row.IssueJSON = payload
}
row.DepJSON = string(record.Dep)
row.CommentJSON = string(record.Comment)
return row
}

View file

@ -0,0 +1,917 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/lifecycle.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"reflect"
"slices"
"time"
"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/types"
"github.com/steveyegge/beads/issueops"
)
// httpLifecycle serves issueops.Lifecycle WHOLE (design D8 row 16): Create over
// POST createIssue, Update over PATCH updateIssue, and Close and Reopen over
// their custom methods.
//
// It was PARTIAL until the create landed: POST /v0/beads/issues was deliberately
// left free on the wire when issues:batchCreate chose a custom method, and
// upstream #5483 filled it with the single create this role now dials.
type httpLifecycle struct {
store *Store
wire WriteWire
}
var _ issueops.Lifecycle = (*httpLifecycle)(nil)
// Create dials POST /v0/beads/issues.
//
// The whole request maps but for two members, and both refuse rather than
// dropping: IDPrefix where it would act on an explicit, unforced id, which the
// server publishes no member for on purpose (W-CreateRequest.IDPrefix), and
// every member of the issue outside the wire's twenty (W-CreateRequest.Issue)
// — save a CreatedBy that names the actor, which the server stamps from the
// actor itself. A create that reported success having silently dropped the
// storage class, the molecule type or the creation time is a row the caller
// believes they wrote and did not.
//
// The RESPONSE is the row as stored — the minted id, the defaulted status, the
// persisted timestamps — so nothing here echoes the request back.
func (l *httpLifecycle) Create(ctx context.Context, req issueops.CreateRequest) (result issueops.CreateResult, err error) {
// Write-side parity with reads: decorates a bare *encode.RefusedError —
// however deeply createBody/refuseUnwirableCreateIssue/createEdge nested it
// inside an "Issue.%s:"/"dependencies[%d]:" prefix — into
// *InexpressibleError so errors.As(err, &unsupported) reaches
// *storage.ErrUnsupported, same as inexpressible does for a read role. The
// original composite message (including that prefix) is preserved in the
// decorated error's own text.
defer func() { err = l.store.inexpressible("Lifecycle.Create", err) }()
if err := requireActor(req.Actor); err != nil {
return issueops.CreateResult{}, err
}
body, err := createBody(req)
if err != nil {
return issueops.CreateResult{}, err
}
issue, err := l.wire.CreateIssue(ctx, body)
if err != nil {
// The wire's already_exists carries `param: "id"` and no id, because the
// request already said it — the same argument the problem mapper's
// target makes for the conflicts it rebuilds. Putting the caller's own
// id back is what lets `bd create --id X` say WHICH id is taken, the way
// a local backend's refusal does. Nothing else about the refusal is
// recomposed: the sentinel and the server's detail are its own.
if req.Issue != nil && req.Issue.ID != "" && errors.Is(err, issueops.ErrAlreadyExists) {
return issueops.CreateResult{}, fmt.Errorf("%s: %w", req.Issue.ID, err)
}
return issueops.CreateResult{}, err
}
return issueops.CreateResult{Issue: issue}, nil
}
// createBody projects the role's request onto the wire's flat create body.
//
// FLAT is the shape that makes this operation different from every other write
// here: the issue's own members are top-level members of the request rather than
// a nested document, so this function is the only place the two vocabularies
// meet and the allowlist below is the whole of it.
func createBody(req issueops.CreateRequest) (apigen.CreateIssueRequest, error) {
if req.Issue == nil {
return apigen.CreateIssueRequest{}, invalid("a create names no issue")
}
if len(req.Issue.Comments) > 0 || len(req.Issue.Dependencies) > 0 {
// The ROLE's own rule, not a wire divergence: edges are supplied through
// the request's own Dependencies, where their direction can be stated,
// and a create has no way to supply comments at all. A local backend
// refuses this too.
return apigen.CreateIssueRequest{}, invalid(
"Issue carries comments or dependencies; supply edges through the request's own Dependencies")
}
if req.IDPrefix != "" && req.Issue.ID != "" && !req.ForceIDPrefix {
// Refused only where the override would ACT. The role reads it for one
// thing — checking an explicit id it was not told to force — so a create
// that mints its id, or forces one, asks the server for nothing it cannot
// do. `bd create` sends the workspace's prefix on every create, and an
// unconditional refusal would refuse every create in a workspace whose
// config.yaml names one.
return apigen.CreateIssueRequest{}, refuse(encode.OpCreateIssue, "W-CreateRequest.IDPrefix")
}
if err := refuseUnwirableIssueMembers(req.Issue, req.Actor, encode.OpCreateIssue, "W-CreateRequest.Issue"); err != nil {
return apigen.CreateIssueRequest{}, err
}
issue := req.Issue
// Priority is sent ALWAYS, for batchCreateIssues' reason: 0 is P0 and a real
// request, so an absent member — which the server reads as the workspace
// default — would silently reprioritize every critical issue a plan creates.
priority := issue.Priority
body := apigen.CreateIssueRequest{Actor: req.Actor, Title: issue.Title, Priority: &priority}
setItemString(&body.Id, issue.ID)
setItemString(&body.Description, issue.Description)
setItemString(&body.Design, issue.Design)
setItemString(&body.AcceptanceCriteria, issue.AcceptanceCriteria)
setItemString(&body.Notes, issue.Notes)
setItemString(&body.Status, string(issue.Status))
setItemString(&body.IssueType, string(issue.IssueType))
setItemString(&body.Assignee, issue.Assignee)
setItemString(&body.Owner, issue.Owner)
setItemString(&body.Sender, issue.Sender)
setItemString(&body.ParentId, req.ParentID)
if issue.ExternalRef != nil {
// Sent THROUGH the pointer rather than through setItemString: this is
// the one text member the role models as nullable, so a set-but-empty
// ref stores the empty string where an absent one stores NULL, and
// collapsing the two would drop a state the caller can observe.
ref := *issue.ExternalRef
body.ExternalRef = &ref
}
if issue.EstimatedMinutes != nil {
minutes := *issue.EstimatedMinutes
body.EstimatedMinutes = &minutes
}
body.DueAt = copyTime(issue.DueAt)
body.DeferUntil = copyTime(issue.DeferUntil)
if len(issue.Labels) > 0 {
labels := append([]string(nil), issue.Labels...)
body.Labels = &labels
}
if len(issue.Metadata) > 0 {
// The blob travels as the bytes the caller sent, applyDepAddItem's rule:
// the role is the single definition of what the metadata plane accepts,
// and a second parse here would be a second definition.
//
// WELL-FORMEDNESS is a different question from acceptance, and it is
// this layer's: bytes that are not JSON at all cannot go on a JSON wire,
// and letting them through would surface as a marshal fault at the
// transport where the role promises ErrValidation.
if err := requireJSON("Issue.Metadata", issue.Metadata); err != nil {
return apigen.CreateIssueRequest{}, err
}
body.Metadata = append(apigen.MetadataValue(nil), issue.Metadata...)
}
// The four booleans are sent only when TRUE. Each selects something — a
// plane, an inheritance, a bypass — so an explicit false is the default said
// twice, and `ephemeral` and `no_history` are mutually exclusive on the
// wire, which a pair of explicit falses would not trip but a pair of
// explicit trues would.
setItemBool(&body.Ephemeral, issue.Ephemeral)
setItemBool(&body.NoHistory, issue.NoHistory)
setItemBool(&body.InheritLabelsFromParent, req.InheritLabelsFromParent)
setItemBool(&body.ForceIdPrefix, req.ForceIDPrefix)
if len(req.Dependencies) > 0 {
edges := make([]apigen.CreateIssueDependency, 0, len(req.Dependencies))
for i, dep := range req.Dependencies {
edge, err := createEdge(i, dep)
if err != nil {
return apigen.CreateIssueRequest{}, err
}
edges = append(edges, edge)
}
body.Dependencies = &edges
}
if req.WaitsFor != nil {
gate := apigen.CreateIssueWaitsFor{SpawnerId: req.WaitsFor.SpawnerID}
setItemString(&gate.Gate, req.WaitsFor.Gate)
body.WaitsFor = &gate
}
return body, nil
}
// createEdge projects one requested edge onto createIssue's own edge, which
// carries `reverse` and `metadata` where batchCreateIssues' does not — a create
// has an id for a target to point back at, and a batch item has none.
func createEdge(index int, dep issueops.CreateDependency) (apigen.CreateIssueDependency, error) {
where := func(err error) error { return fmt.Errorf("dependencies[%d]: %w", index, err) }
switch {
case dep.TargetID == "":
return apigen.CreateIssueDependency{}, where(invalid("target_id is required"))
case dep.Type == "":
return apigen.CreateIssueDependency{}, where(invalid("type is required"))
case dep.ThreadID != "":
return apigen.CreateIssueDependency{}, where(refuse(encode.OpCreateIssue, "W-CreateDependency.ThreadID"))
}
edge := apigen.CreateIssueDependency{TargetId: dep.TargetID, Type: string(dep.Type)}
setItemBool(&edge.Reverse, dep.Reverse)
if dep.Metadata != "" {
if err := requireJSON("metadata", []byte(dep.Metadata)); err != nil {
return apigen.CreateIssueDependency{}, where(err)
}
edge.Metadata = apigen.MetadataValue(dep.Metadata)
}
return edge, nil
}
// requireJSON refuses a raw blob that is not JSON, before it can become a
// request body.
//
// It is NOT a judgment about the metadata plane's vocabulary — that belongs to
// the role, which is why the blob travels verbatim — only about whether these
// bytes can be sent at all. Without it a malformed blob fails inside
// json.Marshal and reaches the caller as a transport fault, where every role
// contract promises a deterministic validation failure.
func requireJSON(member string, raw []byte) error {
if !json.Valid(raw) {
return invalid("%s is not valid JSON", member)
}
return nil
}
// createCarriedIssueMembers is the wire's create vocabulary: the twenty members
// of apigen.CreateIssueRequest that describe the issue itself, keyed by the
// types.Issue field each one carries.
//
// It is the ALLOWLIST half of refuse-not-drop for this operation. What it does
// not name is refused, and there is no third arm — see refuseUnwirableIssueMembers.
var createCarriedIssueMembers = map[string]string{
"ID": "id",
"Title": "title",
"Description": "description",
"Design": "design",
"AcceptanceCriteria": "acceptance_criteria",
"Notes": "notes",
"Status": "status",
"Priority": "priority",
"IssueType": "issue_type",
"Assignee": "assignee",
"Owner": "owner",
"EstimatedMinutes": "estimated_minutes",
"ExternalRef": "external_ref",
"DueAt": "due_at",
"DeferUntil": "defer_until",
"Sender": "sender",
"Metadata": "metadata",
"Labels": "labels",
"Ephemeral": "ephemeral",
"NoHistory": "no_history",
}
// setItemBool writes an optional wire boolean, leaving it absent when the caller
// asked for nothing. The pointer addresses a local copy, never the caller's field.
func setItemBool(dest **bool, value bool) {
if !value {
return
}
v := value
*dest = &v
}
// copyTime detaches an optional timestamp from the caller's request, so nothing
// downstream can be surprised by a value the caller still holds a pointer to.
func copyTime(value *time.Time) *time.Time {
if value == nil {
return nil
}
v := *value
return &v
}
// Update dials PATCH updateIssue.
//
// Everything hard about it is the PATCH shape, and it is hard for one reason:
// on this operation PRESENCE is the signal and an explicit null is the CLEAR, so
// "omitted" and "set to nothing" are different requests. issueops.Field carries
// that distinction; apigen.IssuePatchBody cannot — its members are pointers with
// `omitempty`, which collapses a nil clear into an absent member — so the body
// is built as an ordered document here and the wire marshals it verbatim.
//
// Refuse-not-drop governs every member the wire's issuePatchMembers list
// excludes, and every UpdateRequest member with no wire counterpart. A dropped
// patch member is an edit the caller believes landed; a dropped precondition is
// a conditional write turned unconditional. Both are the failure class the
// divergence ledger exists to make impossible.
//
// A CLAIM rides the same request (upstream #6890): `claim` is a top-level
// member beside the patch, so a claim alone, a claim with a patch and a claim
// with a version guard are each ONE updateIssue call, claimed and patched in
// one transaction by the same role the direct route runs, and answered with the
// post-write `revision` like every other update. The one claim that goes
// anywhere else is a claim ALONE to a server that predates the member — see
// serverPredatesUpdateClaim.
func (l *httpLifecycle) Update(ctx context.Context, req issueops.UpdateRequest) (result issueops.UpdateResult, err error) {
// Write-side parity with reads: decorates a bare *encode.RefusedError —
// however deeply refuseUnwirableUpdateMembers/encodeIssuePatch/
// refuseExcludedPatchMembers nested it, and transitively covering
// claimOnlyUpdate's own refusals since every one of its returns flows back
// through this method's single call site — into *InexpressibleError so
// errors.As(err, &unsupported) reaches *storage.ErrUnsupported, same as
// inexpressible does for a read role.
defer func() { err = l.store.inexpressible("Lifecycle.Update", err) }()
if err := requireActor(req.Actor); err != nil {
return issueops.UpdateResult{}, err
}
if err := requireID("issue id", req.IssueID); err != nil {
return issueops.UpdateResult{}, err
}
if err := refuseUnwirableUpdateMembers(req); err != nil {
return issueops.UpdateResult{}, err
}
patch, err := encodeIssuePatch(req.Patch)
if err != nil {
return issueops.UpdateResult{}, err
}
if len(patch) == 0 && !req.Claim {
// The server answers a 400 for an empty patch — except beside `claim`,
// where the claim is the write — and so does the local role's own
// validation. Saying it here keeps a write that writes nothing off the
// wire entirely.
return issueops.UpdateResult{}, invalid("update names no field to write")
}
res, err := l.wire.UpdateIssue(ctx, req.IssueID, req.Actor, patch, updateGuards(req), updateFlags(req))
if err != nil {
if req.Claim && isClaimOnlyUpdate(req) && serverPredatesUpdateClaim(err) {
return l.claimOnlyUpdate(ctx, req)
}
return issueops.UpdateResult{}, err
}
// The stitch releaser.go documents: types.Issue.RowVersion is `json:"-"`, so
// the decoded row carries no token and updateIssue publishes the post-write
// revision as a sibling member. Riding it back onto Issue.RowVersion is what
// lets a guarded read-modify-write compose its next ExpectedVersion from the
// result rather than paying a Get to re-read a token the write already answered.
issue := res.Issue
if issue.RowVersion, err = parseRevision("updateIssue", res.Revision); err != nil {
return issueops.UpdateResult{}, err
}
return issueops.UpdateResult{Issue: &issue, Changed: res.Changed}, nil
}
// updateGuards carries the request's three compare-and-set preconditions onto
// the wire.
//
// EVERY ONE IS A POINTER ON BOTH SIDES AND THE COPY IS A NIL CHECK, which is the
// whole implementation and is the point: a zero value is a REQUEST on all three
// — `expected_version` 0 is a token the migration-0054 backfill really wrote,
// and an empty `expected_assignee` is the guard that says "only if nobody holds
// it" — so absent has to stay absent. No sentinel is encoded here, in either
// direction.
//
// The pointers address LOCAL copies, so nothing downstream can be surprised by
// a value the caller still holds.
func updateGuards(req issueops.UpdateRequest) wire.UpdateGuards {
var guards wire.UpdateGuards
guards.ExpectedVersion = revisionGuard(req.ExpectedVersion)
if req.ExpectedStatus != nil {
status := string(*req.ExpectedStatus)
guards.ExpectedStatus = &status
}
if req.ExpectedAssignee != nil {
assignee := *req.ExpectedAssignee
guards.ExpectedAssignee = &assignee
}
return guards
}
// updateFlags carries the claim and the three force overrides onto the wire.
// The wire sends each only when true, so a request that sets none of them is
// byte-identical to one built before any of them was carried.
func updateFlags(req issueops.UpdateRequest) wire.UpdateFlags {
return wire.UpdateFlags{
Claim: req.Claim,
ForceAssigneeTransfer: req.ForceAssigneeTransfer,
ForceClosePolicy: req.ForceClosePolicy,
ForceNotesOverwrite: req.ForceNotesOverwrite,
}
}
// serverPredatesUpdateClaim reports whether err is a server that predates
// `claim` on updateIssue (upstream #6890) refusing the member: the version-skew
// 400 — `unknown_parameter`, naming `claim` itself. Such a server checks body
// members before it reads anything else, so the refusal arrives before any
// database work and nothing the request asked for was written.
//
// It is the SKEW signal, not the capability list, because no capability token
// announces the member — it is additive, so it bumped no wire revision either —
// and the reason is what dispatches, never the code alone: `invalid_value`
// naming `claim` is a current server refusing a claim beside a member it may
// not ride with, which is the caller's error to see, not a server to route
// around.
func serverPredatesUpdateClaim(err error) bool {
var problem *wire.ProblemError
return errors.As(err, &problem) &&
problem.Reason == encode.UnknownParameterReason &&
problem.Param == "claim"
}
// Close dials POST issues/{id}:close.
func (l *httpLifecycle) Close(ctx context.Context, req issueops.CloseRequest) (issueops.CloseResult, error) {
if err := requireActor(req.Actor); err != nil {
return issueops.CloseResult{}, err
}
if err := requireID("issue id", req.IssueID); err != nil {
return issueops.CloseResult{}, err
}
body := closeBody(req.Actor, req.Reason, req.Session, req.Force)
body.ExpectedVersion = revisionGuard(req.ExpectedVersion)
res, err := l.wire.CloseIssue(ctx, req.IssueID, body)
if err != nil {
return issueops.CloseResult{}, err
}
// The stitch releaser.go documents; an idempotent re-close carries the current
// token too, so a close-then-reopen chain composes its next ExpectedVersion here.
issue := res.Issue
if issue.RowVersion, err = parseRevision("closeIssue", res.Revision); err != nil {
return issueops.CloseResult{}, err
}
return issueops.CloseResult{
Issue: &issue,
Changed: !res.AlreadyClosed,
OpenChildren: res.OpenChildren,
}, nil
}
// Reopen dials POST issues/{id}:reopen.
func (l *httpLifecycle) Reopen(ctx context.Context, req issueops.ReopenRequest) (result issueops.ReopenResult, err error) {
// 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.
defer func() { err = l.store.inexpressible("Lifecycle.Reopen", err) }()
if err := requireActor(req.Actor); err != nil {
return issueops.ReopenResult{}, err
}
if err := requireID("issue id", req.IssueID); err != nil {
return issueops.ReopenResult{}, err
}
if req.Provenance != "" {
return issueops.ReopenResult{}, refuse(encode.OpReopenIssue, "W-ReopenRequest.Provenance")
}
body := apigen.ReopenIssueRequest{Actor: req.Actor, ExpectedVersion: revisionGuard(req.ExpectedVersion)}
if req.Reason != "" {
body.Reason = &req.Reason
}
res, err := l.wire.ReopenIssue(ctx, req.IssueID, body)
if err != nil {
return issueops.ReopenResult{}, err
}
// The stitch releaser.go documents; a recovery flow that reopens and then
// re-closes composes its next ExpectedVersion from this token.
issue := res.Issue
if issue.RowVersion, err = parseRevision("reopenIssue", res.Revision); err != nil {
return issueops.ReopenResult{}, err
}
return issueops.ReopenResult{Issue: &issue, Changed: !res.AlreadyOpen}, nil
}
// revisionGuard spells a row-version precondition for the wire.
//
// The Go contract holds the token as an int64 (types.Issue.RowVersion, the
// request's ExpectedVersion) and the wire carries it as a decimal STRING
// (upstream #6053: the token spans the full 64-bit range and a JSON number
// would be rounded past 2^53 by any IEEE-754-double consumer, so the server
// refuses a bare number on `expected_version` with a 400). types.RevisionToken
// is the one spelling of that encoding and this is the one place the client
// applies it on the way out.
//
// NIL STAYS NIL and 0 becomes "0": the token is opaque and compared for
// equality alone, and 0 is one a row really holds — the migration-0054 backfill
// wrote it — so an absent guard and a guard on zero are different requests.
// Every verb that publishes the member goes through here, so there is one place
// the rule can be read and one place it could be broken.
func revisionGuard(version *int64) *string {
if version == nil {
return nil
}
token := types.RevisionToken(*version)
return &token
}
// parseRevision reads the `revision` a write answered with back to the int64
// the Go contract carries, revisionGuard's inverse.
//
// The member is required on every response that publishes it, and the server
// spells it with types.RevisionToken, so ParseRevisionToken accepts exactly what
// a conforming server emits. A token it cannot read is a server this client
// cannot follow, reported the way the package reports every other malformed
// answer (a batch-apply result of the wrong arity, a count with no `groups`):
// as a plain error naming bd serve, the operation and the member, rather than
// stitching 0 onto the row — 0 is a real token and the corruption would only
// surface as a precondition_failed on the NEXT request.
func parseRevision(op, token string) (int64, error) {
version, err := types.ParseRevisionToken(token)
if err != nil {
return 0, fmt.Errorf("%s: bd serve answered a `revision` this client cannot read as a token (%q): %w", op, token, err)
}
return version, nil
}
// closeBody builds the close request. The three optional members are pointers on
// the wire, and an omitted one is not the same as an empty one: the server
// distinguishes "no reason supplied" from an explicit null, which it refuses.
func closeBody(actor, reason, session string, force bool) apigen.CloseIssueRequest {
body := apigen.CloseIssueRequest{Actor: actor}
if reason != "" {
body.Reason = &reason
}
if session != "" {
body.Session = &session
}
if force {
body.Force = &force
}
return body
}
// claimOnlyUpdate is the claim a server that predates `claim` on updateIssue
// can still serve: a claim and nothing else, dialed as claimIssue through the
// Claimer role. Update reaches it only after such a server refused the member
// as unknown (serverPredatesUpdateClaim) and only for a claim-only request
// (isClaimOnlyUpdate) — claimIssue's own request is `{actor}` alone (see
// apigen.ClaimRequest), so a claim-only UpdateRequest IS that request, and
// anything beside the claim would be dropped by it. A claim combined with a
// patch, a guard or a force override is therefore NOT retried here: the skew
// refusal is returned as it came, rather than synthesized as two calls
// (claimIssue then updateIssue), which would let a caller observe an issue
// claimed but not yet patched.
//
// That keeps `bd update <id> --claim --json` — gc's exclusive claim path —
// working against an older bd serve. The two roles' result shapes line up
// member for member (Issue, Changed): same-actor re-claim is the idempotent
// Changed=false Claimer already promises, and a foreign holder or an
// ineligible status is the same *issueops.ClaimConflictError updateIssue's
// claim raises.
//
// What this route cannot match, it says. claimIssue answers the bare row
// (issueops/claimer.go's ClaimResult doc, pinned against the Claimer role
// directly by TestServedClaimerClaimsAnUnassignedOpenIssueAndAnswersTheBareRow),
// where updateIssue answers the hydrated one, so the LABELS and CreatedBy are
// read back below for CommandUpdateMutation's shared `bd update --json`
// renderer — the hydration is composed HERE rather than by widening Claimer's
// promise, which backend/conformance's ClaimerFixture suite holds every backend
// to. claimIssue also carries no `revision`, so the result's RowVersion stays
// unset rather than borrowing the follow-up read's token: that read is a second
// snapshot, and a token from it could postdate a write this claim never saw,
// arming a guard that should have missed. And claimIssue excludes the wisp
// plane, so a wisp id refuses by name (W-ClaimRequest.Wisp).
func (l *httpLifecycle) claimOnlyUpdate(ctx context.Context, req issueops.UpdateRequest) (issueops.UpdateResult, error) {
claimer, err := l.store.IssueClaimer()
if err != nil {
return issueops.UpdateResult{}, err
}
res, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: req.Actor, IssueID: req.IssueID})
if err != nil {
// claimIssue excludes wisps (issueops.Claimer's own contract), where the
// direct route's `bd update <id> --claim` claims one through Lifecycle's
// general issue-or-wisp routing. A wisp id therefore reaches THIS branch
// as the wire's generic not-found — "no issue or wisp with that id" —
// indistinguishable from an id that names nothing at all. The probe
// below runs ONLY here, on a not-found answer, rather than ahead of
// every claim attempt, so an ordinary claim of a real, non-wisp issue
// costs no probe. A refusal for any other reason (already claimed, not
// eligible from its current status, actor/id validation) needs no probe
// and returns unchanged.
if errors.Is(err, issueops.ErrNotFound) {
if issue, probeErr := l.store.GetIssue(ctx, req.IssueID); probeErr == nil && issue != nil && isWispIssue(issue) {
return issueops.UpdateResult{}, refuse(encode.OpUpdateIssue, "W-ClaimRequest.Wisp")
}
// Not a wisp — either the probe also found nothing (the id truly
// names no row), or the probe itself failed. Either way, the
// original not-found error from claimIssue is the right thing to
// return, unmodified: it is what lets a not-found-sensitive caller
// (gc's Claim among them) recognize a missing id over http exactly
// as it recognizes one against a local workspace.
}
return issueops.UpdateResult{}, err
}
issue := res.Issue
// Best-effort hydration for output parity with the direct route (see the
// doc above): the claim itself already committed, so a failed follow-up
// read is not this call's failure to report — fall back to the bare row
// issueops.Claimer promised rather than failing an otherwise-successful
// claim. Labels and CreatedBy ONLY: the read's RowVersion is another
// snapshot's, and the doc above is why it must not ride onto this row. A
// guard composed from the unset token fails closed (ErrVersionMismatch: the
// caller re-reads), where a borrowed one could pass over a write this claim
// never saw. Against a current server the claim rides updateIssue instead,
// whose `revision` Update stitches as it does for any patch, so the real
// token is missing only on this pre-#6890 fallback.
if issue != nil {
if hydrated, hydrateErr := l.store.GetIssue(ctx, req.IssueID); hydrateErr == nil && hydrated != nil {
withLabels := *issue
withLabels.Labels = hydrated.Labels
withLabels.CreatedBy = hydrated.CreatedBy
issue = &withLabels
}
}
return issueops.UpdateResult{Issue: issue, Changed: res.Changed}, nil
}
// isClaimOnlyUpdate reports whether req carries nothing but the claim itself
// (and the Actor/IssueID pair every UpdateRequest needs) — whether claimIssue,
// whose wire request is the actor alone, can carry ALL of it. Any other
// UpdateRequest member holding a non-zero value — a Patch field, a guard, a
// force override, a provenance label — is one claimIssue has no place for, so
// claimOnlyUpdate's fallback would drop it.
//
// reflect.DeepEqual against the zero IssuePatch, rather than a hand-enumerated
// field list, is deliberate: a future IssuePatch member defaults to unset, so
// it is caught by this check without this function needing to learn its name.
func isClaimOnlyUpdate(req issueops.UpdateRequest) bool {
return reflect.DeepEqual(req.Patch, issueops.IssuePatch{}) &&
!req.ForceAssigneeTransfer &&
!req.ForceClosePolicy &&
!req.ForceNotesOverwrite &&
!req.IssuePlaneOnly &&
req.Provenance == "" &&
req.ExpectedVersion == nil &&
req.ExpectedAssignee == nil &&
req.ExpectedStatus == nil
}
// isWispIssue reports whether issue lives on the wisp plane, mirroring
// internal/storage/issueops.IsWisp's flags-not-id-pattern rule (unexported
// there, and this package does not import it): a row is a wisp because it is
// Ephemeral or NoHistory, never because of what its id looks like. It does
// not read WispPlaneOverride, which only matters mid-import — a row this
// client just fetched off a live server is never an in-flight import record.
func isWispIssue(issue *types.Issue) bool {
return issue.Ephemeral || issue.NoHistory
}
// refuseUnwirableUpdateMembers walks the UpdateRequest members the wire's
// updateIssue body has no place for.
//
// The claim and the three force overrides are NOT on this switch: updateIssue
// publishes all four (internal/httpapi/apigen's UpdateIssueRequest), the
// server reads them (internal/httpapi/update.go), and Update sends them beside
// the patch as wire.UpdateFlags. Their W-UpdateRequest rows are RETIRED.
//
// The order is the ledger's, and each refusal cites its row rather than a
// sentence, so the taxonomy renders the same reason the design recorded.
func refuseUnwirableUpdateMembers(req issueops.UpdateRequest) error {
switch {
case req.IssuePlaneOnly:
return refuse(encode.OpUpdateIssue, "W-UpdateRequest.IssuePlaneOnly")
case req.Provenance != "":
return refuse(encode.OpUpdateIssue, "W-UpdateRequest.Provenance")
}
return nil
}
// encodeIssuePatch turns the role's patch into the wire's patch document.
//
// A member that is Set becomes a member of the document; a member that is not
// stays out of it. The four NULLABLE members are the reason the document is a
// map of any rather than a struct: their Field values wrap a POINTER, and a set
// nil pointer has to reach the server as a literal null — the clear — where an
// unset one has to be absent entirely.
//
// Every member the wire excludes refuses here rather than being skipped. Reading
// this function as the wire's allowlist is the point: what it does not write, it
// refuses, and there is no third arm.
func encodeIssuePatch(patch issueops.IssuePatch) (map[string]any, error) {
// REFUSE FIRST, then encode. The excluded members are decided before any
// member is written, so a patch that both names one and carries a malformed
// metadata blob reports the refusal — the fact about the WIRE — rather than
// whichever error the encoder happened to reach first.
if err := refuseExcludedPatchMembers(patch); err != nil {
return nil, err
}
out := map[string]any{}
setString(out, "title", patch.Title)
setString(out, "description", patch.Description)
setString(out, "design", patch.Design)
setString(out, "acceptance_criteria", patch.AcceptanceCriteria)
setString(out, "notes", patch.Notes)
setString(out, "append_notes", patch.AppendNotes)
if patch.Priority.Set {
out["priority"] = patch.Priority.Value
}
if patch.IssueType.Set {
out["issue_type"] = string(patch.IssueType.Value)
}
// The four members upstream #5484 added.
//
// PRESENCE ALONE DECIDES all three of the strings, and on two of them the
// EMPTY STRING is a request rather than an absence: an empty `assignee`
// unassigns, and an empty `parent_id` removes every parent-child edge. A
// builder that skipped a member because its value was empty would turn both
// into no edit at all — silently, since the server answers `changed: false`
// and the caller reads a 200.
//
// `status` is not a second spelling of close and reopen. Those two carry
// semantics a status write has nowhere to put — the reason and session under
// first-close-wins, the done-status normalization, the already-closed
// idempotence flag — and stay the operations to reach for. This member is
// the status moved ALONGSIDE other fields in one transaction, which is the
// thing two calls cannot do. It answers to close policy either way: a
// crossing into the done category earns the server's own not_closable.
if patch.Status.Set {
out["status"] = string(patch.Status.Value)
}
setString(out, "assignee", patch.Assignee)
setString(out, "parent_id", patch.ParentID)
if metadataPatched(patch.Metadata) {
document, err := encodeMetadataPatch(patch.Metadata)
if err != nil {
return nil, err
}
out["metadata"] = document
}
// The nullable four. A set member always lands, and lands as null when its
// pointer is nil, because that is the clear.
setNullable(out, "estimated_minutes", patch.EstimatedMinutes)
setNullable(out, "external_ref", patch.ExternalRef)
setNullableTime(out, "due_at", patch.DueAt)
setNullableTime(out, "defer_until", patch.DeferUntil)
// THE ORDERED LABEL EDIT, whole. The wire spells it as three FLAT members
// where applyBatch nests them under one object, and the difference is
// historical rather than meaningful: `labels` shipped as a bare array, and
// nesting it now would re-type a published member. What both spell is the
// role's own algebra — replace, then add, then remove, so REMOVAL WINS where
// a label appears in more than one — and the server assembles all three into
// ONE issueops.LabelPatch, so the order is never this client's to arrange.
//
// AN INCREMENTAL EDIT USED TO REFUSE HERE (W-IssuePatch.Labels), and it is
// worth saying what the refusal was protecting: a client that degraded an add
// to the replace-only member would have to read the set, add to it and write
// it back, which silently drops any label another writer added in between —
// and `bd label add` and every agent that tags work concurrently are exactly
// that caller. The members retire the refusal rather than the argument.
if patch.Labels.Replace.Set {
labels := patch.Labels.Replace.Value
if labels == nil {
// An empty array clears the set; a JSON null on this member is not
// a clear and the server refuses it.
labels = []string{}
}
out["labels"] = labels
}
// EMITTED ONLY WHEN NON-EMPTY, which is not a drop: Add and Remove are bare
// slices on the role, so nil and empty are one value there — an Add carrying
// nothing changes nothing and reports Changed false — and sending an empty
// array would put a member on the wire that says nothing while turning a
// patch that edits nothing into one the server has to refuse for a different
// reason. It is encodeApplyLabelPatch's rule, on the flat spelling.
if len(patch.Labels.Add) > 0 {
out["add_labels"] = append([]string(nil), patch.Labels.Add...)
}
if len(patch.Labels.Remove) > 0 {
out["remove_labels"] = append([]string(nil), patch.Labels.Remove...)
}
return out, nil
}
// encodeMetadataPatch turns the role's metadata edit into the wire's own
// metadata document.
//
// It is a PROJECTION rather than a translation: apigen.ApplyMetadataPatch
// publishes replace, merge, set and unset, the role's MetadataPatch carries
// exactly those four, and the algebra over them — merge, then set in key order,
// then unset, with replace replacing the whole document and refusing beside the
// other three — is the ROLE's and is applied server-side by the same body a
// local workspace runs. Nothing here re-decides any of it, which is why the
// replace-plus-incremental contradiction is sent rather than pre-empted: both
// sides refuse it as a validation failure and writing nothing.
//
// It is a map for its parent's reason. apigen.ApplyMetadataPatch spells every
// member `omitempty`, and on THIS document that collapses the one state the
// role can express and the struct cannot: a set Replace holding no bytes is the
// CLEAR, and an omitted `replace` is no replacement at all.
//
// The two things it does decide, both because the alternative is not
// expressible on a JSON wire:
//
// - a clear travels as `{}`. An empty json.RawMessage is not a JSON value —
// json.Marshal fails on one — and `{}` is the document the role's own
// ApplyMetadataPatch substitutes for it before it writes, so this is the
// role's answer rather than a choice made here.
// - a blob that is not JSON refuses as ErrValidation, the way the create's
// does, rather than failing inside the marshaler as a transport fault.
func encodeMetadataPatch(patch issueops.MetadataPatch) (map[string]any, error) {
out := map[string]any{}
if patch.Replace.Set {
replacement := append(json.RawMessage(nil), patch.Replace.Value...)
if len(replacement) == 0 {
replacement = json.RawMessage(`{}`)
}
if err := requireJSON("Metadata.Replace", replacement); err != nil {
return nil, err
}
out["replace"] = replacement
}
if patch.Merge.Set {
merge := append(json.RawMessage(nil), patch.Merge.Value...)
if err := requireJSON("Metadata.Merge", merge); err != nil {
return nil, err
}
out["merge"] = merge
}
if len(patch.Set) > 0 {
values := make(map[string]json.RawMessage, len(patch.Set))
// Sorted, so a patch breaking two keys always names the same offender.
// The role applies them in key order for its own reasons; this is only
// about which refusal a caller fixing one key at a time sees first.
for _, key := range slices.Sorted(maps.Keys(patch.Set)) {
value := append(json.RawMessage(nil), patch.Set[key]...)
if err := requireJSON(fmt.Sprintf("Metadata.Set[%q]", key), value); err != nil {
return nil, err
}
values[key] = value
}
out["set"] = values
}
if len(patch.Unset) > 0 {
out["unset"] = append([]string(nil), patch.Unset...)
}
return out, nil
}
// refuseExcludedPatchMembers is the other half of the allowlist above: the
// IssuePatch members internal/httpapi/update.go's issuePatchMembers list leaves
// out.
func refuseExcludedPatchMembers(patch issueops.IssuePatch) error {
switch {
case patch.Owner.Set:
return refuse(encode.OpUpdateIssue, "W-IssuePatch.Owner")
case patch.ClosedBySession.Set:
return refuse(encode.OpUpdateIssue, "W-IssuePatch.ClosedBySession")
case patch.SpecID.Set:
return refuse(encode.OpUpdateIssue, "W-IssuePatch.SpecID")
case patch.AwaitID.Set:
return refuse(encode.OpUpdateIssue, "W-IssuePatch.AwaitID")
case patch.Persistence.Set:
return refuse(encode.OpUpdateIssue, "W-IssuePatch.Persistence")
}
return nil
}
func metadataPatched(m issueops.MetadataPatch) bool {
return m.Replace.Set || m.Merge.Set || len(m.Set) > 0 || len(m.Unset) > 0
}
func setString(out map[string]any, member string, field issueops.Field[string]) {
if field.Set {
out[member] = field.Value
}
}
// setNullable writes a member whose absence and whose null mean different
// things. The generic parameter is the POINTEE, so a nil Value marshals to null.
func setNullable[T any](out map[string]any, member string, field issueops.Field[*T]) {
if !field.Set {
return
}
if field.Value == nil {
out[member] = nil
return
}
out[member] = *field.Value
}
// setNullableTime is setNullable for the two timestamp members. It is separate
// only because a *time.Time dereferenced into an `any` would marshal through
// time.Time's own encoder either way, and spelling it out keeps the RFC 3339
// contract visible at the call site.
func setNullableTime(out map[string]any, member string, field issueops.Field[*time.Time]) {
if !field.Set {
return
}
if field.Value == nil {
out[member] = nil
return
}
out[member] = field.Value.UTC().Format(time.RFC3339Nano)
}
// CloseIssue is the OFF-ROLE raw close, mapped onto the same closeIssue
// operation the Lifecycle role uses (design D8's off-role list, extended by the
// `bd close` decision).
//
// Its one caller at tip is the molecule auto-close, which closes a parent whose
// children have all finished and discards nothing about the outcome. Routing it
// onto the role's operation rather than refusing it is what keeps that path
// working over http; it carries no reason-per-item and no force, so the mapping
// is total.
func (s *Store) CloseIssue(ctx context.Context, id, reason, actor, session string) error {
w, err := s.roleWire("CloseIssue")
if err != nil {
return err
}
if err := requireActor(actor); err != nil {
return err
}
if err := requireID("issue id", id); err != nil {
return err
}
_, err = w.CloseIssue(ctx, id, closeBody(actor, reason, session, false))
return err
}

View file

@ -0,0 +1,289 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/lifecycle_create_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"errors"
"reflect"
"slices"
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The SINGLE create's refuse-not-drop gate, and the counterpart of
// TestBatchCreateRefusesEveryMemberTheWireExcludes.
//
// The two operations flatten the same types.Issue and they flatten DIFFERENT
// slices of it — createIssue publishes twenty members where batchCreateIssues'
// item publishes eight — so neither gate can stand in for the other. What they
// do share is the ROLE's own ignore list, which is one fact about one role and
// is one table here.
//
// The four directions:
//
// carried -> wire the twenty members the client claims to carry are
// members apigen.CreateIssueRequest really publishes.
// source -> partition every populatable field of types.Issue is carried,
// ignored by the role, refused by the role, or refused by
// the wire. There is no fifth arm, so a member added
// upstream cannot arrive unclassified.
// behavior every wire-refused member really fails, citing its
// ledger row, WITHOUT dialing.
// request the request's own excluded member — IDPrefix — refuses
// the same way wherever it would act.
func TestCreateRefusesEveryMemberTheWireExcludes(t *testing.T) {
t.Run("carried members are the wire's own", func(t *testing.T) {
published := bodyMembers(t, reflect.TypeOf(apigen.CreateIssueRequest{}))
for field, wireMember := range createCarriedIssueMembers {
if _, ok := reflect.TypeOf(issueops.Issue{}).FieldByName(field); !ok {
t.Errorf("the carried table names Issue.%s, which does not exist", field)
}
if !published[wireMember] {
t.Errorf("Issue.%s claims wire member %q, which CreateIssueRequest does not publish", field, wireMember)
}
}
// The complement is the REQUEST's own members rather than the issue's,
// so this direction stops at "published"; the whole-body bijection is
// the createIssue writeShape's, which claims every member of this body
// exactly once.
for _, wireMember := range createCarriedIssueMembers {
if strings.TrimSpace(wireMember) == "" {
t.Error("the carried table names an empty wire member")
}
}
})
refused := createWireRefusedIssueMembers(t)
t.Run("the partition covers every member", func(t *testing.T) {
if len(refused) == 0 {
t.Fatal("no member is wire-refused; the partition tables have swallowed the population this gate exists for")
}
// The creation stamp and the classification plumbing are the two
// populations the operation's own description says it cannot set, and a
// create that dropped either is a row the caller believes they wrote.
// CreatedBy stays here because only a value NAMING THE ACTOR rides the
// server's stamp — see "a CreatedBy naming the actor" below.
for _, name := range []string{"CreatedAt", "CreatedBy", "SpecID", "StorageClass", "MolType", "Pinned"} {
if !slices.Contains(refused, name) {
t.Errorf("Issue.%s is not in the refused population; a create that dropped it is data loss", name)
}
}
// And the mirror image: the members this operation DOES publish that
// the batch's narrower item does not. A regression that copied the
// batch's table onto this operation would refuse all six.
for _, name := range []string{"ID", "Status", "Notes", "Metadata", "Ephemeral", "Sender"} {
if slices.Contains(refused, name) {
t.Errorf("Issue.%s is refused, but createIssue publishes it — this is the operation that fixed the batch's gap", name)
}
}
for field := range roleIgnoredCreateIssueMembers {
if _, dup := createCarriedIssueMembers[field]; dup {
t.Errorf("Issue.%s is both carried and ignored", field)
}
}
})
t.Run("every refused member fails without dialing", func(t *testing.T) {
for _, name := range refused {
t.Run(name, func(t *testing.T) {
issue := &issueops.Issue{Title: "t"}
setNonZero(t, reflect.ValueOf(issue).Elem().FieldByName(name))
w := &stubWire{}
_, err := createRole(t, w).Create(t.Context(), issueops.CreateRequest{
Actor: "writer", Issue: issue,
})
assertRefusedBy(t, err, "W-CreateRequest.Issue")
if !strings.Contains(err.Error(), name) {
t.Errorf("the refusal does not name the member: %v", err)
}
if len(w.calls) != 0 {
t.Errorf("the refused member reached the wire: %v", w.calls)
}
})
}
})
t.Run("the role's own two are ErrValidation", func(t *testing.T) {
for name := range createRoleRefusedIssueMembers {
issue := &issueops.Issue{Title: "t"}
setNonZero(t, reflect.ValueOf(issue).Elem().FieldByName(name))
w := &stubWire{}
_, err := createRole(t, w).Create(t.Context(), issueops.CreateRequest{Actor: "writer", Issue: issue})
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Issue.%s error = %v, want ErrValidation — a local backend refuses it too", name, err)
}
if len(w.calls) != 0 {
t.Errorf("Issue.%s reached the wire: %v", name, w.calls)
}
}
})
t.Run("a CreatedBy naming the actor rides the server's stamp", func(t *testing.T) {
// Every create shape stamps created_by from the actor, so the one value
// that stamp writes is carried BY it — and it is what every CLI create
// sends. Any other value would be silently replaced, which is why the
// sweep above still refuses CreatedBy: "sentinel" is never the actor.
w := &stubWire{}
if _, err := createRole(t, w).Create(t.Context(), issueops.CreateRequest{
Actor: "writer",
Issue: &issueops.Issue{Title: "t", CreatedBy: "writer"},
}); err != nil {
t.Fatalf("Create with CreatedBy == Actor = %v, want it carried by the server's stamp", err)
}
if w.lastCreate.Actor != "writer" {
t.Errorf("sent actor = %q, want the creator the stamp will write", w.lastCreate.Actor)
}
})
t.Run("the request's own excluded member refuses where it would act", func(t *testing.T) {
w := &stubWire{}
_, err := createRole(t, w).Create(t.Context(), issueops.CreateRequest{
Actor: "writer",
IDPrefix: "other",
Issue: &issueops.Issue{ID: "other-1", Title: "t"},
})
assertRefusedBy(t, err, "W-CreateRequest.IDPrefix")
if len(w.calls) != 0 {
t.Errorf("the prefix override reached the wire: %v", w.calls)
}
})
t.Run("the request's own excluded member is inert where it would not act", func(t *testing.T) {
// The role reads IDPrefix only to check an explicit, unforced id. `bd
// create` sends the workspace's prefix on EVERY create, so refusing it
// on a minted or forced id would refuse every create in a workspace
// whose config.yaml names a prefix.
for name, req := range map[string]issueops.CreateRequest{
"a minted id": {Issue: &issueops.Issue{Title: "t"}},
"a forced id": {Issue: &issueops.Issue{ID: "other-1", Title: "t"}, ForceIDPrefix: true},
} {
t.Run(name, func(t *testing.T) {
w := &stubWire{}
request := req
request.Actor = "writer"
request.IDPrefix = "other"
if _, err := createRole(t, w).Create(t.Context(), request); err != nil {
t.Fatalf("Create = %v, want the inert override sent without", err)
}
if got := derefOr(w.lastCreate.Id, ""); got != request.Issue.ID {
t.Errorf("sent id = %q, want %q", got, request.Issue.ID)
}
if forced := w.lastCreate.ForceIdPrefix != nil && *w.lastCreate.ForceIdPrefix; forced != request.ForceIDPrefix {
t.Errorf("sent force_id_prefix = %v, want %v", forced, request.ForceIDPrefix)
}
})
}
})
t.Run("a metadata blob that is not JSON is ErrValidation, not a marshal fault", func(t *testing.T) {
// The blob's CONTENT is the role's business and travels verbatim; its
// well-formedness is this layer's, because bytes that are not JSON
// cannot go on a JSON wire and would otherwise fail inside
// json.Marshal — a transport fault where the contract promises a
// deterministic validation failure.
for name, req := range map[string]issueops.CreateRequest{
"on the issue": {
Issue: &issueops.Issue{Title: "t", Metadata: []byte(`{"k":`)},
},
"on an edge": {
Issue: &issueops.Issue{Title: "t"},
Dependencies: []issueops.CreateDependency{{TargetID: "bd-9", Type: types.DepBlocks, Metadata: `not json`}},
},
} {
t.Run(name, func(t *testing.T) {
w := &stubWire{}
request := req
request.Actor = "writer"
if _, err := createRole(t, w).Create(t.Context(), request); !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Create with a malformed metadata blob = %v, want ErrValidation", err)
}
if len(w.calls) != 0 {
t.Errorf("the malformed blob reached the wire: %v", w.calls)
}
})
}
})
t.Run("the edge's one", func(t *testing.T) {
// ONE, not the batch's three: createIssue's edge publishes `reverse`
// and `metadata`, because a create has an id for a target to point back
// at. Only the thread has no member on any operation.
w := &stubWire{}
_, err := createRole(t, w).Create(t.Context(), issueops.CreateRequest{
Actor: "writer",
Issue: &issueops.Issue{Title: "t"},
Dependencies: []issueops.CreateDependency{
{TargetID: "bd-9", Type: types.DepBlocks, ThreadID: "th-1"},
},
})
assertRefusedBy(t, err, "W-CreateDependency.ThreadID")
if len(w.calls) != 0 {
t.Errorf("the thread id reached the wire: %v", w.calls)
}
})
t.Run("the request has exactly the members this gate accounts for", func(t *testing.T) {
// The CONTAINER above types.Issue, which no other gate can see: the
// createIssue writeShape classifies these fields against the body, but
// a field added to CreateRequest tomorrow and then carried by a new
// wire member would leave this gate's own reasoning stale without
// anything saying so.
got := populatableFields(reflect.TypeOf(issueops.CreateRequest{}))
sort.Strings(got)
want := []string{
"Actor", "Dependencies", "ForceIDPrefix", "IDPrefix",
"InheritLabelsFromParent", "Issue", "ParentID", "WaitsFor",
}
if !reflect.DeepEqual(got, want) {
t.Errorf("CreateRequest carries %v, want %v.\n"+
"A new member reaches no wire member and no refusal: carry it in createBody, or refuse it with a ledger row.", got, want)
}
})
}
// createRoleRefusedIssueMembers are the two members the ROLE refuses in its own
// right, so the refusal is ErrValidation on every backend rather than a
// divergence: "Issue.Comments and Issue.Dependencies must be empty; supply edges
// through the request's own Dependencies field" (issueops.CreateRequest.Issue).
var createRoleRefusedIssueMembers = map[string]string{
"Comments": "the role refuses a create carrying comments",
"Dependencies": "the role refuses an inline edge list; edges ride the request's own Dependencies",
}
// createWireRefusedIssueMembers is the complement the gate drives: every
// populatable field of types.Issue that is neither carried by this operation's
// vocabulary, nor ignored by the role, nor refused by the role in its own right.
func createWireRefusedIssueMembers(t *testing.T) []string {
t.Helper()
var out []string
for _, name := range populatableFields(reflect.TypeOf(issueops.Issue{})) {
if _, ok := createCarriedIssueMembers[name]; ok {
continue
}
if _, ok := roleIgnoredCreateIssueMembers[name]; ok {
continue
}
if _, ok := createRoleRefusedIssueMembers[name]; ok {
continue
}
out = append(out, name)
}
return out
}
func createRole(t *testing.T, w *stubWire) issueops.Lifecycle {
t.Helper()
lifecycle, err := stubStore(t, w).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
return lifecycle
}

View file

@ -0,0 +1,308 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/lifecycle_update_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"encoding/json"
"errors"
"reflect"
"sort"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
)
// The PATCH document's own gates, and the counterpart of
// lifecycle_create_test.go for the operation whose request is not a struct.
//
// updateIssue is the one write on this surface the client builds as a map, so
// nothing the compiler does can hold it to the wire's vocabulary: a typo is a
// 400 from a live server and a green run everywhere else. Three things are
// asserted here that no served case can show as cheaply — the members the wire
// wave added really reach the document, the metadata sub-document is the wire's
// own algebra rather than a second spelling of it, and a member the role adds
// tomorrow cannot arrive unclassified.
// TestUpdateSendsThePatchMembersTheWireNowPublishes is the round trip for the
// four members client wave ga-7i6by carries: `status`, `assignee`, `parent_id`
// and `metadata`. Each was a W-IssuePatch refusal until the wire published it,
// and each is asserted through the document the role built rather than through
// the result, because the result is the server's and would look identical if
// the member had been dropped.
func TestUpdateSendsThePatchMembersTheWireNowPublishes(t *testing.T) {
w := &stubWire{update: &apigen.UpdateIssueResponse{Changed: true, Revision: "0"}}
lifecycle, err := stubStore(t, w).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
if _, err := lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "writer", IssueID: "bd-1",
Patch: issueops.IssuePatch{
Status: set(issueops.StatusInProgress),
Assignee: set("holder"),
ParentID: set("bd-parent"),
Metadata: issueops.MetadataPatch{
Set: map[string]json.RawMessage{"gc.lease": json.RawMessage(`"win44"`)},
},
},
}); err != nil {
t.Fatalf("Update: %v", err)
}
patch := w.lastPatch
for member, want := range map[string]any{
"status": string(issueops.StatusInProgress),
"assignee": "holder",
"parent_id": "bd-parent",
} {
if got, ok := patch[member]; !ok || got != want {
t.Errorf("patch[%s] = %v (present %t), want %v", member, got, ok, want)
}
}
metadata, ok := patch["metadata"].(map[string]any)
if !ok {
t.Fatalf("patch[metadata] = %#v, want the wire's own metadata document", patch["metadata"])
}
values, ok := metadata["set"].(map[string]json.RawMessage)
if !ok {
t.Fatalf("metadata[set] = %#v, want the raw values map", metadata["set"])
}
if got := string(values["gc.lease"]); got != `"win44"` {
t.Errorf("metadata.set[gc.lease] = %s, want the caller's own bytes", got)
}
}
// TestUpdateSendsTheEmptyStringsThatMeanSomething is the half of the three
// string members a nil check would lose. On this operation the empty string is
// not "no value": it UNASSIGNS on `assignee` and removes every parent-child
// edge on `parent_id`, so a builder that skipped a member because its value was
// empty would turn two real edits into no edit at all — silently, since the
// server answers `changed: false` and the caller reads a 200.
func TestUpdateSendsTheEmptyStringsThatMeanSomething(t *testing.T) {
w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "0"}}
lifecycle, err := stubStore(t, w).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
if _, err := lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "writer", IssueID: "bd-1",
Patch: issueops.IssuePatch{Assignee: set(""), ParentID: set("")},
}); err != nil {
t.Fatalf("Update: %v", err)
}
for _, member := range []string{"assignee", "parent_id"} {
got, ok := w.lastPatch[member]
if !ok {
t.Errorf("patch omits %s, which was set to the empty string — the unassign and the unparent are edits, not omissions", member)
continue
}
if got != "" {
t.Errorf("patch[%s] = %v, want the empty string the caller set", member, got)
}
}
}
// TestUpdateEncodesTheMetadataAlgebra drives the sub-document one arm at a time.
//
// The algebra is the ROLE's — merge, then set in key order, then unset, with
// replace replacing the whole document — and the wire publishes it member for
// member, so this asserts a projection rather than a translation. The one place
// the two genuinely disagree is the CLEAR: the role spells it as a set Replace
// holding no bytes, and no bytes is not a JSON value at all.
func TestUpdateEncodesTheMetadataAlgebra(t *testing.T) {
tests := []struct {
name string
patch issueops.MetadataPatch
want map[string]string
}{
{
name: "replace carries the caller's document",
patch: issueops.MetadataPatch{Replace: set(json.RawMessage(`{"a":1}`))},
want: map[string]string{"replace": `{"a":1}`},
},
{
name: "an empty replacement is the clear, spelled as the empty document",
patch: issueops.MetadataPatch{Replace: set(json.RawMessage(nil))},
want: map[string]string{"replace": `{}`},
},
{
name: "merge carries the overlay",
patch: issueops.MetadataPatch{Merge: set(json.RawMessage(`{"b":2}`))},
want: map[string]string{"merge": `{"b":2}`},
},
{
name: "set and unset travel together",
patch: issueops.MetadataPatch{
Set: map[string]json.RawMessage{"k": json.RawMessage(`{"nested":[1,2]}`)},
Unset: []string{"gone"},
},
want: map[string]string{"set": `{"k":{"nested":[1,2]}}`, "unset": `["gone"]`},
},
{
name: "a key stored as JSON null is a value, not an absence",
patch: issueops.MetadataPatch{Set: map[string]json.RawMessage{"k": json.RawMessage(`null`)}},
want: map[string]string{"set": `{"k":null}`},
},
{
// EVERY NUMBER TRAVELS AS THE CALLER'S OWN LITERAL, and this is the
// case that says why it must. The role compares metadata values by
// their SOURCE LITERAL — `1` and `1.0` are not equal — so a client
// that decoded a value through `any` and re-encoded it would change
// the request: `1.0` would arrive as `1`, an integer past 2^53 would
// arrive rounded, and both would be compared against a stored value
// under a spelling the caller never wrote. On the compare-and-set
// path that is a changed VERDICT, not a cosmetic difference.
//
// The store renormalizes numbers on the way in and says so; what
// must not happen is a SECOND renormalization here, before the
// store has seen what was actually sent.
name: "numbers travel as the caller's own literal",
patch: issueops.MetadataPatch{
Set: map[string]json.RawMessage{
"tenth": json.RawMessage(`1.0`),
"big": json.RawMessage(`9007199254740993`),
},
},
want: map[string]string{"set": `{"big":9007199254740993,"tenth":1.0}`},
},
{
name: "and so does a replacement document",
patch: issueops.MetadataPatch{Replace: set(json.RawMessage(`{"n":1.0}`))},
want: map[string]string{"replace": `{"n":1.0}`},
},
{
name: "and so does a merge overlay",
patch: issueops.MetadataPatch{Merge: set(json.RawMessage(`{"n":1.0}`))},
want: map[string]string{"merge": `{"n":1.0}`},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "0"}}
lifecycle, err := stubStore(t, w).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
if _, err := lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "writer", IssueID: "bd-1",
Patch: issueops.IssuePatch{Metadata: test.patch},
}); err != nil {
t.Fatalf("Update: %v", err)
}
// Through the marshaler, because what the server reads is the
// BYTES: a map of json.RawMessage that looked right in Go and
// marshaled to something else would pass a field-by-field check.
document, ok := w.lastPatch["metadata"]
if !ok {
t.Fatal("the patch carries no metadata member")
}
encoded, err := json.Marshal(document)
if err != nil {
t.Fatalf("marshal the metadata document: %v", err)
}
var got map[string]json.RawMessage
if err := json.Unmarshal(encoded, &got); err != nil {
t.Fatalf("re-read the metadata document: %v", err)
}
if len(got) != len(test.want) {
t.Errorf("metadata document = %s, want exactly %v", encoded, sortedStringKeys(test.want))
}
for member, want := range test.want {
if string(got[member]) != want {
t.Errorf("metadata[%s] = %s, want %s", member, got[member], want)
}
}
})
}
}
// TestUpdateRefusesMetadataThatIsNotJSON keeps a blob that cannot go on a JSON
// wire off it, the way the create's own gate does. The blob's CONTENT is the
// role's business and travels verbatim; its well-formedness is this layer's,
// because bytes that are not JSON fail inside json.Marshal and would reach the
// caller as a transport fault where every role contract promises a
// deterministic validation failure.
func TestUpdateRefusesMetadataThatIsNotJSON(t *testing.T) {
for name, patch := range map[string]issueops.MetadataPatch{
"replace": {Replace: set(json.RawMessage(`{"k":`))},
"merge": {Merge: set(json.RawMessage(`not json`))},
"set": {Set: map[string]json.RawMessage{"k": json.RawMessage(`{`)}},
} {
t.Run(name, func(t *testing.T) {
w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "0"}}
lifecycle, err := stubStore(t, w).IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
_, err = lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "writer", IssueID: "bd-1",
Patch: issueops.IssuePatch{Metadata: patch},
})
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("a malformed %s = %v, want ErrValidation", name, err)
}
if len(w.calls) != 0 {
t.Errorf("the malformed blob reached the wire: %v", w.calls)
}
})
}
}
// TestTheEncodedMetadataDocumentUsesOnlyPublishedMembers is the patch
// document's own gate one level down.
//
// TestTheEncodedPatchDocumentUsesOnlyPublishedMembers holds the TOP level to
// apigen.IssuePatchBody; the metadata member is a nested document built the
// same untyped way, and until this ran nothing held it to
// apigen.ApplyMetadataPatch at all. Both directions matter: a member the wire
// does not publish is a 400, and a member it publishes that no arm of
// MetadataPatch drives is an edit this client cannot make.
func TestTheEncodedMetadataDocumentUsesOnlyPublishedMembers(t *testing.T) {
published := bodyMembers(t, reflect.TypeOf(apigen.ApplyMetadataPatch{}))
// Replace is deliberately NOT set beside the other three: the wire refuses
// that combination with a 400 and so does the role, so a patch setting all
// four at once is not a request either side would answer. It gets its own
// pass.
document, err := encodeMetadataPatch(issueops.MetadataPatch{
Merge: set(json.RawMessage(`{"m":1}`)),
Set: map[string]json.RawMessage{"s": json.RawMessage(`1`)},
Unset: []string{"u"},
})
if err != nil {
t.Fatalf("encode the incremental metadata edits: %v", err)
}
replacement, err := encodeMetadataPatch(issueops.MetadataPatch{Replace: set(json.RawMessage(`{}`))})
if err != nil {
t.Fatalf("encode the replacement: %v", err)
}
for member := range replacement {
document[member] = replacement[member]
}
for member := range document {
if !published[member] {
t.Errorf("the encoded metadata document carries %q, which ApplyMetadataPatch does not publish: %v",
member, sortedKeys(published))
}
}
for member := range published {
if _, ok := document[member]; !ok {
t.Errorf("ApplyMetadataPatch publishes %q and no arm of MetadataPatch drives it; that member is unreachable from this client",
member)
}
}
}
func sortedStringKeys(m map[string]string) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}

View file

@ -0,0 +1,209 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/list_sort_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"slices"
"testing"
"time"
"gopkg.in/yaml.v3"
"github.com/steveyegge/beads/internal/httpapi/spec"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/storage/sqlbuild"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// TestFlaglessListSortIsTheSameOrderNamed is the drift pin for the pushdown's
// one translation: issueops.ListRequest's empty SortBy goes onto the wire as
// `priority`, and that is sound only while the two are the SAME order.
//
// A served run cannot show this. It would answer correctly whichever spelling
// were sent, because the reference store on the far side is the same code
// making the same substitution — so the case that catches a wrong constant is
// this one, asked of the three places the equivalence has to hold at once.
//
// It sits in the default build rather than behind the cgo tag for the same
// reason the other two drift pins do: nothing here needs a database.
func TestFlaglessListSortIsTheSameOrderNamed(t *testing.T) {
// THE DOCUMENT. The translation exists because an empty value is not in
// the published enum — a server would refuse `sort=` — so what the client
// substitutes has to be a member, and the absence of an empty member is
// what keeps the substitution from being dead code.
published := publishedParamEnum(t, wire.OpListIssues, "sort")
if len(published) == 0 {
t.Fatalf("the document publishes no `sort` enum on %s; this direction would assert nothing", wire.OpListIssues)
}
if !slices.Contains(published, flaglessListSort) {
t.Errorf("flaglessListSort = %q, which %s does not publish (%v): the pushdown would earn a 400 on every "+
"request nobody named a sort for", flaglessListSort, wire.OpListIssues, published)
}
if slices.Contains(published, "") {
t.Errorf("%s now publishes an empty `sort` member (%v): ListRequest's own empty SortBy could be sent "+
"verbatim and this translation is dead code rather than a necessity", wire.OpListIssues, published)
}
// THE SERVER'S ORDER BY, which is what actually decides which rows survive
// the limit once the order is pushed down. Both directions, because the
// pushdown emits `reverse` alongside `sort` and a spelling that agreed
// ascending and disagreed descending would still lose rows.
column := func(key string) string { return key }
for _, reverse := range []bool{false, true} {
flagless := sqlbuild.OrderByForColumns("", reverse, column)
named := sqlbuild.OrderByForColumns(flaglessListSort, reverse, column)
if flagless == "" {
t.Fatalf("the flagless order renders no ORDER BY (reverse %v); it is a Go-side sort now, and the "+
"pushdown cannot ask a server for an order the server does not express", reverse)
}
if flagless != named {
t.Errorf("reverse %v: the flagless order renders %q and %q renders %q; the pushdown would ask the "+
"server for a different order than a local `bd list` runs", reverse, flagless, flaglessListSort, named)
}
}
// THE CLIENT'S OWN EPILOGUE, which is the half the pushdown newly leans on.
// sortListRows still runs over the page the server ordered, and it runs
// under the caller's spelling — the empty one — while the server ordered
// under the substituted one. If those two produced different orders, the
// fast leg would fetch the right rows and then shuffle them.
//
// The corpus is SCRAMBLED before each run so this compares two orders
// rather than two no-ops.
for _, reverse := range []bool{false, true} {
flagless := flaglessSortCorpus()
named := flaglessSortCorpus()
sortListRows(flagless, "", reverse)
sortListRows(named, flaglessListSort, reverse)
if got, want := rowIDs(flagless), rowIDs(named); !slices.Equal(got, want) {
t.Errorf("reverse %v: the client orders the flagless spelling %v and %q %v; the pushdown asks the "+
"server for one and re-sorts the answer under the other", reverse, got, flaglessListSort, want)
}
}
}
// TestKeysetFilterKeepsExactlyTheRowsPastThePositionInItsOrder is the drift
// pin for the walk's discard rule: a row survives keysetFilter exactly when
// sqlbuild.Less — the Go-side mirror of the ORDER BY a local list renders —
// puts the position before it, in the order the position names. A position
// carrying AfterPriority is one in the priority order and a bare pair is one in
// the created order, which is how the local predicate chooses between
// sqlbuild's two keyset clauses.
//
// Every corpus row is tried as the position against every row, so each of the
// order's tie-breaks — priority, then instant, then id — decides some pair, and
// the corpus's newer lower-priority rows are the ones a filter that compared
// the pair alone would get wrong.
func TestKeysetFilterKeepsExactlyTheRowsPastThePositionInItsOrder(t *testing.T) {
corpus := flaglessSortCorpus()
for _, order := range []string{"priority", "created"} {
for _, pos := range corpus {
req := issueops.ListRequest{AfterCreatedAt: ptrTo(pos.CreatedAt), AfterID: pos.ID}
if order == "priority" {
req.AfterPriority = ptrTo(pos.Priority)
}
keep := keysetFilter(req)
if keep == nil {
t.Fatalf("a %s position at %s has no discard rule", order, pos.ID)
}
for _, row := range corpus {
if got, want := keep(row), sqlbuild.Less(pos.Issue, row.Issue, order, false); got != want {
t.Errorf("a %s position at %s (P%d) keeps %s (P%d) = %v, want %v",
order, pos.ID, pos.Priority, row.ID, row.Priority, got, want)
}
}
}
}
}
// TestKeysetFilterNeedsAnInstant pins the contract's rule that AfterCreatedAt
// alone decides whether a position was supplied: an id or a priority without
// one is ignored, as the local predicate ignores it, rather than read as a
// position at the zero instant — which every row is after, so the page would
// come back empty.
func TestKeysetFilterNeedsAnInstant(t *testing.T) {
for name, req := range map[string]issueops.ListRequest{
"an id alone": {AfterID: "bd-1"},
"a priority alone": {AfterPriority: ptrTo(1)},
"both, no instant": {AfterID: "bd-1", AfterPriority: ptrTo(1)},
} {
if keysetFilter(req) != nil {
t.Errorf("%s: keysetFilter answered a discard rule, want none — there is no position without an instant", name)
}
}
}
func rowIDs(rows []*types.IssueWithCounts) []string {
ids := make([]string, 0, len(rows))
for _, row := range rows {
ids = append(ids, row.ID)
}
return ids
}
// flaglessSortCorpus is a fixed set of rows, in an order that is none of the
// ones under test, reaching every tie-break the flagless order carries: equal
// priorities decided by created time, equal priorities and equal instants
// decided by id, and ids whose natural and lexical orders disagree.
func flaglessSortCorpus() []*types.IssueWithCounts {
base := time.Date(2026, 8, 21, 12, 0, 0, 0, time.UTC)
var corpus []*types.IssueWithCounts
for _, seed := range []struct {
id string
priority int
minute int
}{
{"bd-6", 2, 0}, {"bd-2", 0, 0}, {"bd-7", 3, 5}, {"bd-10", 0, 0},
{"bd-4", 1, 0}, {"bd-1", 0, 0}, {"bd-5", 1, 5}, {"bd-3", 0, 5},
} {
at := base.Add(time.Duration(seed.minute) * time.Minute)
corpus = append(corpus, &types.IssueWithCounts{Issue: &types.Issue{
ID: seed.id, Title: seed.id, Status: types.StatusOpen, Priority: seed.priority,
IssueType: types.TypeTask, CreatedAt: at, UpdatedAt: at,
}})
}
return corpus
}
// publishedParamEnum reads one operation parameter's enum out of the wire
// contract itself, rather than out of a second copy of the names.
func publishedParamEnum(t *testing.T, operationID, param string) []string {
t.Helper()
// S3 reconciliation (2026-10): spec.OpenAPIV0() rather
// than a relative os.ReadFile — the document is go:embed'd into
// internal/httpapi/spec precisely so a reader does not depend on a
// filesystem layout, and a relative path breaks the moment this runs
// under Bazel's test sandbox, which copies in only what a target
// declares as `data`. internal/httpclient/encode's own bijection gate
// already reads the document this way for the same reason.
raw := spec.OpenAPIV0()
var doc struct {
Paths map[string]map[string]struct {
OperationID string `yaml:"operationId"`
Parameters []struct {
Name string `yaml:"name"`
Schema struct {
Enum []string `yaml:"enum"`
} `yaml:"schema"`
} `yaml:"parameters"`
} `yaml:"paths"`
}
if err := yaml.Unmarshal(raw, &doc); err != nil {
t.Fatalf("parse the wire contract: %v", err)
}
for _, methods := range doc.Paths {
for _, operation := range methods {
if operation.OperationID != operationID {
continue
}
for _, p := range operation.Parameters {
if p.Name == param {
return p.Schema.Enum
}
}
}
}
t.Fatalf("the document publishes no %s parameter on %s", param, operationID)
return nil
}

View file

@ -0,0 +1,457 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/list_walk.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"net/http"
"net/url"
"slices"
"strconv"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/storage/sqlbuild"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The listIssues pager: the three things the wire cannot carry for `bd list`,
// done here because the encoder table says they are done here.
//
// - THE DISPLAY ORDER. The operation publishes `sort` now, so a BOUNDED
// request in an order the caller named is one request: sortedPage names the
// order on the wire and the server's own LIMIT decides which rows survive
// it. What is left of ledger row L2 is the three legs that cannot take that
// route — an unlimited read, a caller-supplied keyset position, and a
// server that does not advertise the capability — which still walk to
// exhaustion and then run the client-side comparator. The weld itself is
// unchanged: a cursor is bound to the paged order it was minted in
// (`created` or `priority`, upstream #5666), and the server refuses it under
// any other `sort`, because resuming a keyset position inside a different
// order skips and duplicates rows; the seven display orders and every
// reversed order never carry one.
// - THE CALLER-SUPPLIED KEYSET POSITION. issueops.Reader promises every
// implementation honors AfterCreatedAt/AfterID, and the wire populates them
// only from an opaque cursor the client must not mint. So the position is
// honored by a SKIP-FORWARD WALK: page the created-order wire from the
// start and discard the rows at or before the position (D8 row 1).
// - THE MaxRows CAP. The wire publishes no max_rows, so the cap is enforced
// during page accumulation and the exact sentinel `bd list` classifies into
// exit 2 is synthesized here (D12).
//
// WHAT IS DELIBERATELY ABSENT is a `created_before` jump for the keyset walk.
// It would be the obvious optimization and it is unsafe: created_before is
// strictly exclusive while the keyset upper bound is inclusive, so a jump
// computed from an instant whose storage granularity the client cannot observe
// would silently drop the same-instant tail — the exact drop L3 and L12 exist
// to prevent, traded for a round trip.
// wireListSort is the order listIssues serves when no `sort` names another,
// spelled as the sort key ListRequest.SortBy takes for it. A request in this
// order and this direction is the one shape the walk can stop early on, and the
// one shape the pushdown leaves alone.
const wireListSort = "created"
// flaglessListSort is how the pager spells ListRequest's own empty SortBy — the
// order `bd list` shows when nobody names one — as a value the published enum
// carries.
//
// The two are the SAME clause and not merely similar ones: sqlbuild renders `""`
// and `"priority"` through one branch (internal/storage/sqlbuild/sort.go,
// `if sortBy == "" || sortBy == "priority"`), and sqlbuild.Less mirrors it the
// same way. What the server does differently under the named spelling is run the
// page epilogue's comparator over the clause's output, which is a stable sort by
// the same key — order-preserving on rows the same clause already ordered.
//
// It cannot be sent as `sort=` instead: an empty value is not in the published
// enum, so the server would refuse it, and refusing is the correct thing for the
// server to do — an empty enum member is a client that failed to decide.
const flaglessListSort = "priority"
// walkPageSize is how many rows one request asks for when the CLIENT owns the
// paging rather than the caller's own limit — an unlimited read, or any walk to
// exhaustion. It is a round trip's worth of rows, not a bound on the answer.
//
// It is a var and not a const for exactly one reason: the multi-page arm of the
// walk — the cursor echo, the accumulation across pages, the termination — is
// only reachable with more rows than this, and a test that seeded two hundred of
// them would be paying seconds to exercise three lines.
var walkPageSize = 200
// defaultListLimit is the shared list default a nil ListRequest.Limit means.
//
// It is redeclared rather than imported: internal/workapi is denied to this
// package by depguard (a client-side filter is one no server-side gate can
// observe), and the constant is needed here because a walk to exhaustion has to
// know what to trim to. TestDefaultListLimitMatchesTheSharedDefault pins it
// against workapi's own from a test file, where the rule does not apply.
const defaultListLimit = 50
// walkIssues answers one ListRequest from listIssues.
//
// params is the encoder's output and stays authoritative for every filter: the
// only keys this function writes are `limit` and `cursor`, which the encoder
// table already assigns to the pager (the cursor is reserved on the listIssues
// table, and the parent-walk table says the pager owns the per-page limit).
func (s *Store) walkIssues(ctx context.Context, params url.Values, req issueops.ListRequest) (issueops.IssuePage, error) {
limit := defaultListLimit
if req.Limit != nil {
limit = *req.Limit
}
// A negative limit is the server's refusal to make, not this pager's: it
// has a documented 400 for it, and the mapper turns that into the same
// ErrValidation a local backend answers with. Sending the encoder's params
// verbatim is how that reaches the caller unmangled.
if limit < 0 {
var body apigen.IssuesPage
if err := s.dispatch(ctx, listRequest(params), &body); err != nil {
return issueops.IssuePage{}, err
}
return issueops.IssuePage{Items: wireRows(body.Items, req.Brief), HasMore: body.HasMore}, nil
}
keep := keysetFilter(req)
// The walk can stop early only when the rows arrive in the order the caller
// asked for; anything else has to see every row before it knows which ones
// the page keeps.
want := 0
if req.SortBy == wireListSort && !req.Reverse {
want = limit
}
// THE PUSHDOWN LEG. Each conjunct names a leg that must stay a walk, and
// they are ordered cheapest-decides-first because only the last one can
// cost a round trip:
//
// limit > 0 — an unlimited read has to cross every row anyway, so
// pushdown saves nothing, and sending `limit=0` down would
// newly meet the server's unlimited-read refusal that the
// fixed-size walk deliberately never reaches. (A negative
// limit returned above; this is "not unlimited".)
// want == 0 — the created order the walk ALREADY stops early on. Under
// it `want` is the caller's limit and under every other
// order it is zero, so this is that same fact spelled once
// rather than a second copy of the condition that can drift
// from it. Sending `sort=created` would be accepted and
// would buy nothing but a larger skew surface, so the one
// request family that predates the parameter keeps sending
// no parameter.
// keep == nil — no caller-supplied keyset position. keysetFilter returns
// nil for exactly that, so asking IT rather than restating
// its condition is what keeps the two from drifting. The
// filter discards from what the walk FETCHED, and run
// against a page some other order truncated it drops rows
// whose replacements were never fetched — a wrong answer,
// not a slow one.
// sort + cap — a --max-rows cap over an order SQL cannot express. This
// leg's whole cap story is that min(limit, MaxRows+1) IS
// the local expression, and for a GO-SIDE sort it is not:
// workapi.SQLLimit pushes 0 down rather than the limit,
// because the ordering happens after the query, so locally
// the window is MaxRows+1 REGARDLESS of the limit and the
// cap fires on the overage even under a limit at or below
// it. A request bounded by the limit cannot observe that
// overage, so pushing one down would answer where both
// local mode and the walk refuse. sqlbuild.IsGoSideSort is
// asked rather than its member named, so a second Go-side
// key added there cannot reopen this silently. Uncapped,
// the question does not arise and these keys push down like
// any other.
//
// The capability probe is last because it is the only one that can dial.
if limit > 0 && want == 0 && keep == nil &&
listSortPushdownEligible(req) &&
!(req.MaxRows > 0 && sqlbuild.IsGoSideSort(req.SortBy)) &&
s.servesListSort(ctx) {
return s.sortedPage(ctx, params, req, limit)
}
rows, err := s.fetchIssuePages(ctx, params, req.Brief, want, req.MaxRows, req.MaxRowsSource, keep)
if err != nil {
return issueops.IssuePage{}, err
}
sortListRows(rows, req.SortBy, req.Reverse)
hasMore := false
if limit > 0 && len(rows) > limit {
rows, hasMore = rows[:limit], true
}
return issueops.IssuePage{Items: rows, HasMore: hasMore}, nil
}
// servesListSort reports whether the server advertises issues.list.sort.
//
// It forces the one lazy handshake the store already owns and reads the cached
// capability list, exactly as servesBatchClose does, so it costs at most one
// round trip per process and none once the handshake has run. listIssues is a
// BASELINE operation — dispatch preflights nothing for it — so on a `bd list`
// this is the only handshake there is, which is why the gate above consults it
// last: a request that cannot push down never pays for it.
//
// A handshake that cannot be obtained reports false rather than an error, and
// that is a deliberate choice about which behavior is preserved. This is a
// CAPABILITY PROBE on a baseline read: the answer it is asking for is "may I
// take the fast leg", and every negative answer — the token absent, the server
// too old, the handshake refused — has the same correct response, which is to
// take the leg this client has always taken. Propagating the error instead
// would newly fail `bd list` against a server it works against today, since the
// baseline exemption means today's walk never asks for a handshake at all. The
// error is not lost: the walk's own first request meets the same server, and
// whatever it says — a transport failure, a wrong-project refusal — reaches the
// caller from there.
func (s *Store) servesListSort(ctx context.Context) bool {
snap, err := s.snapshot(ctx)
if err != nil || snap == nil {
return false
}
return slices.Contains(snap.Capabilities, wire.CapListSort)
}
// listSortPushdownEligible reports whether req's display order is one
// listIssues can serve directly.
//
// The operation's `sort` enum is closed to the two keyset orders this client
// names wireListSort and flaglessListSort ("created" and "priority") — the
// seven other `bd list --sort` orders have no keyset predicate the server can
// page, so the spec does not publish them here at all; sending one anyway
// would meet the same `invalid_value` 400 a stale client earns for a value
// outside the enum.
//
// listIssues ALSO publishes no `reverse` parameter — that member exists only
// on GET /v0/beads/issues:query, a different operation with a different
// vocabulary (nine orders, used for the Go-side sort case up above, not a
// keyset order at all). A pushdown request naming `reverse` would not be
// answered backwards; it would be refused outright as a parameter this
// operation does not know, since listIssues never reads one. So a reversed
// request of any order, including the two eligible ones, has to come home
// over the walk and be re-sorted client-side in sortListRows — the walk and
// the early-stop leg above both already gate on !req.Reverse for the same
// reason.
func listSortPushdownEligible(req issueops.ListRequest) bool {
if req.Reverse {
return false
}
switch req.SortBy {
case "", wireListSort, flaglessListSort:
return true
default:
return false
}
}
// sortedPage answers a bounded request in the caller's own order with ONE
// request, by naming that order on the wire.
//
// What this fixes is not the sort — the client could always re-sort what it
// fetched — but the ROW SET: which rows survive the caller's limit is now
// decided under the caller's order, by the same reader a local `bd list` runs,
// instead of by fetching every row the filter matches. The page carries no
// cursor and needs none: there is exactly one request, and the server's
// has_more IS the caller's, because unlike the walk this leg discards nothing
// the server counted.
//
// sortListRows still runs. It is O(n log n) over the page rather than over the
// result set, and keeping it leaves the display order self-authoritative
// against tie-semantics drift in a server one version away — which is the half
// of an order a re-sort CAN repair.
func (s *Store) sortedPage(ctx context.Context, params url.Values, req issueops.ListRequest, limit int) (issueops.IssuePage, error) {
page := url.Values{}
for key, values := range params {
page[key] = values
}
sortBy := req.SortBy
if sortBy == "" {
sortBy = flaglessListSort
}
page.Set("sort", sortBy)
// No `reverse` here: listIssues publishes no such parameter (that member
// belongs only to GET /v0/beads/issues:query's nine-order vocabulary), and
// listSortPushdownEligible already refused this call before it got here if
// req.Reverse were set. Sending it — even spelled false — would meet this
// operation's unknown-parameter refusal, since the handler never reads a
// `reverse` key at all.
// The cap, spelled as the storage layer spells it: LIMIT min(Limit,
// MaxRows+1). The overage row is what proves the cap fired, and asking for
// no more than one past it is what stops the cap from bounding a page it
// was never meant to bound. Under a cap at or above the limit the request
// is the limit's own, so the cap CANNOT fire — which is local semantics
// (the window could not have exceeded it) and the L15 narrowing.
//
// That equivalence holds because a capped GO-SIDE sort never reaches this
// function: for those keys workapi.SQLLimit sends 0 rather than the limit,
// so the local window is MaxRows+1 and the cap CAN fire under a limit
// beneath it. walkIssues' gate is what keeps them on the walk, which is
// the leg that models that unbounded window.
size := limit
if req.MaxRows > 0 && req.MaxRows+1 < size {
size = req.MaxRows + 1
}
page.Set("limit", strconv.Itoa(size))
var body apigen.IssuesPage
if err := s.dispatch(ctx, listRequest(page), &body); err != nil {
return issueops.IssuePage{}, err
}
if req.MaxRows > 0 && len(body.Items) > req.MaxRows {
return issueops.IssuePage{}, &storageops.ErrTooManyRows{Found: len(body.Items), Cap: req.MaxRows, Source: req.MaxRowsSource}
}
rows := wireRows(body.Items, req.Brief)
sortListRows(rows, req.SortBy, req.Reverse)
return issueops.IssuePage{Items: rows, HasMore: body.HasMore}, nil
}
// fetchIssuePages walks the created-order wire, keeping the rows keep admits.
//
// want is how many KEPT rows are enough to answer, or 0 for "every one of
// them". It over-fetches by one, exactly as the store-backed reader asks its
// query for one row past the page: the extra row IS the has-more verdict, and
// asking the wire for its own has_more instead would answer about the rows the
// SERVER hid rather than the ones the caller's page does.
//
// brief travels down here rather than being applied to the walk's answer because
// this is where the rows are lifted, and wireRows is the one place that knows
// how to mark a projected one. It sits next to params rather than beside want
// and maxRows deliberately: it is the only bool in the list, so it has no
// same-typed neighbor to be transposed with.
func (s *Store) fetchIssuePages(
ctx context.Context,
params url.Values,
brief bool,
want, maxRows int,
maxRowsSource string,
keep func(*types.IssueWithCounts) bool,
) ([]*types.IssueWithCounts, error) {
page := url.Values{}
for key, values := range params {
page[key] = values
}
var (
kept []*types.IssueWithCounts
fetched int
cursor string
)
for {
size := walkPageSize
if want > 0 {
if remaining := want + 1 - len(kept); remaining < size {
size = remaining
}
}
if maxRows > 0 {
// Mirrors the storage layer's LIMIT MaxRows+1 overage probe: one
// row past the cap is what proves the cap fired, and never more
// than one, because the cap bounds WIRE ROWS FETCHED (D12).
if allowed := maxRows + 1 - fetched; allowed < size {
size = allowed
}
}
if size <= 0 {
break
}
page.Set("limit", strconv.Itoa(size))
if cursor != "" {
page.Set("cursor", cursor)
}
var body apigen.IssuesPage
if err := s.dispatch(ctx, listRequest(page), &body); err != nil {
return nil, err
}
fetched += len(body.Items)
if maxRows > 0 && fetched > maxRows {
return nil, &storageops.ErrTooManyRows{Found: fetched, Cap: maxRows, Source: maxRowsSource}
}
for _, row := range wireRows(body.Items, brief) {
if keep == nil || keep(row) {
kept = append(kept, row)
}
}
if want > 0 && len(kept) > want {
break
}
// next_cursor is present if and only if has_more WITHIN THE UNSORTED
// FAMILY, which is the scope the document now states the biconditional
// at: a page the server ordered by a `sort` reports a truthful has_more
// and carries no cursor at all, because a cursor is a position in the
// created order and that page is not in it.
//
// THIS FUNCTION IS ALWAYS INSIDE THAT FAMILY, and it is the reason the
// stop below is still a correctness check rather than an early exit
// from a shape the server ships on purpose: the `sort` key is written
// by sortedPage and by nothing else, and sortedPage sends one request
// and reads no cursor. So on every page this walk can receive, a claim
// of more with no position named is a server this client cannot page,
// and it stops rather than re-issuing the same request forever.
if !body.HasMore || body.NextCursor == nil || *body.NextCursor == "" {
break
}
cursor = *body.NextCursor
}
if kept == nil {
kept = []*types.IssueWithCounts{}
}
return kept, nil
}
func listRequest(query url.Values) wire.Request {
return wire.Request{
Op: wire.OpListIssues,
Method: http.MethodGet,
Path: wire.PathIssues,
Query: query,
}
}
// keysetFilter turns a caller-supplied position into the discard rule of the
// skip-forward walk, or nil when the request carries none.
//
// AfterCreatedAt ALONE decides whether there is a position, which is the
// contract's rule (issueops.ListRequest) and the local predicate's
// (sqlbuild.BuildIssueFilterClauses). An AfterID or AfterPriority with no instant
// is ignored there, so it is ignored here — read as a position at the zero
// instant instead, it would discard every row, since every row is after it.
//
// The position is a PAIR and both halves matter: rows older than its timestamp
// are kept, and rows sharing that timestamp are kept only when their id sorts
// after it. A filter that compared the timestamp alone would drop the
// same-instant row, which is exactly how a keyset page loses records.
//
// AfterPriority extends the pair to the (priority ASC, created_at DESC, id ASC)
// order, and it is decided FIRST: a row at another priority is past the
// position exactly when its priority is the higher-numbered one, whatever its
// instant, and only a row at the position's own priority falls through to the
// pair. That nesting is sqlbuild.KeysetPriorityCreatedAtIDPredicate's, for its
// reason: the pair alone would re-deliver every higher-priority row created
// before the position and drop every lower-priority row created after it.
func keysetFilter(req issueops.ListRequest) func(*types.IssueWithCounts) bool {
if req.AfterCreatedAt == nil {
return nil
}
at, after := *req.AfterCreatedAt, req.AfterID
byPriority, atPriority := req.AfterPriority != nil, 0
if byPriority {
atPriority = *req.AfterPriority
}
return func(row *types.IssueWithCounts) bool {
if row == nil || row.Issue == nil {
return false
}
switch {
case byPriority && row.Priority != atPriority:
return row.Priority > atPriority
case row.CreatedAt.After(at):
return false
case row.CreatedAt.Equal(at) && row.ID <= after:
return false
default:
return true
}
}
}

View file

@ -0,0 +1,122 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/memories.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"strings"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
"github.com/steveyegge/beads/memoryops"
)
// httpMemories serves memoryops.Memories from the four memory operations
// (design D8 row 15).
//
// The role is one plane and one interface, so the accessor cannot be flipped by
// halves: the two writes this bead owns arrive with the two reads that share
// their vocabulary, and all four go through the same key rules.
//
// THE MISS IS A RESULT, NOT AN ERROR. memoryops deliberately declares no
// ErrNotFound: a recall or a forget that found nothing answers Found false with
// a nil error. The wire spells the same miss as a 404, which the problem mapper
// turns into issueops.ErrNotFound — so the one piece of real translation in this
// file is turning that back into the role's own answer. Getting it wrong would
// make `bd recall` of an unknown key an error where every other backend prints
// "not found".
type httpMemories struct {
store *Store
wire WriteWire
}
var _ memoryops.Memories = (*httpMemories)(nil)
// Remember stores one memory. An ABSENT key asks the server to derive one from
// the content, which is why the wire member is a pointer: an empty string is not
// the same request as an omitted member, and the derived key comes back in the
// result so the caller learns where the memory landed.
func (m *httpMemories) Remember(ctx context.Context, req memoryops.RememberRequest) (memoryops.RememberResult, error) {
if strings.TrimSpace(req.Content) == "" {
return memoryops.RememberResult{}, invalid("content is required")
}
body := apigen.RememberRequest{Content: req.Content}
if req.Key != "" {
key := req.Key
body.Key = &key
}
res, err := m.wire.RememberMemory(ctx, body)
if err != nil {
return memoryops.RememberResult{}, err
}
return memoryops.RememberResult{Key: res.Key, Value: res.Value, Replaced: res.Replaced}, nil
}
// Recall reads one memory.
func (m *httpMemories) Recall(ctx context.Context, req memoryops.RecallRequest) (memoryops.RecallResult, error) {
if err := requireMemoryKey(req.Key); err != nil {
return memoryops.RecallResult{}, err
}
res, err := m.wire.RecallMemory(ctx, req.Key)
if errors.Is(err, issueops.ErrNotFound) {
return memoryops.RecallResult{Key: req.Key}, nil
}
if err != nil {
return memoryops.RecallResult{}, err
}
// Found is Value != "": the role conflates a stored empty string with an
// absent memory, and so does the wire, which 404s the same row.
return memoryops.RecallResult{Key: req.Key, Value: res.Value, Found: res.Value != ""}, nil
}
// Forget removes one memory and reports the value it removed.
func (m *httpMemories) Forget(ctx context.Context, req memoryops.ForgetRequest) (memoryops.ForgetResult, error) {
if err := requireMemoryKey(req.Key); err != nil {
return memoryops.ForgetResult{}, err
}
res, err := m.wire.ForgetMemory(ctx, req.Key)
if errors.Is(err, issueops.ErrNotFound) {
// Nothing was stored under the key, and nothing was deleted. A result,
// not an error: forgetting what was never remembered is the state the
// caller asked for.
return memoryops.ForgetResult{Key: req.Key}, nil
}
if err != nil {
return memoryops.ForgetResult{}, err
}
return memoryops.ForgetResult{Key: req.Key, Value: res.Value, Found: true}, nil
}
// List enumerates the memory plane, narrowed by Search.
//
// The folding is the ROLE's, so it happens server-side: the raw term goes on the
// wire as `search` and the server's own role lowercases both sides. Folding it
// here as well would be a second implementation of a rule that has one.
func (m *httpMemories) List(ctx context.Context, req memoryops.ListRequest) (memoryops.ListResult, error) {
page, err := m.wire.ListMemories(ctx, req.Search)
if err != nil {
return memoryops.ListResult{}, err
}
// Empty map, never nil: a caller ranges over it without a nil check, and
// "the plane is empty" is not something to spell as an absent answer.
out := make(map[string]string, len(page.Items))
for _, memory := range page.Items {
out[memory.Key] = memory.Value
}
return memoryops.ListResult{Memories: out}, nil
}
// requireMemoryKey applies the role's trim rule before a key becomes a path.
//
// The server refuses a blank key on these two operations as well, but as a 400
// alongside the 404 that means "no such memory" — and a caller cannot act on the
// difference if the client never made it. Refusing here keeps the role's
// ErrValidation promise and keeps a request that cannot succeed off the wire.
func requireMemoryKey(key string) error {
if strings.TrimSpace(key) == "" {
return invalid("memory key is required")
}
return nil
}

View file

@ -0,0 +1,140 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/metadata.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"github.com/steveyegge/beads/internal/httpclient/wire"
)
// LocalMetadataFileName holds the per-user local metadata this backend answers
// from disk instead of from the server (design D3/D4).
const LocalMetadataFileName = "http_local_metadata.json"
// localMetadata is the per-user state file beside the activation sidecar. It is
// small, rewritten whole, and 0600 like the sidecar.
type localMetadata struct {
path string
mu sync.Mutex
}
func newLocalMetadata(beadsDir string) *localMetadata {
if beadsDir == "" {
return nil
}
return &localMetadata{path: filepath.Join(beadsDir, LocalMetadataFileName)}
}
func (l *localMetadata) load() (map[string]string, error) {
data, err := os.ReadFile(l.path) // #nosec G304 - controlled path
if os.IsNotExist(err) {
return map[string]string{}, nil
}
if err != nil {
return nil, fmt.Errorf("reading %s: %w", LocalMetadataFileName, err)
}
m := map[string]string{}
if err := json.Unmarshal(data, &m); err != nil {
return nil, fmt.Errorf("parsing %s: %w", LocalMetadataFileName, err)
}
return m, nil
}
func (l *localMetadata) get(key string) (string, error) {
l.mu.Lock()
defer l.mu.Unlock()
m, err := l.load()
if err != nil {
return "", err
}
return m[key], nil
}
func (l *localMetadata) set(key, value string) error {
l.mu.Lock()
defer l.mu.Unlock()
m, err := l.load()
if err != nil {
return err
}
m[key] = value
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
return fmt.Errorf("marshaling %s: %w", LocalMetadataFileName, err)
}
if err := os.WriteFile(l.path, data, 0o600); err != nil {
return fmt.Errorf("writing %s: %w", LocalMetadataFileName, err)
}
return nil
}
// GetLocalMetadata is served from the per-user state file, not from the server
// (design D4, "Tips GetLocalMetadata/SetLocalMetadata"): tips-shown timestamps
// are per-user UI state and storing them server-side would be the wrong scope.
// A missing key is ("", nil), matching every other backend.
func (s *Store) GetLocalMetadata(_ context.Context, key string) (string, error) {
if s.local == nil {
return "", nil
}
return s.local.get(key)
}
// SetLocalMetadata writes the same per-user file. It must not error on a store
// with nowhere to write — cmd/bd defers a tip write to PersistentPostRunE and
// treats any error there as fatal (design D3), and an ephemeral `--server-url`
// workspace has no durable .beads to hold the file. Tips are suppressed for
// those invocations, so dropping the write loses nothing a user asked for.
func (s *Store) SetLocalMetadata(_ context.Context, key, value string) error {
if s.local == nil {
return nil
}
return s.local.set(key, value)
}
// GetMetadata answers the workspace-identity probe from the cached handshake
// (design D4, "validateWorkspaceIdentity"). Serving `_project_id` is what makes
// wrong-server protection actually enforce: cmd/bd swallows a store error here
// into "skip validation", so a refusal would silently disarm the check.
//
// Before the handshake there is nothing to compare, and ("", nil) is the
// documented "new or pre-identity database" answer that skips validation
// without claiming a mismatch. Every other key refuses: no wire operation
// exposes the metadata table, and answering "" for an unknown key would be a
// dropped read dressed as an empty one.
//
// A wrong-server handshake is the one error that must NOT collapse to that
// benign skip (ga-b8ddd.11, Option C): the mismatch carries the id the server
// actually owns, so handing that Got value back is what lets cmd/bd's
// validateWorkspaceIdentity compare it against metadata.json and FIRE the
// identity check — the write is refused, exit 1. What this path does NOT surface
// is the wire ProjectMismatchError's own text: only the Got id survives this
// method, so the server URL, database, repo root and recovery clause it carries
// are discarded here. cmd/bd renders the http-appropriate recovery separately,
// off the RemoteWorkspaceBackend capability (ga-b8ddd.16), rather than from
// this returned string. Any other handshake failure has no identity to offer,
// so it stays the ("", nil) "nothing to compare" skip the caller already treats
// as benign.
func (s *Store) GetMetadata(ctx context.Context, key string) (string, error) {
if key != "_project_id" {
return "", s.unsupported("GetMetadata")
}
snap, err := s.snapshot(ctx)
if err != nil {
var mismatch *wire.ProjectMismatchError
if errors.As(err, &mismatch) {
return mismatch.Got, nil
}
return "", nil
}
if snap == nil {
return "", nil
}
return snap.ProjectId, nil
}

View file

@ -0,0 +1,127 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/metadatacas.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"encoding/json"
"strings"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
)
// httpMetadataCAS serves issueops.MetadataCAS from the compareAndSetMetadata
// custom method — the conditional single-key write every coordination protocol
// over the metadata plane is built from.
//
// The MAPPING IS TOTAL: all five members of the role's request have a wire
// member or a path, and both members of its result are published, so nothing
// here refuses on shape and the ledger carries no W- row for this operation.
// What made the port a decision rather than a transcription is the two places
// this operation's shape is unlike every other write on this seam.
//
// A LOST RACE IS A 200. Every other write learns a refusal from a status code;
// here `swapped: false` with the value that refused the swap is the ANSWER, and
// the role says the same thing in the same words — "a mismatch is an answer,
// not a failure". So the verdict travels through the success path and nothing
// in the problem mapper knows about it. There is no 409 to classify, and a
// client that dispatched on the status code would report a lost race as a won
// one.
//
// ABSENCE IS A VALUE, on all three of `expected`, `value` and `current`. An
// omitted member means the key is ABSENT on that side of the transition — which
// is what makes a first-writer-wins acquire (nil → value) and a release
// (value → nil) expressible — while a member present holding `null` means the
// key exists and holds null. The two states are different requests and
// different answers, so nothing on this path may collapse one into the other:
// the request members are pointers on the role's side and `omitempty` raw
// messages on the wire's, and the response's `current` is a BARE
// json.RawMessage rather than a pointer precisely so a present null survives
// the decode (see the server's metadataCASWireValue).
//
// WHAT IS NOT DECIDED HERE, deliberately: the metadata-key syntax, the
// canonical equality rule, and which transitions write. All three are the
// ROLE's, the server routes this request through the same issueops.MetadataCAS
// a local workspace uses, and a second copy of any of them in this client would
// be a second definition. They come back as issueops.ErrValidation, which is
// what the role's contract promises.
type httpMetadataCAS struct {
store *Store
wire WriteWire
}
var _ issueops.MetadataCAS = (*httpMetadataCAS)(nil)
// CompareAndSetKey dials POST /v0/beads/issues/{id}:casMetadata.
func (c *httpMetadataCAS) CompareAndSetKey(ctx context.Context, req issueops.CompareAndSetKeyRequest) (issueops.CompareAndSetKeyResult, error) {
if err := requireActor(req.Actor); err != nil {
return issueops.CompareAndSetKeyResult{}, err
}
if err := requireID("issue id", req.IssueID); err != nil {
return issueops.CompareAndSetKeyResult{}, err
}
// The KEY's emptiness is checked here and its SYNTAX is not, and the split
// is the same one requireID makes: an empty key would be sent as a body
// member the server refuses by name, which is a round trip to be told what
// the role's own contract already calls invalid, while the syntax is the
// workspace's rule and belongs to the role that owns the metadata plane.
if strings.TrimSpace(req.Key) == "" {
return issueops.CompareAndSetKeyResult{}, invalid("metadata key is required")
}
expected, err := casValue("Expected", req.Expected)
if err != nil {
return issueops.CompareAndSetKeyResult{}, err
}
value, err := casValue("Value", req.Value)
if err != nil {
return issueops.CompareAndSetKeyResult{}, err
}
res, err := c.wire.CompareAndSetMetadata(ctx, req.IssueID, apigen.CompareAndSetMetadataRequest{
Actor: req.Actor, Key: req.Key, Expected: expected, Value: value,
})
if err != nil {
return issueops.CompareAndSetKeyResult{}, err
}
return issueops.CompareAndSetKeyResult{Swapped: res.Swapped, Current: casCurrent(res.Current)}, nil
}
// casValue projects one side of the transition onto its wire member.
//
// NIL STAYS ABSENT, which is the whole of the mapping and the reason it is a
// function: the role spells "the key is absent on this side" as a nil pointer
// and the wire spells it as an omitted member, and `omitempty` omits exactly
// the empty raw message. A present value is COPIED rather than aliased — the
// role promises implementations never write through a caller's request, and
// handing these bytes to a marshaler is the kind of borrow that becomes a write
// when a helper is added.
//
// An EMPTY value is refused rather than sent. It is not a JSON value at all, so
// `omitempty` would silently turn it into the absent member — which is the
// opposite request — and the role calls it ErrValidation too.
func casValue(member string, value *json.RawMessage) (apigen.MetadataValue, error) {
if value == nil {
return nil, nil
}
if err := requireJSON(member, *value); err != nil {
return nil, err
}
return apigen.MetadataValue(append([]byte(nil), (*value)...)), nil
}
// casCurrent projects the answer's current value back onto the role's optional
// one. nil stays nil, so an absent member is an ABSENT key rather than a null
// one — the same distinction the request side makes, answered the same way.
//
// The bytes are COPIED for the reason a caller needs them to be: Current is fed
// back as the next Expected, and a window onto a decoded response body is not
// something a retry loop should be holding between requests.
func casCurrent(current apigen.MetadataValue) *json.RawMessage {
if current == nil {
return nil
}
value := json.RawMessage(append([]byte(nil), current...))
return &value
}

View file

@ -0,0 +1,283 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/metadatacas_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"encoding/json"
"errors"
"reflect"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
)
// The compare-and-set role's own gates.
//
// Two things about this operation are unlike every other write on this seam,
// and both are asserted here rather than left to the served tier: a LOST RACE
// IS A 200, so the verdict is read out of the body of a success; and ABSENCE IS
// A VALUE on three members — `expected`, `value` and `current` — where an
// omitted member means "the key is absent on that side" and a member present
// holding `null` means the key exists and holds null.
func casRole(t *testing.T, w *stubWire) issueops.MetadataCAS {
t.Helper()
cas, err := stubStore(t, w).MetadataCAS()
if err != nil {
t.Fatalf("MetadataCAS(): %v", err)
}
return cas
}
func raw(s string) *json.RawMessage {
value := json.RawMessage(s)
return &value
}
// TestMetadataCASSendsTheTransitionAsAPair is the request half: Expected is the
// value before and Value the value after, and nil on either side means the key
// is ABSENT there — so a first-writer-wins acquire omits `expected` and a
// release omits `value`.
//
// A serializer that dropped an empty member would turn a conditional write into
// a delete, which is the trap the operation's own description opens with.
func TestMetadataCASSendsTheTransitionAsAPair(t *testing.T) {
tests := []struct {
name string
request issueops.CompareAndSetKeyRequest
wantExpected, wantValue string
}{
{
name: "a first-writer-wins acquire omits expected",
request: issueops.CompareAndSetKeyRequest{
Actor: "win44", IssueID: "bd-1", Key: "gc.lease", Value: raw(`"win44"`),
},
wantExpected: "", wantValue: `"win44"`,
},
{
name: "a release omits value",
request: issueops.CompareAndSetKeyRequest{
Actor: "win44", IssueID: "bd-1", Key: "gc.lease", Expected: raw(`"win44"`),
},
wantExpected: `"win44"`, wantValue: "",
},
{
name: "a hand-off carries both",
request: issueops.CompareAndSetKeyRequest{
Actor: "win44", IssueID: "bd-1", Key: "gc.lease",
Expected: raw(`"win30"`), Value: raw(`"win44"`),
},
wantExpected: `"win30"`, wantValue: `"win44"`,
},
{
name: "a stored null is a PRESENT value on both sides",
request: issueops.CompareAndSetKeyRequest{
Actor: "win44", IssueID: "bd-1", Key: "gc.lease",
Expected: raw(`null`), Value: raw(`null`),
},
wantExpected: `null`, wantValue: `null`,
},
{
// A NUMBER TRAVELS AS THE CALLER'S OWN LITERAL, and on THIS
// operation the stakes are a changed verdict rather than a changed
// value: equality here is canonical but numbers compare as their
// source literal, so `1` and `1.0` do NOT match. A client that
// decoded either side through `any` and re-encoded it would send
// `1` for a caller who wrote `1.0` — and the swap would land where
// the role would have refused it, or be refused where the role
// would have landed it.
//
// The big integer is the second half of the same rule: past 2^53 a
// double cannot hold the value at all, so a re-encode hands the
// server a token NEAR the caller's that is not it.
name: "numbers travel as the caller's own literal, on both sides",
request: issueops.CompareAndSetKeyRequest{
Actor: "win44", IssueID: "bd-1", Key: "gc.epoch",
Expected: raw(`1.0`), Value: raw(`9007199254740993`),
},
wantExpected: `1.0`, wantValue: `9007199254740993`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
w := &stubWire{cas: &apigen.CompareAndSetMetadataResponse{Swapped: true}}
if _, err := casRole(t, w).CompareAndSetKey(t.Context(), test.request); err != nil {
t.Fatalf("CompareAndSetKey: %v", err)
}
if got := w.lastCAS.Actor; got != test.request.Actor {
t.Errorf("actor = %q, want %q", got, test.request.Actor)
}
if got := w.lastCAS.Key; got != test.request.Key {
t.Errorf("key = %q, want %q", got, test.request.Key)
}
// Through the marshaler: `omitempty` on a json.RawMessage omits the
// EMPTY one, and what the server reads is the member set of the
// encoded body, not the Go value.
encoded, err := json.Marshal(w.lastCAS)
if err != nil {
t.Fatalf("marshal the request: %v", err)
}
var body map[string]json.RawMessage
if err := json.Unmarshal(encoded, &body); err != nil {
t.Fatalf("re-read the request: %v", err)
}
for member, want := range map[string]string{"expected": test.wantExpected, "value": test.wantValue} {
got, present := body[member]
switch {
case want == "" && present:
t.Errorf("the request carries %q = %s; a nil side of the transition is an ABSENT member", member, got)
case want != "" && !present:
t.Errorf("the request omits %q; omitting it means the key is absent there, which is a different request", member)
case want != "" && string(got) != want:
t.Errorf("%s = %s, want %s", member, got, want)
}
}
})
}
}
// TestMetadataCASReadsTheVerdictOutOfASuccess is the response half, and the
// reason this role could not be wired by analogy with its neighbors: a lost
// race is a 200 carrying `swapped: false` and the value that refused the swap.
// A client that dispatched on the status code would report a lost race as a
// won one.
func TestMetadataCASReadsTheVerdictOutOfASuccess(t *testing.T) {
tests := []struct {
name string
response apigen.CompareAndSetMetadataResponse
wantSwap bool
want string
wantNil bool
}{
{
name: "a lost race is an answer, not a failure",
response: apigen.CompareAndSetMetadataResponse{Swapped: false, Current: apigen.MetadataValue(`"win30"`)},
wantSwap: false, want: `"win30"`,
},
{
name: "a landed swap reports the value the row now holds",
response: apigen.CompareAndSetMetadataResponse{Swapped: true, Current: apigen.MetadataValue(`"win44"`)},
wantSwap: true, want: `"win44"`,
},
{
name: "an absent current is an ABSENT key",
response: apigen.CompareAndSetMetadataResponse{Swapped: true},
wantSwap: true, wantNil: true,
},
{
name: "a present null is a value the key HOLDS",
response: apigen.CompareAndSetMetadataResponse{Swapped: false, Current: apigen.MetadataValue(`null`)},
wantSwap: false, want: `null`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
response := test.response
w := &stubWire{cas: &response}
result, err := casRole(t, w).CompareAndSetKey(t.Context(), issueops.CompareAndSetKeyRequest{
Actor: "win44", IssueID: "bd-1", Key: "gc.lease", Value: raw(`"win44"`),
})
if err != nil {
t.Fatalf("CompareAndSetKey: %v", err)
}
if result.Swapped != test.wantSwap {
t.Errorf("Swapped = %t, want %t", result.Swapped, test.wantSwap)
}
switch {
case test.wantNil && result.Current != nil:
t.Fatalf("Current = %s, want nil: an omitted member is an ABSENT key", *result.Current)
case !test.wantNil && result.Current == nil:
t.Fatalf("Current = nil, want %s: a client that cannot tell a present null from an absent key cannot converge on a null-valued key", test.want)
case !test.wantNil && string(*result.Current) != test.want:
t.Errorf("Current = %s, want %s", *result.Current, test.want)
}
})
}
}
// TestMetadataCASRefusesAnUnusableRequestBeforeDialing covers the two refusals
// this layer owns rather than leaving to the server.
//
// Actor and issue id are the shared write rules — an empty id would join to the
// COLLECTION path and turn an operation on one resource into one on all of them
// — and a malformed JSON value cannot go on a JSON wire at all, so it would
// fail inside json.Marshal as a transport fault where the role's contract
// promises a deterministic validation failure.
//
// The KEY's syntax is deliberately NOT decided here: it is the workspace's own
// metadata-key rule, the server's role applies it inside the refusing
// transaction, and a second copy of it in this client would be a second
// definition of which keys a workspace may hold.
func TestMetadataCASRefusesAnUnusableRequestBeforeDialing(t *testing.T) {
for name, request := range map[string]issueops.CompareAndSetKeyRequest{
"empty actor": {IssueID: "bd-1", Key: "gc.lease"},
"blank actor": {Actor: " ", IssueID: "bd-1", Key: "gc.lease"},
"empty issue id": {Actor: "win44", Key: "gc.lease"},
"malformed expected": {
Actor: "win44", IssueID: "bd-1", Key: "gc.lease", Expected: raw(`{`),
},
"malformed value": {
Actor: "win44", IssueID: "bd-1", Key: "gc.lease", Value: raw(`nope`),
},
"an empty expected is not the empty string": {
Actor: "win44", IssueID: "bd-1", Key: "gc.lease", Expected: raw(``),
},
} {
t.Run(name, func(t *testing.T) {
w := &stubWire{cas: &apigen.CompareAndSetMetadataResponse{Swapped: true}}
result, err := casRole(t, w).CompareAndSetKey(t.Context(), request)
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("CompareAndSetKey(%s) = %v, want ErrValidation", name, err)
}
if result.Swapped {
t.Error("a refused request reported Swapped")
}
if len(w.calls) != 0 {
t.Errorf("the refused request dialed %v", w.calls)
}
})
}
}
// TestMetadataCASDoesNotWriteThroughTheCallerRequest holds the promise every
// role here makes and this one states twice: "Implementations never mutate
// caller-owned request values: the two raw messages are read, never written
// through."
//
// The request travels as bytes into a marshaler, which is exactly the kind of
// borrow that becomes a write when a helper is added later.
func TestMetadataCASDoesNotWriteThroughTheCallerRequest(t *testing.T) {
expected, value := raw(`"win30"`), raw(`"win44"`)
request := issueops.CompareAndSetKeyRequest{
Actor: "win44", IssueID: "bd-1", Key: "gc.lease", Expected: expected, Value: value,
}
before := reflect.DeepEqual(request, request)
if !before {
t.Fatal("the request is not comparable to itself")
}
w := &stubWire{cas: &apigen.CompareAndSetMetadataResponse{Swapped: true, Current: apigen.MetadataValue(`"win44"`)}}
result, err := casRole(t, w).CompareAndSetKey(t.Context(), request)
if err != nil {
t.Fatalf("CompareAndSetKey: %v", err)
}
if string(*expected) != `"win30"` || string(*value) != `"win44"` {
t.Errorf("the caller's values were written through: expected = %s, value = %s", *expected, *value)
}
if request.Expected != expected || request.Value != value {
t.Error("the request's own pointers were replaced")
}
// And the answer is detached from the transport's buffer for the same
// reason: a caller feeding Current back as the next Expected must not hold
// a window onto a response body the client may reuse.
if result.Current == nil {
t.Fatal("Current is nil")
}
if &(*result.Current)[0] == &w.cas.Current[0] {
t.Error("Current aliases the response body rather than copying it")
}
}

View file

@ -0,0 +1,37 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/offrole.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
// The off-role raw methods design D8 keeps off the unsupported allowlist. They
// are not role accessors — cmd/bd still calls them directly at tip — but each
// has a v0 operation behind it, so refusing them would refuse a command the
// wire can serve. Like the role accessors, they are hand-written and move OUT of
// this file to sit beside the surface they serve the moment their bead wires
// them (precedent resolve.go/bridge.go/vocabulary.go).
//
// This file is now a TOMBSTONE: it holds no methods. It stays because the
// retirement path is worth writing down where it happened. (There is no skip
// list to keep in step: unsupportedgen derives the shell from the methods
// declared on *Store, so a read that moved out of here needed only a
// regeneration.)
//
// The reads this file used to hold are SERVED, each beside the surface it
// belongs to: the four getIssue riders — GetLabels, GetDependenciesWithMetadata,
// GetDependentsWithMetadata and GetIssueComments — in detail_reads.go, and the
// anchored GetDependencyRecords in roles_graph.go beside the EdgeReader role it
// shares its operation with (ga-b8ddd.30). The verbatim-row question their flip
// waited on — whether the wire surfaces unresolved depends_on_id rows the
// GH#5005 `bd dep remove` guard must see — was answered by the dual run in
// served_detail_reads_test.go: it does, so there is no L17 degradation to
// ledger.
//
// The earlier tenants left the same way: SearchIssues and GetConfig to
// resolve.go with the id-resolution probes, the ready bridge and the raw
// GetIssue probe to bridge.go, and the settings, statistics and vocabulary reads
// to vocabulary.go.
//
// Everything NOT here and not in accessors.go, store.go or metadata.go is on the
// generated shell and refuses permanently — including the batch and unanchored
// variants (GetLabelsForIssues, GetDependencyRecordsForIssues, GetDependencies,
// GetDependents, GetNextChildID) and the VersionReconciler, Bootstrapper and
// InitVerifier accessors.

View file

@ -0,0 +1,123 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/order.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"cmp"
"slices"
"strings"
"github.com/steveyegge/beads/internal/storage/sqlbuild"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
// The client-side display order (ledger row L2).
//
// A local list is ordered TWICE and the second pass is not redundant: the query
// renders sqlbuild's ORDER BY, and the shared page epilogue then stable-sorts
// the rows it returned by the single display key. The two disagree on purpose —
// the SQL clause carries the tie-break tail (created DESC, id ASC) and the
// epilogue carries the orders SQL cannot express — so an order applied here has
// to be BOTH of them, in that sequence, or the tie order comes out different
// from a local run of the same request.
//
// sqlbuild.Less is imported rather than reimplemented. It is already the
// Go-side mirror of that ORDER BY — the storage layer merges the issue and wisp
// planes with it — so borrowing it is what makes "the client comparator and the
// SQL order cannot drift" true by construction instead of by a golden file.
// Only the epilogue's own comparator is written out below, because it lives in
// internal/workapi, which depguard denies to this package.
// sortListRows applies the display order a ListRequest asked for to a page the
// wire returned in created order.
func sortListRows(rows []*types.IssueWithCounts, sortBy string, reverse bool) {
slices.SortStableFunc(rows, func(a, b *types.IssueWithCounts) int {
ai, bi := rowIssue(a), rowIssue(b)
switch {
case ai == nil && bi == nil:
return 0
case ai == nil:
return 1
case bi == nil:
return -1
}
switch {
case sqlbuild.Less(ai, bi, sortBy, reverse):
return -1
case sqlbuild.Less(bi, ai, sortBy, reverse):
return 1
default:
return 0
}
})
if sortBy == "" {
// The epilogue leaves an unnamed order alone, so the SQL order above is
// the whole of it — which is the flagless default no one names and
// everyone sees.
return
}
slices.SortStableFunc(rows, func(a, b *types.IssueWithCounts) int {
ai, bi := rowIssue(a), rowIssue(b)
switch {
case ai == nil && bi == nil:
return 0
case ai == nil:
return 1
case bi == nil:
return -1
}
r := compareIssuesBy(ai, bi, sortBy)
if reverse {
return -r
}
return r
})
}
func rowIssue(row *types.IssueWithCounts) *types.Issue {
if row == nil {
return nil
}
return row.Issue
}
// compareIssuesBy orders two issues by one of `bd list --sort`'s fields. An
// unknown field compares equal, which leaves the underlying order intact.
//
// It is a copy of internal/workapi.CompareIssuesBy, kept honest by
// TestCompareIssuesByMatchesTheSharedComparator rather than by review: the
// depguard rule that keeps the work-query builders out of this package takes
// the comparator with them, and a display order that disagreed with the local
// one by a single tie would show up as a reordered page and nothing else.
func compareIssuesBy(a, b *types.Issue, sortBy string) int {
switch sortBy {
case "priority":
return cmp.Compare(a.Priority, b.Priority)
case "created":
return b.CreatedAt.Compare(a.CreatedAt)
case "updated":
return b.UpdatedAt.Compare(a.UpdatedAt)
case "closed":
switch {
case a.ClosedAt == nil && b.ClosedAt == nil:
return 0
case a.ClosedAt == nil:
return 1
case b.ClosedAt == nil:
return -1
}
return b.ClosedAt.Compare(*a.ClosedAt)
case "status":
return cmp.Compare(a.Status, b.Status)
case "id":
return utils.NaturalCompareIDs(a.ID, b.ID)
case "title":
return cmp.Compare(strings.ToLower(a.Title), strings.ToLower(b.Title))
case "type":
return cmp.Compare(a.IssueType, b.IssueType)
case "assignee":
return cmp.Compare(a.Assignee, b.Assignee)
}
return 0
}

View file

@ -0,0 +1,6 @@
//go:build cgo && !race
package httpclient
// raceEnabled is false in non-race builds; see race_detector_on_test.go.
const raceEnabled = false

View file

@ -0,0 +1,13 @@
//go:build cgo && race
package httpclient
// raceEnabled reports whether the test binary was built with the race
// detector (-race), as the embedded lane's httpclient_served_test is. The
// served tier stands its `bd serve` handler up over the in-process embedded
// Dolt engine, whose own goroutine/lock machinery the detector instruments
// (see internal/storage/embeddeddolt/race_detector_on_test.go), so a large
// write that takes seconds without it can outlast the client's per-request
// timeout with it. The pair carries `cgo` like that package's: its consumers
// are served_*_test.go files, which build only under cgo.
const raceEnabled = true

View file

@ -0,0 +1,290 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/readyclaimer.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"fmt"
"slices"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// readyClaimPage is how many ready rows one DOWN-LEVEL attempt looks at.
//
// The local role does this in ONE transaction with an unbounded scan; a server
// too old to advertise issues.claimNext leaves the composition below no choice
// but a window, and the choice is between wasted rows and wasted round trips.
// Twenty-five is a page a contended front survives — losing all of it takes
// twenty-five simultaneous winners — while staying an order of magnitude under
// the server's own default ready limit, so a claim never drags a full listing
// across the wire.
const readyClaimPage = 25
// httpReadyClaimer serves issueops.ReadyClaimer, on the wire's claimNext
// operation where the server advertises it and by composing a listing and a
// claim where it does not (design D8 row 4).
//
// WHERE THE WIRE CARRIES issues.claimNext, the whole role is one call: the
// filter travels as the query string GET /v0/beads/ready's own decode reads, the
// actor travels as the body, and the server's role does the selection, the
// compare-and-set and the hydration inside ONE transaction. That is the
// operation this role was always waiting for — every clause of the contract that
// the composition could only approximate is simply true of it.
//
// WHERE IT DOES NOT — a server older than upstream #5510 — the composition
// survives unchanged, because `bd ready --claim` worked against those servers
// before this port and refusing it now would be a regression dressed as
// progress. It is the same posture BatchCloser takes toward issues.batchClose,
// and it keeps L14 describing shipped behavior rather than history: the three
// residues are the DOWN-LEVEL leg's, and none of them survives on the served
// one.
//
// - the ready-at-fetch / claim-at-dial window: a row that gained a blocker
// between the listing and the claim can still be claimed, which the local
// one-transaction role can never do;
// - a false empty under contention: after the bounded refetch below, a front
// that was never actually empty is reported as lost races — an ERROR
// distinct from the nil-Claimed nil-error answer an empty front earns, so a
// polling agent is never told "nothing to do" about work it merely lost;
// - the claimed row's cardinalities come from the READY PAGE rather than from
// the claiming transaction. See the hydration note on composedClaim below.
type httpReadyClaimer struct {
store *Store
wire WriteWire
}
var _ issueops.ReadyClaimer = (*httpReadyClaimer)(nil)
// ErrClaimRacesLost reports that every candidate this claim looked at was taken
// by someone else before it could take one. It is deliberately NOT the empty
// front: the queue had work, and re-running is the recovery.
var ErrClaimRacesLost = errors.New("every ready candidate was claimed by someone else")
// ClaimRacesLostError names how many races were lost and where, because "try
// again" without a count cannot be told from a broken claim path.
type ClaimRacesLostError struct {
Actor string
Attempts int
ServerURL string
}
func (e *ClaimRacesLostError) Error() string {
return fmt.Sprintf("lost %d races for ready work on bd serve at %s; re-run to take the next one",
e.Attempts, e.ServerURL)
}
func (e *ClaimRacesLostError) Unwrap() error { return ErrClaimRacesLost }
// ClaimNext takes the next ready row the filter admits.
//
// The filter is the reader's own vocabulary and is encoded by the same table the
// listing uses on BOTH legs, so the claim asks exactly the question `bd ready`
// shows — an inexpressible member refuses there rather than widening the
// candidate set here.
func (r *httpReadyClaimer) ClaimNext(ctx context.Context, req issueops.ClaimNextRequest) (result issueops.ClaimNextResult, err error) {
// Write-side parity with reads: decorates a bare *encode.RefusedError —
// whichever leg raised it, serveClaimNext's encode.ClaimNextParams or
// composeClaimNext's encode.ReadyParams — into *InexpressibleError so
// errors.As(err, &unsupported) reaches *storage.ErrUnsupported, same as
// inexpressible does for a read role. Both legs return directly from this
// method's own return statements, so one defer here catches both.
defer func() { err = r.store.inexpressible("ReadyClaimer.ClaimNext", err) }()
// The role's own request rules, taken from the one place every ReadyClaimer
// shares them rather than restated here, and run BEFORE the leg is chosen so
// both legs refuse the same set. Restating them is how this leg drifted:
// upstream added the Brief refusal to the shared validator and this copy
// kept accepting a projection on a MUTATING call — the field whose whole job
// is to tell a caller it got less than it asked for, answering that it got
// everything.
if err := storageops.ValidateClaimNextRequest(req); err != nil {
return issueops.ClaimNextResult{}, err
}
served, err := r.servesClaimNext(ctx)
if err != nil {
return issueops.ClaimNextResult{}, err
}
if served {
return r.serveClaimNext(ctx, req)
}
return r.composeClaimNext(ctx, req)
}
// servesClaimNext reports whether the server advertises issues.claimNext. It
// forces the one lazy handshake the store already owns and reads the cached
// capability list, so the check costs at most one round trip and none once the
// handshake has run — servesBatchClose's shape exactly, for the same question.
func (r *httpReadyClaimer) servesClaimNext(ctx context.Context) (bool, error) {
snap, err := r.store.snapshot(ctx)
if err != nil {
return false, err
}
if snap == nil {
return false, nil
}
token, _ := wire.CapabilityFor(wire.OpClaimNextIssue)
return slices.Contains(snap.Capabilities, token), nil
}
// serveClaimNext sends the whole request on one issues:claimNext call.
//
// THE ANSWER IS THE ROLE'S RESULT ALREADY. `claimed` is pinned to
// types.IssueWithCounts by the document, hydrated inside the transaction that
// committed the claim, so it passes through unrewritten — no counts to stitch,
// no second read to make, and nothing for this client to recompute. A client
// that rebuilt the row here would be inventing a hydration the wire had already
// done correctly.
//
// AN ABSENT `claimed` IS A NORMAL OUTCOME and is the whole signal: there is no
// boolean beside it, so a drained front is a 200 whose body is `{}`. That
// decodes to a nil pointer, which is exactly what ClaimNextResult means by "nil
// Claimed, nil error, nothing written".
func (r *httpReadyClaimer) serveClaimNext(ctx context.Context, req issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) {
params, err := encode.ClaimNextParams(req.Filter)
if err != nil {
return issueops.ClaimNextResult{}, err
}
res, err := r.wire.ClaimNextIssue(ctx, params, apigen.ClaimNextRequest{Actor: req.Actor})
if err != nil {
return issueops.ClaimNextResult{}, err
}
if err := checkServedClaimNext(res.Claimed); err != nil {
return issueops.ClaimNextResult{}, err
}
return issueops.ClaimNextResult{Claimed: res.Claimed}, nil
}
// checkServedClaimNext holds a served `claimed` to the role contract, and it is
// ONE rule where batchClose's checkServedClaim is three.
//
// A CLAIM CARRYING NO ROW is the rule both share, and it is here for the harder
// of the two reasons that function gives. types.IssueWithCounts holds the row as
// an EMBEDDED POINTER, so an object carrying the cardinalities and none of the
// issue's own members decodes to a non-nil claim whose Issue is nil — a shape
// nothing on the wire tells apart from a claim that landed, and one nothing
// downstream is written to expect. Passing it through is not a wrong answer but
// a PANIC in the caller: `bd ready --claim` dereferences the claimed row's ID
// with no nil check, and the hook decorator above this store fires the
// workspace's on_update hook on the member's PRESENCE alone.
//
// THE OTHER TWO RULES DO NOT APPLY HERE, and the difference is the operation's
// shape rather than a laxer standard. batchClose refuses a claim the request
// never ASKED for and a claim for a batch that closed NOTHING, because there the
// claim is an optional rider on a different act: both preconditions are facts
// about the request and its outcomes, and both are checkable. This operation IS
// the claim — asking is what calling it means, and there is no other outcome for
// it to be earned by — so restating either would be asserting a tautology, and a
// rule that cannot fail is a rule that teaches a later reader the wrong thing
// about what is being checked.
//
// THE CLAIMED ID IS CHECKED AGAINST NOTHING, for exactly the reason it is not
// checked there: the answer names no id the caller enumerated. It names the next
// READY row, chosen by a predicate this client cannot evaluate without running
// the selection the operation exists to keep inside one transaction.
func checkServedClaimNext(claimed *types.IssueWithCounts) error {
if claimed == nil {
return nil
}
if claimed.Issue == nil {
return fmt.Errorf("bd serve returned a claim carrying no issue")
}
return nil
}
// composeClaimNext is the DOWN-LEVEL leg: one listReadyWork page, then claimIssue
// down it until one lands. It is reached only when issues.claimNext is absent,
// and L14 is the ledger row for everything it cannot promise.
func (r *httpReadyClaimer) composeClaimNext(ctx context.Context, req issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) {
// A copy, because the request is the caller's and the page size is ours.
filter := req.Filter
page := readyClaimPage
filter.Limit = &page
params, err := encode.ReadyParams(filter)
if err != nil {
return issueops.ClaimNextResult{}, err
}
// At most one refetch, and only after a FULL page was lost end to end: a
// short page means the front really is that short, so refetching it would
// only re-read the rows that just refused. Two passes bound the work a
// single ClaimNext can do against a server under contention.
var lost int
for attempt := 0; attempt < 2; attempt++ {
ready, err := r.wire.ListReadyWork(ctx, params)
if err != nil {
return issueops.ClaimNextResult{}, err
}
if len(ready.Items) == 0 {
// The steady state of a drained queue, and a normal outcome: nil
// Claimed, nil error, nothing written.
return issueops.ClaimNextResult{}, nil
}
for i := range ready.Items {
row := ready.Items[i]
if row.Issue == nil {
continue
}
claimed, err := r.composedClaim(ctx, req.Actor, row)
switch {
case err == nil:
return issueops.ClaimNextResult{Claimed: claimed}, nil
case isLostRace(err):
lost++
default:
return issueops.ClaimNextResult{}, err
}
}
if len(ready.Items) < page {
break
}
}
return issueops.ClaimNextResult{}, &ClaimRacesLostError{
Actor: req.Actor, Attempts: lost, ServerURL: r.store.target.String(),
}
}
// composedClaim takes one candidate and assembles the hydrated row the role
// promises, for the down-level leg alone.
//
// HYDRATION. ClaimNextResult.Claimed is an issue plus its cardinalities, and the
// wire's ClaimResponse carries the bare row. The counts here therefore come from
// the ready page's own IssueWithCounts rather than from a second read: the issue
// is the POST-claim row the claim itself answered, and the counts are as of the
// listing. A claim changes no dependency, dependent or comment count, so the
// only staleness is the listing window L14's first residue already owns —
// whereas a follow-up getIssue would add a read that can fail AFTER the claim is
// durable, which is a worse answer to the same question.
func (r *httpReadyClaimer) composedClaim(ctx context.Context, actor string, row apigen.IssueWithCounts) (*types.IssueWithCounts, error) {
res, err := r.wire.ClaimIssue(ctx, row.Issue.ID, apigen.ClaimRequest{Actor: actor})
if err != nil {
return nil, err
}
issue := res.Issue
return &types.IssueWithCounts{
Issue: &issue,
DependencyCount: row.DependencyCount,
DependentCount: row.DependentCount,
CommentCount: row.CommentCount,
Parent: row.Parent,
}, nil
}
// isLostRace classifies the refusals that mean "someone else got there first",
// which the loop walks past rather than surfacing.
//
// ErrNotFound joins the two claim refusals deliberately: a row listed as ready
// and gone by the time it was dialed was deleted or promoted mid-loop, which is
// the same situation for a caller that just wants the next piece of work.
func isLostRace(err error) bool {
return errors.Is(err, issueops.ErrAlreadyClaimed) ||
errors.Is(err, issueops.ErrNotClaimable) ||
errors.Is(err, issueops.ErrNotFound)
}

View file

@ -0,0 +1,87 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/refusal.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"errors"
"fmt"
"github.com/steveyegge/beads/internal/httpclient/encode"
)
// InexpressibleError is what a caller gets when a request carries a field the
// v0 wire has no member for: the encoder's divergence-ledger row, joined to the
// portable refusal sentinel.
//
// It is two errors rather than one because two audiences classify it. A caller
// holding an issueops role reaches for *storage.ErrUnsupported — that is what
// the role contracts assert on a knob a backend cannot serve, and it is the
// same arm a local backend's refusal answers. The refusal taxonomy (D7) reaches
// for the LEDGER ROW, because case 3's text names the flag that produced the
// parameter and the reason it cannot cross. Neither is derivable from the
// other, so the error carries both and errors.Is/errors.As reach each.
//
// The Op it names is the ROLE METHOD, not a storage method: nothing on the
// unsupported allowlist refuses this way, and a refusal that named `IssueReader`
// would say the accessor is unserved when the accessor is exactly what answered.
type InexpressibleError struct {
// Unsup is the portable sentinel, decorated with the server context D7
// renders (see (*Store).unsupported).
Unsup *ErrHTTPUnsupported
// Refused is the encoder's refusal, carrying the ledger row: the flag or
// field, the reason, the design decision and its pin.
Refused *encode.RefusedError
// detail is the ORIGINAL error's own Error() text, preserved so a refusal
// a caller decorated with its own context before it reached inexpressible
// (a batch item's index, a dependency's position, a patch member's name)
// keeps naming that context. Empty when the original error IS the bare
// refusal, which is reads' own shape today — see inexpressible's doc.
detail string
}
func (e *InexpressibleError) Error() string {
msg := e.detail
if msg == "" {
msg = e.Refused.Error()
}
if e.Unsup == nil || e.Unsup.ServerURL == "" {
return msg
}
return fmt.Sprintf("%s (bd serve at %s)", msg, e.Unsup.ServerURL)
}
// Unwrap returns both arms, so errors.As reaches *storage.ErrUnsupported and
// errors.Is reaches encode.ErrRefused off the same value.
func (e *InexpressibleError) Unwrap() []error { return []error{e.Unsup, e.Refused} }
// inexpressible decorates an encoder refusal for op, or passes any other error
// through untouched.
//
// The pass-through matters: an encoder can also fail for reasons that are NOT
// divergences — a table lookup for an operation it does not encode, a source
// value of the wrong type — and dressing one of those as an unsupported
// capability would tell a user to upgrade their server over a client bug.
//
// A WRITE ROLE calls this at its own exported method's single defer (never
// at the raw refuse() call inside a nested encoder helper), so a refusal that
// a deeper helper already decorated with its own "items[%d]" or "Issue.%s"
// context arrives here as err's own composite message — preserved in detail
// — rather than as the bare *encode.RefusedError the ledger row alone would
// render. This is how a write-side refusal comes to satisfy
// errors.As(*issueops.ErrUnsupported) exactly as a read-side one already
// does, without rewriting every encoder that builds one.
func (s *Store) inexpressible(op string, err error) error {
var refused *encode.RefusedError
if !errors.As(err, &refused) {
return err
}
unsup, ok := s.unsupported(op).(*ErrHTTPUnsupported)
if !ok {
return err
}
detail := err.Error()
if detail == refused.Error() {
detail = ""
}
return &InexpressibleError{Unsup: unsup, Refused: refused, detail: detail}
}

View file

@ -0,0 +1,30 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/register.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import "github.com/steveyegge/beads/internal/storage/backends"
// Register adds the http client store to the backend registry under the "http"
// name, so workspace validation, discovery and store dispatch recognize
// metadata.json's `backend: "http"`.
//
// Deliberately not an init, for the reason postgres.Register documents:
// registration is a property of the distribution being built, not of the import
// graph. An OSS bd that reached this package transitively would gain a
// selectable "http" backend it must instead hard-fail on with
// UnknownBackendError. Only a distribution that opts in via its own
// build-tagged wiring in cmd/bd calls this.
//
// WorkspaceIsBeadsDir is true: there is no local database to discover, and
// metadata.json plus the activation sidecar are the whole workspace.
//
// Register panics on a duplicate registration, like any process-start wiring
// error, so it must have exactly one production call site.
func Register() {
backends.Register(Backend, backends.Backend{
Open: NewFromConfig,
OpenReadOnly: NewReadOnlyFromConfig,
WorkspaceIsBeadsDir: true,
Remote: true,
})
}

View file

@ -0,0 +1,146 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/relations.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"net/http"
"net/url"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/issueops"
)
// httpRelations serves issueops.Relations from listRelatedIssues (GET
// /v0/beads/issues/{id}/related) — the TWENTY-FIFTH wire-backed accessor, and
// the first read on this surface anchored on ONE issue in the PATH.
//
// IT IS SINGLE-ANCHOR, which is the difference from every other graph role here
// and the reason its miss is shaped differently. EdgeReader and GraphCounter
// take a LIST of anchors, so an id that names nothing has to be reported per
// anchor — `missing: true` beside the ones that answered. This request names
// exactly one, so there is nowhere to put a per-anchor flag and no need for one:
// an anchor on neither plane is a 404, which the shared problem mapper has
// already turned into issueops.ErrNotFound. That is the role's own promise —
// "this issue has no dependencies" and "there is no such issue" are different
// facts — and it costs this client nothing but the discipline of not inventing a
// Missing member the wire does not have.
//
// BOTH HALVES ARE TWO-PLANE and neither half is this client's work. The edges
// come from `dependencies` and `wisp_dependencies`, the far ends are hydrated
// from `issues` and `wisps`, and a WISP ID IS A LEGAL ANCHOR — all three decided
// inside the server's own transaction. What this layer must not do is narrow any
// of them, which is why there is no plane parameter here to forget: the
// operation publishes none, because the role has none.
//
// THE ELEMENT CARRIES NO REVISION BY CONSTRUCTION, so this role is the one place
// on the wave-2b surface with no revision-token stitch. types.Issue.RowVersion
// is `json:"-"` and IssueWithDependencyMetadata publishes no sibling member for
// it, unlike releaseIssue's answer — a neighbor list is not a
// read-modify-write's starting point, and nothing here composes a following
// expected_version.
//
// THE ORDER IS THE SERVER'S and is deliberately not re-applied. The role pins
// ascending by the neighbor's id with the edge type breaking a tie, and
// FinishRelatedPage — the one body both store legs run — produces exactly that
// before the rows are marshaled. Re-sorting here would be a second definition of
// one ordering, which is the drift the shared helper exists to prevent.
type httpRelations struct{ store *Store }
var _ issueops.Relations = httpRelations{}
// Related returns the anchor's neighbors in the requested direction.
//
// THE VALIDATION IS THE ROLE'S OWN BODY, not a second copy of it: this calls
// storageops.ValidateRelatedRequest, the same function the two Dolt legs and the
// unit-of-work leg run, so the three refusals — an empty anchor id, a direction
// outside the closed set, an unusable type filter — are one definition with one
// ORDER. The order is part of the answer: the id is checked FIRST, so a request
// carrying two mistakes names the same offender here as it does on every other
// backend.
//
// TWO OF THE THREE ARE ALSO REACHABLE ON THE SERVER and the third is not, which
// is why validating first is not merely an optimization. The path bound turns an
// unusable id into a 404 before the role is ever called, so the empty-id refusal
// exists ONLY on this side of the wire — a client that forwarded an empty id
// would earn `ErrNotFound` where every other backend answers `ErrValidation`.
func (r httpRelations) Related(ctx context.Context, req issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
if err := storageops.ValidateRelatedRequest(req); err != nil {
return nil, err
}
path, err := wire.IssueRelatedPath(req.ID)
if err != nil {
return nil, err
}
q := url.Values{}
// Required and always sent, including a value the role has already accepted.
// The operation has no default direction and an absent one is a 400 rather
// than a walk of the other end — which is the whole reason the vocabulary is
// closed and the zero value invalid.
//
// The constants are the ListRelatedIssuesParamsDirection* family, spelled
// through relationDirection below rather than as bare strings: apigen carries
// a SECOND [out, in] enum for countDependencyEdges, so the two are one rename
// away from silently answering each other's question.
q.Set("direction", relationDirection(req.Direction))
// Repeated rather than comma-joined, listDependencies' rule: the operation
// reads `type` with the repeatable list decoder and does no splitting, so a
// comma would travel into a type name.
for _, depType := range req.Types {
q.Add("type", string(depType))
}
var body apigen.RelatedIssues
if err := r.store.dispatch(ctx, wire.Request{
Op: wire.OpListRelatedIssues,
Method: http.MethodGet,
Path: path,
Query: q,
IssueID: req.ID,
}, &body); err != nil {
return nil, err
}
// Never nil for a successful call, which the role promises and a caller
// ranges over without checking. The wire promises `items` is an empty array
// and never null, so this is the belt to that braces — and it is the one
// shape a decode CAN produce that the document forbids, since an absent
// member unmarshals to a nil slice.
items := make([]*issueops.RelatedIssue, 0, len(body.Items))
for i := range body.Items {
items = append(items, &body.Items[i])
}
return items, nil
}
// relationDirection maps the role's direction onto the parameter value, through
// the generated constants of THIS operation.
//
// It exists to make one class of mistake impossible rather than to convert two
// strings. apigen carries two [out, in] enums — this operation's
// ListRelatedIssuesParamsDirection* and countDependencyEdges'
// CountDependencyEdgesParamsDirection* — and the second one's arrival RENAMED
// the bare In/Out constants the first draft of a client like this would reach
// for. The two happen to spell the same values today, so a cross-wired reference
// would compile, pass, and answer the inverse graph the day either enum's
// values changed.
//
// A direction outside the closed set cannot reach here: ValidateRelatedRequest
// refuses it above, in the role's own order. The default arm therefore sends the
// value through UNTRANSLATED rather than guessing a direction — if the
// unreachable ever becomes reachable, the server's own 400 naming `direction` is
// a far better answer than a walk of whichever end this function picked.
func relationDirection(direction issueops.RelationDirection) string {
switch direction {
case issueops.RelationOut:
return string(apigen.ListRelatedIssuesParamsDirectionOut)
case issueops.RelationIn:
return string(apigen.ListRelatedIssuesParamsDirectionIn)
default:
return string(direction)
}
}

View file

@ -0,0 +1,154 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/releaser.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
)
// httpReleaser is issueops.Releaser over releaseIssue (POST
// /v0/beads/issues/{id}:release) — the TWENTY-THIRD wire-backed accessor, and
// the claim's inverse.
//
// THE MAPPING IS TOTAL on the request: all four members of ReleaseRequest have a
// wire member or the path, so nothing here refuses on shape and the ledger
// carries no W- row for this operation. What the port had to decide is three
// facts about the ANSWER and one about the refusals.
//
// THE POST-STATE IS ANONYMOUS, which is the Changed ruling and the reason this
// role cannot be idempotent the way Claimer is. A claim leaves its own signature
// on the row — assignee == actor, status in_progress — so a re-claim can be told
// from a foreign one; a release leaves assignee cleared, status open and
// started_at gone, which is the same row no matter who emptied it or whether it
// was ever full. So `changed` is true on every 200 this client will ever see,
// and the three situations an idempotent release would collapse — "I already
// released this", "a reaper beat me to it", "nothing ever claimed it" — arrive
// as refusals instead. This client transcribes them rather than deciding between
// them, which is what keeps a downstream adapter able to map the ones it can
// live with onto its own quiet answer.
//
// THE REVISION RIDES ON Issue.RowVersion AND NOWHERE ELSE. types.Issue.RowVersion
// is `json:"-"`, so the row the server sends carries no token at all and the
// operation publishes it as a sibling member; this role stitches the two back
// together, because the role's own leaf says the post-release token rides on
// Issue.RowVersion and that two spellings of one token is how they come to
// disagree. It is int64 on the Go contract and a decimal STRING on the wire
// (upstream #6053, types.RevisionToken): live tokens run past 5e17, where an
// IEEE-754 double's ulp is already 64, so a JSON number would hand a lossy
// consumer a value NEAR the token that is not it — and the corruption would
// only show up as a precondition_failed on the NEXT request. parseRevision
// reads the string back, and a token it cannot read refuses the answer.
//
// ONE REFUSAL IS FLATTENED and it is ledgered rather than hidden: the role
// splits an unheld row (ErrNotClaimed) from a status that will not accept a
// release (ErrNotReleasable), and the wire spells both `not_releasable` with no
// member telling them apart. See L-release-notclaimed; the wire's own code doc
// says the flattening is deliberate, and the client answers the WIDER of the two
// rather than asserting a fact the wire never sent.
type httpReleaser struct {
store *Store
wire WriteWire
}
var _ issueops.Releaser = (*httpReleaser)(nil)
// Release gives up the claim on one issue and reports the row it left behind.
//
// THE FOUR REFUSALS A CALLER ACTS ON reach it unchanged from the shared problem
// mapper, and naming them here is the point rather than documentation: an id on
// neither plane is issueops.ErrNotFound, a row that will not produce a release is
// issueops.ErrNotReleasable (the flattened pair above), a guard that missed is
// issueops.ErrAssigneeMismatch, and a foreign holder on the unconditional path is
// issueops.ErrAlreadyClaimed carrying *issueops.ClaimConflictError — the wire's
// spelling of the role's ErrNotOwner, which is the fifth refusal and the one
// this operation renames. A conditional caller never earns it: naming the holder
// REPLACES the fence, so a supervisor's release either matches or answers
// ErrAssigneeMismatch. Everything a caller downstream chooses to treat as "the
// claim is already gone" it chooses from those sentinels, so they travel whole.
func (r *httpReleaser) Release(ctx context.Context, req issueops.ReleaseRequest) (issueops.ReleaseResult, error) {
if err := validateReleaseRequest(req); err != nil {
return issueops.ReleaseResult{}, err
}
body := apigen.ReleaseIssueRequest{Actor: req.Actor}
if req.ExpectedAssignee != nil {
// COPIED, never aliased. The role promises implementations never write
// through a caller's request, and handing this pointer to a marshaler is
// the kind of borrow that becomes a write when a helper is added. It is
// also sent UNTRIMMED: the comparison forgives separators and nothing
// else, so a padded expectation has to lose every time rather than
// intermittently.
expected := *req.ExpectedAssignee
body.ExpectedAssignee = &expected
}
if req.Force {
// Sent only when TRUE, because absent and `false` are the same request
// and the operation refuses `force` beside `expected_assignee`. A client
// that always sent the member would put both on the wire for a request
// that asked for neither conflict — legal today, since the server tests
// the value rather than the presence, and one server release away from
// not being.
force := true
body.Force = &force
}
res, err := r.wire.ReleaseIssue(ctx, req.IssueID, body)
if err != nil {
return issueops.ReleaseResult{}, err
}
// A COPY of the decoded row, so the result does not alias a response body,
// and the token stitched onto it rather than beside it.
issue := res.Issue
if issue.RowVersion, err = parseRevision("releaseIssue", res.Revision); err != nil {
return issueops.ReleaseResult{}, err
}
return issueops.ReleaseResult{Issue: &issue, Changed: res.Changed}, nil
}
// validateReleaseRequest is the role's own request rules, restated.
//
// It is the client-side twin of internal/workapi.ValidateReleaseRequest, and it
// is redeclared rather than imported for counter.go's reason: internal/workapi
// is denied to this package by depguard, because a client that could build a
// filter is a client whose narrowing no server-side gate can observe.
// TestReleaseValidationMatchesTheSharedValidator pins the two against each other
// from a test file, where the rule does not apply — the same shape
// TestDefaultListLimitMatchesTheSharedDefault uses, and the answer to
// readyclaimer.go's warning that a restated rule is how a leg drifts.
//
// EVERY ONE OF THESE IS RAISED BEFORE THE DIAL, which is this seam's standing
// rule and sharper here than usual: the server refuses all three at the edge
// with a 400 the mapper turns into the same ErrValidation, so a client that
// skipped the check would still pass the contract — while spending a round trip
// to be told what the role's own contract already calls invalid, and binding the
// classification to a problem body a future server release might spell
// differently.
func validateReleaseRequest(req issueops.ReleaseRequest) error {
if strings.TrimSpace(req.Actor) == "" {
return fmt.Errorf("%w: release requires an actor to attribute it to", issueops.ErrValidation)
}
if strings.TrimSpace(req.IssueID) == "" {
return fmt.Errorf("%w: release requires an issue id", issueops.ErrValidation)
}
if req.ExpectedAssignee != nil {
// A non-nil pointer to "" is NOT "expected unassigned" here, unlike
// UpdateRequest.ExpectedAssignee: releasing a row nobody holds is not a
// release at all, and a caller that wants to assert a row is unheld is
// asking a READER a question.
if strings.TrimSpace(*req.ExpectedAssignee) == "" {
return fmt.Errorf("%w: expected assignee must name a holder; there is no release of an unheld issue",
issueops.ErrValidation)
}
if req.Force {
return fmt.Errorf("%w: force releases whoever holds the issue and expected-assignee releases only a named holder; a request cannot ask for both",
issueops.ErrValidation)
}
}
return nil
}

View file

@ -0,0 +1,23 @@
package httpclient
import (
"os"
"testing"
)
// servedTierLinked reports whether this test binary links the served tier.
// served_harness_test.go, which builds only under cgo like every
// served_*_test.go file, sets it from its init.
var servedTierLinked bool
// TestServedTierIsLinkedWhenRequired is the one served-tier check that builds
// without cgo. skipUnlessEmbeddedDolt turns a missing BEADS_TEST_EMBEDDED_DOLT
// into a failure under BEADS_HTTP_TEST_REQUIRED=1, but it lives in a cgo file:
// with cgo off the go tool drops every served_*_test.go file, so no served test
// exists to fail, and a required run would pass having served nothing.
func TestServedTierIsLinkedWhenRequired(t *testing.T) {
if os.Getenv("BEADS_HTTP_TEST_REQUIRED") == "1" && !servedTierLinked {
t.Fatal("BEADS_HTTP_TEST_REQUIRED=1 but this test binary was built without cgo, which drops " +
"the served-surface conformance tier (served_*_test.go); build it with CGO_ENABLED=1")
}
}

View file

@ -0,0 +1,222 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/resolve.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"fmt"
"net/http"
"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/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The id-resolution surface (design D11). ResolvePartialID is the front door
// every id-taking command goes through, and it makes exactly three store
// probes: an exact-ids SearchIssues, two GetConfig reads for the prefix
// vocabulary, and — only if those fail — a substring SearchIssueIDs. The first
// two are served here; the third has no wire operation at all and is on the
// unsupported allowlist, where the refusal below gives it its vocabulary.
// ErrPartialIDSearch reports that a substring or prefix id lookup was asked of
// a server that publishes no operation for one.
var ErrPartialIDSearch = errors.New("partial-id search is not available over HTTP")
// PartialIDSearchError is D11's dedicated refusal, and it is dedicated because
// the raw failure it replaces answers the wrong question.
//
// The input may be a partial id OR a full id that simply does not exist, and
// the client cannot tell which: it asked for an exact row and got nothing back.
// A "failed to search issues" fallthrough would report the second case as a
// backend fault and the first as nothing at all, so the text names both
// outcomes and the one recovery that covers them.
type PartialIDSearchError struct {
// Input is what the user typed, echoed so the message is about their id.
Input string
// ServerURL is the server that was asked.
ServerURL string
// Unsup is the portable sentinel, so errors.As classification holds through
// this type exactly as it does through every other refusal here.
Unsup *ErrHTTPUnsupported
}
func (e *PartialIDSearchError) Error() string {
return fmt.Sprintf("no exact issue %q on bd serve at %s; partial-id search is not available over HTTP — "+
"check the id or use a local workspace", e.Input, e.ServerURL)
}
func (e *PartialIDSearchError) Unwrap() []error { return []error{e.Unsup, ErrPartialIDSearch} }
func (s *Store) partialIDSearch(op, input string) error {
e := &PartialIDSearchError{Input: input, ServerURL: s.target.String()}
if unsup, ok := s.unsupported(op).(*ErrHTTPUnsupported); ok {
e.Unsup = unsup
}
return e
}
// SearchIssues serves the two shapes the v0 wire can express and refuses every
// other one.
//
// The classification is the encoder's, not this method's: PlanSearch decides
// SHAPE FIRST and then sweeps the fields that shape cannot read, so a filter
// naming both an id set and a parent is refused before either arm is chosen.
// What is decided here is only what to do with each shape once it is named.
//
// The `query` argument is the substring search, and it has no wire operation:
// it refuses with D11's partial-id text rather than with a bare sentinel,
// because a caller that reaches this with a non-empty query is resolving an id
// and the useful thing to say is that the id was not found exactly.
func (s *Store) SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) {
if strings.TrimSpace(query) != "" {
return nil, s.partialIDSearch("SearchIssues", query)
}
plan, err := encode.PlanSearch(filter, func() encode.ListConfig { return s.listConfig(ctx) })
if err != nil {
return nil, s.inexpressible("SearchIssues", err)
}
switch plan.Shape {
case encode.SearchExactIDs:
return s.getIssuesByExactID(ctx, plan.IDs)
case encode.SearchParentWalk:
return s.walkDescendants(ctx, plan)
}
return nil, s.unsupported("SearchIssues")
}
// getIssuesByExactID is D11's fast path: one getIssue per named id, in the
// caller's order, bounded by the encoder at MaxExactIDs.
//
// A 404 becomes an ABSENT ROW, not an error. That is the whole reason this is a
// special case rather than a filter: ResolvePartialID's first probe reads
// `err == nil && len(issues) > 0`, so a miss reported as an error would abandon
// resolution at the exact point the resolver is supposed to fall through to its
// prefix pass. Every other failure — a dead connection, a busy server, a
// refused credential — passes through, because none of them is evidence about
// whether the row exists.
func (s *Store) getIssuesByExactID(ctx context.Context, ids []string) ([]*types.Issue, error) {
found := make([]*types.Issue, 0, len(ids))
for _, id := range ids {
path, err := wire.IssuePath(id)
if err != nil {
return nil, err
}
var details types.IssueDetails
err = s.dispatch(ctx, wire.Request{
Op: wire.OpGetIssue,
Method: http.MethodGet,
Path: path,
IssueID: id,
}, &details)
if errors.Is(err, issueops.ErrNotFound) {
continue
}
if err != nil {
return nil, err
}
// The detail view carries labels in a field of its OWN rather than on
// the embedded issue, and the local SearchIssues hydrates them onto the
// issue. Lifting them across is what makes the two answers the same
// value; a caller reading `issue.Labels` would otherwise see an
// unlabeled row over http and a labeled one locally.
issue := details.Issue
if len(issue.Labels) == 0 && len(details.Labels) > 0 {
issue.Labels = append([]string(nil), details.Labels...)
}
// Issue.RowVersion is json:"-", so the decode above left it at 0;
// details.Revision is getIssue's only wire spelling of the token, the
// same stitch bridge.go's own GetIssue makes. Without this, an exact-id
// hit through SearchIssues (e.g. the resolver's fast path) would carry
// a RowVersion of 0 where a getIssue of the same row populates the real
// token, and a caller that feeds the search result's RowVersion into a
// guarded write would get a spurious mismatch instead of none.
version, err := parseRevision("searchIssues(exact id)", details.Revision)
if err != nil {
return nil, err
}
issue.RowVersion = version
found = append(found, &issue)
}
return found, nil
}
// walkDescendants is D4's hierarchical shape: paged listIssues?parent=<id>.
//
// The CLI asks each level for every descendant (Limit=0 per level), and
// unlimited maps to PAGING TO EXHAUSTION rather than to the wire's `limit=0`,
// which a non-loopback server refuses outright. The recursion itself belongs to
// the caller — findAllDescendants re-parents the filter at every level — so
// this answers one level.
func (s *Store) walkDescendants(ctx context.Context, plan encode.SearchPlan) ([]*types.Issue, error) {
// Not projected: a descendant walk hands its rows back as whole issues, and
// a caller of the hierarchy has no way to learn a body was withheld.
rows, err := s.fetchIssuePages(ctx, plan.Params, false, 0, 0, "", nil)
if err != nil {
return nil, err
}
out := make([]*types.Issue, 0, len(rows))
for _, row := range rows {
if row != nil && row.Issue != nil {
out = append(out, row.Issue)
}
}
return out, nil
}
// ErrSettingRedacted reports a setting whose value the server withheld because
// its KEY marks it credential-bearing.
var ErrSettingRedacted = errors.New("bd serve withholds this setting's value")
// RedactedSettingError is ledger row L9 made answerable: the value is absent
// with a reason, rather than absent as an empty string.
//
// Returning "" would be a dropped read dressed as an unset key, and the two are
// not the same answer — one says the workspace stores nothing, the other says
// the workspace stores something this client may not see.
type RedactedSettingError struct {
Key string
ServerURL string
}
func (e *RedactedSettingError) Error() string {
return fmt.Sprintf("bd serve at %s withholds %q: the key marks it credential-bearing, "+
"so its value is not served to a client", e.ServerURL, e.Key)
}
func (e *RedactedSettingError) Unwrap() error { return ErrSettingRedacted }
// GetConfig serves getSetting. D11's prefix probes — `issue_prefix` and
// `allowed_prefixes` — ride it, and they are flat legacy keys present in the
// settings enumeration, so nothing about them is special-cased here.
//
// A key nothing stored and a key stored empty are ONE answer on this operation,
// exactly as they are on the local store: the wire omits the value in both
// cases and this returns ("", nil), which is what every caller of GetConfig
// already treats as "unset". The one answer that is NOT "" is a redacted key,
// where a value may well exist and is withheld (L9).
func (s *Store) GetConfig(ctx context.Context, key string) (string, error) {
path, err := wire.SettingPath(key)
if err != nil {
return "", err
}
var setting apigen.Setting
if err := s.dispatch(ctx, wire.Request{
Op: wire.OpGetSetting,
Method: http.MethodGet,
Path: path,
}, &setting); err != nil {
return "", err
}
if setting.Redacted {
return "", &RedactedSettingError{Key: key, ServerURL: s.target.String()}
}
if setting.Value == nil {
return "", nil
}
return *setting.Value, nil
}

View file

@ -0,0 +1,76 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/role_querier.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"net/http"
"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"
)
// httpQuerier is issueops.Querier over queryIssues (design D8 row 5).
//
// The expression is not parsed here and must not be: parsing, the predicate
// decision and the scan bound all live inside the server's role, which is what
// stops this client from shipping the truncating window both front doors used
// to apply. Five parameters go out and a page comes back.
//
// It is post-baseline, so the dispatch pre-flights: an older server that does
// not route this path answers a bare 404 that is indistinguishable from an
// entity's not_found, and consulting the advertised `issues.query` token before
// dialing is the only way to tell "this server is too old" from "nothing
// matched".
type httpQuerier struct{ store *Store }
func (q httpQuerier) Query(ctx context.Context, req issueops.QueryRequest) (issueops.IssuePage, error) {
if err := validateQueryOffset(req); err != nil {
return issueops.IssuePage{}, err
}
params, err := encode.QueryParams(req)
if err != nil {
return issueops.IssuePage{}, q.store.inexpressible("Querier.Query", err)
}
var body apigen.QueryPage
if err := q.store.dispatch(ctx, wire.Request{
Op: wire.OpQueryIssues,
Method: http.MethodGet,
Path: wire.PathIssuesQuery,
Query: params,
}, &body); err != nil {
return issueops.IssuePage{}, err
}
// NEVER projected: issueops.QueryRequest has no Brief member, so this role
// cannot ask for one and its rows are always whole. The `false` is the
// compiler asking the question rather than a value to tune — if the query
// vocabulary ever grows the projection, this is the line that has to move
// with it.
return issueops.IssuePage{Items: wireRows(body.Items, false), HasMore: body.HasMore}, nil
}
// validateQueryOffset answers the two Offset refusals the ROLE owns, ahead of
// the one the WIRE owns.
//
// The distinction is the whole reason this function exists. A negative Offset,
// and an Offset combined with a display order, are ErrValidation at EVERY
// backend — the leaf says so in as many words, because under a page bound each
// page is sorted for itself and a walk with an offset would neither visit every
// row nor visit any row once. Those are the caller's request being wrong, and a
// caller must not be told to upgrade a server over them. Only what is left —
// a plain positive Offset — is this backend's own inability, and the encoder
// refuses that one with *ErrUnsupported (E-QueryRequest.Offset).
func validateQueryOffset(req issueops.QueryRequest) error {
switch {
case req.Offset < 0:
return fmt.Errorf("%w: offset %d is negative", issueops.ErrValidation, req.Offset)
case req.Offset > 0 && req.SortBy != "":
return fmt.Errorf("%w: an offset cannot be combined with a display order (sort %q): "+
"the order is applied to the rows the query bounded, so each page would be sorted for itself",
issueops.ErrValidation, req.SortBy)
}
return nil
}

View file

@ -0,0 +1,131 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/role_reader.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"net/http"
"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/types"
"github.com/steveyegge/beads/issueops"
)
// httpReader is issueops.Reader over the v0 wire (design D8 row 1): Ready is
// listReadyWork, List is listIssues, Get is getIssue.
//
// It builds no filter and applies no default. Both request types are handed to
// the encoder whole, and the SERVER runs the same two workapi builders a local
// command would — against its own authoritative vocabulary, which is what heals
// L7's degraded client-side status/type set for every query that goes through
// here. What stays on this side is the part the wire genuinely cannot carry:
// the display order, the caller-supplied keyset position and the MaxRows cap,
// all three of them ledgered client-side in the encoder table and all three
// implemented in list_walk.go.
type httpReader struct{ store *Store }
// Ready serves listReadyWork.
//
// One request, no paging: the operation publishes no cursor, so `limit` and the
// server's own has_more ARE the page contract. An Offset is refused by the
// encoder rather than dropped — ready work carries no keyset position, so there
// is no honest way to page it (E-ReadyRequest.Offset).
func (r httpReader) Ready(ctx context.Context, req issueops.ReadyRequest) (issueops.IssuePage, error) {
params, err := encode.ReadyParams(req)
if err != nil {
return issueops.IssuePage{}, r.store.inexpressible("Reader.Ready", err)
}
var body apigen.ReadyPage
if err := r.store.dispatch(ctx, wire.Request{
Op: wire.OpListReadyWork,
Method: http.MethodGet,
Path: wire.PathReady,
Query: params,
}, &body); err != nil {
return issueops.IssuePage{}, err
}
return issueops.IssuePage{Items: wireRows(body.Items, req.Brief), HasMore: body.HasMore}, nil
}
// List serves listIssues, through the pager in list_walk.go.
func (r httpReader) List(ctx context.Context, req issueops.ListRequest) (issueops.IssuePage, error) {
params, err := encode.ListParams(req)
if err != nil {
return issueops.IssuePage{}, r.store.inexpressible("Reader.List", err)
}
return r.store.walkIssues(ctx, params, req)
}
// Get serves getIssue, including the two landed include parameters that retired
// ledger row L4.
//
// A 404 arrives as the `not_found` problem code, which the wire's problem
// mapper has already turned into issueops.ErrNotFound — the same sentinel a
// local miss answers with — so the role's "a miss is ErrNotFound, a backend
// failure passes through unchanged" promise holds without a single decision
// here. The nil detail view on any error is the other half of it.
func (r httpReader) Get(ctx context.Context, req issueops.GetRequest) (*issueops.IssueDetails, error) {
id, params := encode.GetTarget(req)
path, err := wire.IssuePath(id)
if err != nil {
return nil, err
}
var details types.IssueDetails
if err := r.store.dispatch(ctx, wire.Request{
Op: wire.OpGetIssue,
Method: http.MethodGet,
Path: path,
Query: params,
IssueID: id,
}, &details); err != nil {
return nil, err
}
// Issue.RowVersion is json:"-"; the wire's only spelling of the token is
// Revision (the decimal string getIssue publishes), so a bare decode
// leaves RowVersion at its zero value on every read — a guarded write
// built off this result would carry a token the row never held, same as
// bd-enterprise's (*Store).GetIssue bridge below and the write
// responses parseRevision already stitches this way.
version, err := parseRevision("getIssue", details.Revision)
if err != nil {
return nil, err
}
details.Issue.RowVersion = version
return &details, nil
}
// wireRows lifts a wire page onto the pointer slice the role's page carries,
// and stamps the projection marker the wire cannot carry.
//
// The element type is an ALIAS of types.IssueWithCounts — the same struct the
// server projects onto and the same one `bd list --json` marshals — so this
// takes an address and copies nothing under the header. The result is never
// nil: an empty page is an empty slice on every surface, and a caller must not
// have to tell null from empty to learn that nothing matched.
//
// brief IS A PARAMETER RATHER THAN A FIELD ON ANYTHING, so every page decode on
// this client has to answer the question. types.Issue.IsLitePartial is
// `json:"-"` — it never crosses — and a `brief` page therefore arrives
// byte-identical to a page of genuinely textless rows. The only thing that can
// tell them apart is having ASKED, which is what issueops.ListRequest.Brief's
// own leaf says a wire consumer distinguishes them by, and this client is the
// consumer that asked. A call site that could forget it would be a page whose
// rows lie about being whole; making it an argument means the compiler asks.
//
// IT IS NEVER STAMPED ON A HYDRATED READ. The marker means "the heavy columns
// were not selected", so setting it on a full page would send a caller to
// refetch a body it already has — the same defect as the missing stamp, pointed
// the other way.
func wireRows(items []apigen.IssueWithCounts, brief bool) []*types.IssueWithCounts {
out := make([]*types.IssueWithCounts, 0, len(items))
for i := range items {
row := &items[i]
if brief && row.Issue != nil {
row.IsLitePartial = true
}
out = append(out, row)
}
return out
}

View file

@ -0,0 +1,70 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/role_readycounter.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"net/http"
"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"
)
// httpReadyCounter is issueops.ReadyCounter over countReadyWork (design D8
// row 2). It is what serves `bd ready`'s "showing 2 of 5".
//
// The request it sends is the LISTING's request with the page taken off, which
// is what makes the answer the size of the page Reader.Ready would return: the
// encoder's ready-count table shares one filter list with the listing's, so a
// parameter one of them sent and the other did not cannot exist.
type httpReadyCounter struct{ store *Store }
func (c httpReadyCounter) CountReady(ctx context.Context, req issueops.ReadyRequest) (issueops.ReadyCountResult, error) {
if err := validateCountReadyPage(req); err != nil {
return issueops.ReadyCountResult{}, err
}
params, err := encode.ReadyCountParams(req)
if err != nil {
return issueops.ReadyCountResult{}, c.store.inexpressible("ReadyCounter.CountReady", err)
}
var body apigen.ReadyCount
if err := c.store.dispatch(ctx, wire.Request{
Op: wire.OpCountReadyWork,
Method: http.MethodGet,
Path: wire.PathReadyCount,
Query: params,
}, &body); err != nil {
return issueops.ReadyCountResult{}, err
}
return issueops.ReadyCountResult{Total: body.Total}, nil
}
// validateCountReadyPage answers the role's own page refusals before the
// encoder can answer them as wire refusals.
//
// A Limit and an Offset are ErrValidation on THIS ROLE at every backend, and
// for a reason that has nothing to do with the wire: a cardinality has no page.
// A Limit would answer "how many of the first N", which the identity with
// Reader.Ready(Limit=0) would then stop being true of, and an Offset would
// subtract the rows it skipped from the size of a set that still contains them.
// An explicit zero Limit is refused with the rest — an unlimited count is the
// only kind there is, so asking for one is asking for the default.
//
// The encoder refuses both fields too (E-ReadyRequest.Limit@countReadyWork,
// E-ReadyRequest.Offset), and that row is not redundant: it is what keeps the
// field from being silently dropped if this check were ever removed. What it
// cannot do is tell a caller their REQUEST is wrong rather than their server.
func validateCountReadyPage(req issueops.ReadyRequest) error {
switch {
case req.Limit != nil:
return fmt.Errorf("%w: a ready count takes no limit (%d): a cardinality has no page, "+
"and a bounded count would not agree with the listing it sizes", issueops.ErrValidation, *req.Limit)
case req.Offset != 0:
return fmt.Errorf("%w: a ready count takes no offset (%d): it would subtract the rows it skipped "+
"from the size of a set that still contains them", issueops.ErrValidation, req.Offset)
}
return nil
}

View file

@ -0,0 +1,314 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/roles_aux.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The aggregate and workspace-state roles: StatsReporter whole, and
// WorkspaceConfig whole (design D8 rows 6 and 11).
//
// D8 ROW 11 IS NO LONGER PARTIAL. The row's per-METHOD refusal — an accessor
// that refused would have taken the reads down with the writes, and the reads
// are what `bd config get`, the routing probe and the id resolver's prefix
// lookups run on — was the posture for as long as v0 published no config write.
// Upstream #5596 published both verbs, client wave ga-jpywb dials them, and the
// role now answers every method it declares. What the split bought while it
// lasted is still worth knowing: a per-method refusal puts the method's own name
// in the sentinel, which is what RunUnsupportedContract and the D7 choke point
// both read, so the next partial role should be spelled the same way.
//
// The MEMORY plane is not here: its role is served whole — reads and writes —
// by memories.go, and a read-only twin alongside it would be a second answer to
// the same accessor.
// httpStatsReporter serves both summaries from getStats.
type httpStatsReporter struct{ store *Store }
// Stats answers the workspace-wide summary.
//
// SkipBlocked travels as the hint it is. The server forwards it to its own role,
// which may or may not take it, and the answer says which by whether
// BlockedIssues is populated — so this client neither promises the saving nor
// reports one, and reads the outcome off the same member every other caller
// does.
func (r httpStatsReporter) Stats(ctx context.Context, req issueops.StatsRequest) (issueops.StatsResult, error) {
q := url.Values{}
if req.SkipBlocked {
q.Set("skip_blocked", "true")
}
return r.dial(ctx, q)
}
// AssigneeStats answers one actor's summary.
//
// The actor is used AS WRITTEN — no trimming, no folding, no alias expansion —
// on this side and on the server's.
func (r httpStatsReporter) AssigneeStats(ctx context.Context, req issueops.AssigneeStatsRequest) (issueops.StatsResult, error) {
if strings.TrimSpace(req.Assignee) == "" {
// The one refusal made here rather than dialed. An empty assignee would
// be sent as an ABSENT parameter, which is the workspace-wide question —
// a different answer, not an error — so the request has to be refused
// before it becomes one.
return issueops.StatsResult{}, fmt.Errorf("%w: an assignee must not be empty; the workspace-wide summary is Stats", issueops.ErrValidation)
}
q := url.Values{}
q.Set("assignee", req.Assignee)
return r.dial(ctx, q)
}
func (r httpStatsReporter) dial(ctx context.Context, q url.Values) (issueops.StatsResult, error) {
var body apigen.StatsResponse
if err := r.store.dispatch(ctx, wire.Request{
Op: wire.OpGetStats,
Method: http.MethodGet,
Path: wire.PathStats,
Query: q,
}, &body); err != nil {
return issueops.StatsResult{}, err
}
return issueops.StatsResult{Summary: body.Summary}, nil
}
// httpWorkspaceConfig serves the read half of the settings role.
type httpWorkspaceConfig struct{ store *Store }
// GetSetting reads one stored setting.
//
// It goes through the raw GetConfig rather than dialing again, so this backend
// gives ONE answer per key. That matters for the redacted case: a withheld value
// is not the same fact as an unset one, and GetConfig reports it as
// RedactedSettingError — L9's "absent WITH REASON" — where returning "" would
// tell a caller the workspace stores nothing there. An unset key and a key
// stored empty stay conflated, which is the role contract's own rule.
func (c httpWorkspaceConfig) GetSetting(ctx context.Context, req issueops.GetSettingRequest) (issueops.SettingResult, error) {
if strings.TrimSpace(req.Key) == "" {
// Refused here because the operation carries the key in the PATH: an
// empty segment would join to the collection and turn a read of one
// setting into a read of all of them.
return issueops.SettingResult{}, fmt.Errorf("%w: a setting key must not be empty", issueops.ErrValidation)
}
value, err := c.store.GetConfig(ctx, req.Key)
if err != nil {
return issueops.SettingResult{}, err
}
return issueops.SettingResult{Key: req.Key, Value: value}, nil
}
// ListSettings reads every stored setting.
//
// Redacted keys are PRESENT with an empty value, and this is the one place the
// withholding cannot be reported as an error: an enumeration that failed because
// one key of forty is credential-bearing would take the whole listing down.
// Omitting them instead would say the workspace stores nothing under that key,
// which is false and is the reading a caller enumerating configuration acts on —
// so the key is listed and its value is the empty string GetSetting refuses to
// pretend is real.
func (c httpWorkspaceConfig) ListSettings(ctx context.Context, _ issueops.ListSettingsRequest) (issueops.ListSettingsResult, error) {
var body apigen.SettingsPage
if err := c.store.dispatch(ctx, wire.Request{
Op: wire.OpListSettings,
Method: http.MethodGet,
Path: wire.PathSettings,
}, &body); err != nil {
return issueops.ListSettingsResult{}, err
}
settings := make(map[string]string, len(body.Items))
for _, item := range body.Items {
settings[item.Key] = settingValue(item)
}
return issueops.ListSettingsResult{Settings: settings}, nil
}
// SetSetting stores one setting, on PUT /v0/beads/config/{key}.
//
// THE KEY IS THE PATH AND THE VALUE IS THE WHOLE BODY, which is what makes this
// the smallest write on the surface: one member out, one row back. There is no
// actor and no guard, because this plane records no history entry to attribute a
// write on and holds no row version to compare — so a write here is neither
// attributable nor conditional on ANY backend, and the wire is not narrowing
// anything by omitting them.
//
// IT IS NOT IDEMPOTENT-SHORT-CIRCUITED and must not become so. Storing the value
// already there still performs the write and its projection: the role's own
// contract says a no-op detection would make the repair of a normalized table
// that had drifted from its row depend on the row having changed, which is
// precisely the state that needs repairing. Nothing here compares first, and
// there is no `changed` member on the answer to compare against — the response
// to the second PUT is byte-identical to the first, which is the shape a PUT
// should have and is deliberately NOT the `already_claimed` / `already_closed`
// shape three other writes on this surface carry.
func (c httpWorkspaceConfig) SetSetting(ctx context.Context, req issueops.SetSettingRequest) (issueops.SetSettingResult, error) {
if err := validateSettingWrite(req.Key, req.Value); err != nil {
return issueops.SetSettingResult{}, err
}
path, err := wire.SettingPath(req.Key)
if err != nil {
return issueops.SetSettingResult{}, invalid("%v", err)
}
var body apigen.Setting
if err := c.store.dispatch(ctx, wire.Request{
Op: wire.OpSetSetting,
Method: http.MethodPut,
Path: path,
Body: apigen.SetSettingRequest{Value: req.Value},
}, &body); err != nil {
return issueops.SetSettingResult{}, err
}
return issueops.SetSettingResult{Key: body.Key, Value: storedSettingValue(req.Value, body)}, nil
}
// UnsetSetting removes one setting, on DELETE /v0/beads/config/{key}.
//
// REMOVING A KEY NOTHING SET SUCCEEDS, twice over: the role states an intended
// END STATE rather than an act performed, and the wire agrees — there is no 404
// on this operation at all, which is the one place it diverges from the memory
// delete beside it. So a caller clearing configuration it is not sure was ever
// written classifies no error to learn it was already absent.
//
// THE PROTECTED KEY IS NOT REFUSED HERE, unlike on the write above, and the
// asymmetry is shipped behavior on every implementation rather than something
// this client introduces (bd-yby99.34). Restating it as a refusal would make
// this leg stricter than the contract it implements, which is the one direction
// a client-side rule must never take.
func (c httpWorkspaceConfig) UnsetSetting(ctx context.Context, req issueops.UnsetSettingRequest) (issueops.UnsetSettingResult, error) {
if err := validateSettingKey(req.Key); err != nil {
return issueops.UnsetSettingResult{}, err
}
path, err := wire.SettingPath(req.Key)
if err != nil {
return issueops.UnsetSettingResult{}, invalid("%v", err)
}
var body apigen.RemovedSetting
if err := c.store.dispatch(ctx, wire.Request{
Op: wire.OpUnsetSetting,
Method: http.MethodDelete,
Path: path,
}, &body); err != nil {
return issueops.UnsetSettingResult{}, err
}
return issueops.UnsetSettingResult{Key: body.Key}, nil
}
// validateSettingKey is the rule a key a caller READS or REMOVES has to meet,
// and it is the only rule at that end: a key has to name something.
//
// It is the client-side twin of internal/workapi.ValidateSettingKey, redeclared
// rather than imported for releaser.go's reason — depguard denies
// internal/workapi to this package — and pinned against it by
// TestSettingWriteValidationMatchesTheSharedValidator, from a test file where
// the rule does not apply.
//
// IT IS ALSO PATH SAFETY, which is why it could not have been left to the
// server even if the role did not state it: the key is one PATH SEGMENT, so an
// empty one would join to the collection and turn a write of one setting into a
// request against all of them.
func validateSettingKey(key string) error {
if strings.TrimSpace(key) == "" {
return invalid("config key must not be empty")
}
return nil
}
// validateSettingWrite is the role's own write rules, restated: the key rule
// above, the protected key, and the one value whose shape is checked because it
// is PROJECTED rather than merely stored.
//
// ALL THREE ARE THE ROLE'S AND NOT THE SERVER'S, which is the line this function
// draws and the reason it stops where it does. The server applies its own EDGE
// bounds on top — a key past 255 characters on the write (but not on the
// remove), a value past types.MaxTextBytes BYTES, a media type — and this client
// restates none of them: those are one server release away from moving, and a
// second copy here would either drift or refuse a request a newer server would
// take. They travel as the 400 the mapper turns into the same ErrValidation, and
// the difference that makes to a local leg is ledgered (L-config-bounds).
//
// The three below cannot travel that way for the reason every restated role rule
// on this seam cannot: a request the role's own contract calls invalid must not
// spend a round trip to be told so, and must not bind its classification to a
// problem body a future server release might spell differently.
func validateSettingWrite(key, value string) error {
if err := validateSettingKey(key); err != nil {
return err
}
// The prefix is owned by `bd init --prefix`, `bd bootstrap` and
// `bd rename-prefix`, each of which does work this plane cannot: rewriting
// existing ids, or seeding a workspace that has none. Storing a new one here
// would leave the beads created before the write and the beads created after
// it disagreeing about their own namespace, with nothing to reconcile them.
// BOTH SPELLINGS refuse, and the dashed one for a different reason than the
// underscored: nothing reads it, so writing it would report success and be
// unobservable.
if key == issueops.SettingKeyIssuePrefix || key == settingKeyIssuePrefixDashed {
return invalid("%q is set by bd init --prefix, bd bootstrap or bd rename-prefix, not by a config write: "+
"storing it here would leave existing ids under the old prefix with nothing to reconcile them", key)
}
// status.custom is PROJECTED into custom_statuses, which reads consult
// first, so a value that cannot be projected must not become a row. The
// parse belongs to the ROLE — every leg refuses it — rather than to a front
// door, because a value one door accepted and another refused would be half
// applied by whichever wrote first.
if key == issueops.SettingKeyStatusCustom && value != "" {
if _, err := types.ParseCustomStatusConfig(value); err != nil {
return invalid("invalid %s value: %v", key, err)
}
}
return nil
}
// settingKeyIssuePrefixDashed is the second spelling of the protected key. The
// role names only the underscored one as a constant and spells this one inline;
// it is named here so the refusal and the test that pins it read one string.
const settingKeyIssuePrefixDashed = "issue-prefix"
// storedSettingValue is what the workspace now holds, read off the answer.
//
// THE PROJECTION IS TRANSCRIBED RATHER THAN INTERPRETED. The response to a write
// is byte-identical to the read that follows it — one `wireSetting` serves both
// — so a stored value comes back on the same optional member, absent for the
// same three facts, and this reads it with the same helper the reads use.
//
// A REDACTED KEY IS THE ONE PLACE THE PROJECTION CANNOT ANSWER, and the fallback
// is the request rather than a guess. The operation PERMITS writing a
// credential-bearing key — refusing would leave a workspace's credentials
// visible as present and permanently unconfigurable through this door — and then
// withholds the value from its own answer, exactly as the read withholds it. So
// `value` is absent on a write that certainly stored something, and reporting ""
// would tell a caller the plane holds nothing there: the write-side spelling of
// the confusion RedactedSettingError exists to prevent on the read side (L9).
//
// Answering with the value the caller SENT is not an interpretation of what
// redaction hid. It is the operation's own promise, stated on the request member:
// the stored value equals the value sent for every key this plane accepts,
// because the one stored key with a normalization step is `issue_prefix` and
// that is the one key the role refuses. There is no third option — the result
// type carries no "withheld" spelling, and erroring on a write that LANDED would
// be a worse answer than either.
func storedSettingValue(sent string, body apigen.Setting) string {
if body.Redacted {
return sent
}
return settingValue(body)
}
// settingValue reads the wire's optional value.
//
// The member is absent for three different facts — nothing stored, the empty
// string stored, and a credential withheld — and `redacted` separates only the
// third. All three are "" to this role by its own contract; see GetSetting.
func settingValue(s apigen.Setting) string {
if s.Value == nil {
return ""
}
return *s.Value
}

View file

@ -0,0 +1,472 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/roles_graph.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The four dependency-graph read roles, served from their v0 operations
// (design D8 rows 7-10).
//
// Each one is a thin projection, and that is a property of the wire rather than
// of the code: every response component on this surface is a Go TYPE ALIAS of
// the canonical struct the role returns (internal/httpapi/pinning.go asserts it
// by ASSIGNMENT, which a structurally-identical twin could not satisfy). So
// there is no field mapping to get wrong here, and deliberately none written —
// a hand-rolled converter would be a second copy of a contract the server
// already pins.
//
// What IS this layer's work is the contract each role's doc comment states and
// the wire does not restate: never-nil collections, the caller's request left
// alone, and the defensive caps the wire publishes no parameter for.
//
// They dispatch GENERICALLY, through the store's one door. A read role differs
// from its neighbors only in the parameters the encoder produced and the
// envelope it decodes, so an operation-shaped transport method per role would
// be a dozen spellings of one round trip — see the WireClient doc for why the
// two halves of that seam are shaped differently.
// httpCycleDetector serves DetectCycles from listDependencyCycles.
type httpCycleDetector struct{ store *Store }
// DetectCycles reports every cycle in the blocking graph.
//
// The request carries nothing (beyond IncludeTracks, refused below) and the
// operation publishes nothing, which is the same statement from both ends: a
// cycle is a property of the whole graph and there is no predicate that
// narrows it.
//
// req.IncludeTracks is refused rather than silently ignored: listDependencyCycles
// (wire.OpListDependencyCycles) has no include_tracks parameter at all, so
// honoring it would mean quietly answering the DEFAULT (narrower) walk to a
// caller who explicitly asked for the wider one that also follows `tracks`
// edges. This is the same typed, ledger-cited refusal CountEdges' own bound
// raises below (refuse/encode.RefusedError, not a bare error) — see
// "L-cycles-tracks" and engdocs/design/http-divergence-ledger.md.
func (d httpCycleDetector) DetectCycles(ctx context.Context, req issueops.DetectCyclesRequest) (result issueops.CycleReport, err error) {
// 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.
defer func() { err = d.store.inexpressible("CycleDetector.DetectCycles", err) }()
if req.IncludeTracks {
return issueops.CycleReport{}, refuse(encode.OpListDependencyCycles, "L-cycles-tracks")
}
var body apigen.CyclesPage
if err := d.store.dispatch(ctx, wire.Request{
Op: wire.OpListDependencyCycles,
Method: http.MethodGet,
Path: wire.PathDependenciesCycles,
}, &body); err != nil {
return issueops.CycleReport{}, err
}
// Empty rather than nil on an acyclic graph: the role promises a caller can
// range over the answer, and the count of cycles is the length of this
// slice with nothing omitted.
cycles := body.Items
if cycles == nil {
cycles = []issueops.Cycle{}
}
return issueops.CycleReport{Cycles: cycles}, nil
}
// httpTreeWalker serves WalkTree from getDependencyTree.
type httpTreeWalker struct{ store *Store }
// WalkTree walks the graph from one root.
//
// TWO REQUEST MEMBERS ARE HONORED HERE RATHER THAN DROPPED. MaxDepth and
// Direction have parameters and travel; MaxRows does not, and it is the one
// member of this request whose contract says every implementation honors it —
// so the cap is enforced against the answer, where the role documents the check
// happening (after the walk and after the prune) and with the sentinel `bd`
// already classifies into exit 2.
//
// max_depth is sent ALWAYS, including the zero and the negative the role
// refuses. The operation defaults an ABSENT max_depth to fifty levels while the
// role makes the bound required, so omitting the caller's value would answer a
// fifty-level walk to a request that asked for none — a wider answer reached by
// dropping a bound, which is the one thing this client may never do.
//
// The validation refusals stay the SERVER's. An empty root, a direction outside
// the closed set and a depth below one are refusals the operation makes for
// itself and maps back to issueops.ErrValidation, so re-making them here would
// be a second copy of a rule that answers differently the day the vocabulary
// grows.
func (w httpTreeWalker) WalkTree(ctx context.Context, req issueops.WalkTreeRequest) (issueops.TreeResult, error) {
q := url.Values{}
q.Set("root_id", req.RootID)
q.Set("max_depth", strconv.Itoa(req.MaxDepth))
if req.Direction != "" {
q.Set("direction", string(req.Direction))
}
if req.Status != "" {
q.Set("status", string(req.Status))
}
var body apigen.DependencyTreePage
if err := w.store.dispatch(ctx, wire.Request{
Op: wire.OpGetDependencyTree,
Method: http.MethodGet,
Path: wire.PathDependenciesTree,
Query: q,
IssueID: req.RootID,
}, &body); err != nil {
return issueops.TreeResult{}, err
}
nodes := make([]*issueops.TreeNode, 0, len(body.Items))
for i := range body.Items {
nodes = append(nodes, &body.Items[i])
}
if req.MaxRows > 0 && len(nodes) > req.MaxRows {
// The count is EXACT rather than the storage layer's cap+1 probe: the
// walk answers whole, so there is no cheaper bound to report and no
// reason to report a vaguer one. The answer is withheld entirely, which
// is what the role's own contract says a cap violation returns.
return issueops.TreeResult{}, &storageops.ErrTooManyRows{
Found: len(nodes),
Cap: req.MaxRows,
Source: req.MaxRowsSource,
}
}
return issueops.TreeResult{Nodes: nodes}, nil
}
// httpEdgeReader serves ReadEdges from listDependencies.
type httpEdgeReader struct{ store *Store }
// ReadEdges reads the stored edges of one anchored set of ids.
//
// The wire answers with the edges FLATTENED across anchors plus the ids that
// named nothing; the role answers per anchor, in the order the request first
// named each id. Regrouping is this method's whole job, and it walks the
// CALLER's id list rather than the response — an anchor with no edges appears in
// neither `items` nor `missing`, so a grouping driven by the response alone
// would silently lose it.
//
// AN EMPTY REQUEST IS ANSWERED WITHOUT A DIAL. The operation requires at least
// one anchor and would refuse, but the role documents an empty request as a
// success with no anchors — so refusing would be this backend inventing an error
// the contract says does not exist.
func (r httpEdgeReader) ReadEdges(ctx context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
if err := validateAnchors(req.IDs); err != nil {
return issueops.EdgeReadResult{}, err
}
ids := distinct(req.IDs)
if len(ids) == 0 {
return issueops.EdgeReadResult{Anchors: []issueops.AnchorEdges{}}, nil
}
q := url.Values{}
for _, id := range ids {
q.Add("issue_id", id)
}
// Repeated rather than comma-joined: the operation reads `type` with the
// repeatable list decoder and does no splitting, so a comma would travel
// into a type name.
for _, edgeType := range req.Types {
q.Add("type", string(edgeType))
}
var body apigen.DependencyEdges
if err := r.store.dispatch(ctx, wire.Request{
Op: wire.OpListDependencies,
Method: http.MethodGet,
Path: wire.PathDependencies,
Query: q,
}, &body); err != nil {
return issueops.EdgeReadResult{}, err
}
missing := make(map[string]bool, len(body.Missing))
for _, id := range body.Missing {
missing[id] = true
}
grouped := make(map[string][]*issueops.Dependency, len(ids))
for i := range body.Items {
edge := &body.Items[i]
grouped[edge.IssueID] = append(grouped[edge.IssueID], edge)
}
anchors := make([]issueops.AnchorEdges, 0, len(ids))
for _, id := range ids {
edges := grouped[id]
if edges == nil {
// Never nil on a successful call, including for an anchor that has
// no edges and for one that names nothing at all.
edges = []*issueops.Dependency{}
}
anchors = append(anchors, issueops.AnchorEdges{ID: id, Edges: edges, Missing: missing[id]})
}
return issueops.EdgeReadResult{Anchors: anchors}, nil
}
// GetDependencyRecords answers one issue's stored outgoing edges as raw rows,
// off the same listDependencies operation httpEdgeReader rides. It is an off-role
// raw method rather than an accessor — `bd dep remove`, the molecule loaders and
// `bd delete`'s preview call it directly — so it sits here beside the surface it
// shares rather than on the role above.
//
// ONE ANCHOR, NEVER CHUNKED. The operation bounds a request at
// maxDependencyAnchors (100), and one id is nowhere near it, so there is no
// splitting to do. The wire flattens the answer across the anchors it was asked
// about; asked about one, every item belongs to that one, and the missing list
// names it iff the id resolved to nothing.
//
// A MISS IS (nil, nil), matching the local method: an id that names neither an
// issue nor a wisp comes back in `missing`, and the reference returns a nil slice
// for a nonexistent id (dolt/dependencies.go). The rows themselves are the wire's
// verbatim — apigen.Dependency is a type alias of types.Dependency, and the
// server resolves each row's target through the same issueops.DepTargetExpr the
// reference read does, so an unresolved or bare-slug depends_on_id (the value the
// GH#5005 `bd dep remove` guard exists to see) crosses whole rather than
// normalized away.
func (s *Store) GetDependencyRecords(ctx context.Context, id string) ([]*types.Dependency, error) {
if id == "" {
return nil, nil
}
q := url.Values{}
q.Set("issue_id", id)
var body apigen.DependencyEdges
if err := s.dispatch(ctx, wire.Request{
Op: wire.OpListDependencies,
Method: http.MethodGet,
Path: wire.PathDependencies,
Query: q,
}, &body); err != nil {
return nil, err
}
for _, missing := range body.Missing {
if missing == id {
return nil, nil
}
}
if len(body.Items) == 0 {
return nil, nil
}
records := make([]*types.Dependency, 0, len(body.Items))
for i := range body.Items {
records = append(records, &body.Items[i])
}
return records, nil
}
// maxEdgeCountAnchors is the anchor bound GET /v0/beads/dependencies:count
// publishes: `issue_id` is minItems 1, maxItems 100.
//
// It is the SAME number as the stored-edge read's, from the server's one
// maxDependencyAnchors constant, because the two operations bound the same
// thing on the same collection — which is exactly why the client refuses at it
// rather than chunking past it. See httpGraphCounter.CountEdges.
const maxEdgeCountAnchors = 100
// httpGraphCounter serves CountEdges from countDependencyEdges — the
// TWENTY-SECOND wire-backed accessor, and the only role on this surface whose
// answer is a number PER ANCHOR.
//
// It builds its query inline rather than through the encoder table, beside the
// three graph reads above and for their reason: the encode package classifies
// PREDICATES, where a forgotten member widens a result set invisibly, and this
// request is an anchored one — four members, every one of them published. What
// takes the place of the table here is TestEdgeCountRequestSendsEveryMember,
// which reflects over the request so a member added upstream fails closed
// instead of being dropped into a count that still looks like a count.
type httpGraphCounter struct{ store *Store }
// CountEdges returns each anchor's edge cardinality in the requested direction.
//
// THE VALIDATION IS THE ROLE'S OWN BODY, not a second copy of it: this calls
// storageops.ValidateEdgeCountRequest, the same function the two Dolt legs and
// the unit-of-work leg run, so the four refusals — an absent or unrecognized
// direction, a status beside direction=out, an empty anchor id, an unusable
// dependency type — are one definition with one ORDER. The order is part of the
// contract (the direction is checked FIRST, so an empty request refuses about
// the direction rather than answering emptily), and a client that re-asked the
// questions in some order of its own would name a different offender than every
// other backend for a request carrying two mistakes.
//
// AN EMPTY REQUEST IS ANSWERED WITHOUT A DIAL, exactly as the stored-edge read's
// is: the operation requires at least one anchor and would refuse, while the
// role documents an empty slice as a success with no anchors. The direction is
// still validated first, so EdgeCountRequest{} refuses rather than answering.
func (c httpGraphCounter) CountEdges(ctx context.Context, req issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) {
if err := storageops.ValidateEdgeCountRequest(req); err != nil {
return issueops.EdgeCountResult{}, err
}
// The collapse is the CLIENT's, not the wire's, and it has to be: the answer
// carries one entry per distinct anchor in first-mention order, and matching
// the response back onto the caller's list means holding the same collapse
// the server performed. Sending the repeats and trusting the server to
// collapse them would work until an id appeared twice near the bound, where
// the request would refuse for a size the answer never had.
ids := distinct(req.IDs)
if len(ids) == 0 {
return issueops.EdgeCountResult{Anchors: []issueops.AnchorEdgeCount{}}, nil
}
if len(ids) > maxEdgeCountAnchors {
return issueops.EdgeCountResult{}, &encode.RefusedError{
Op: encode.OpCountDependencyEdges,
Row: encode.RowByID("L-edgecount-bound"),
}
}
q := url.Values{}
for _, id := range ids {
q.Add("issue_id", id)
}
// Required and always sent, including a value the role has already accepted:
// the operation has no default direction, and an omitted one is a 400 rather
// than a count of the other end.
q.Set("direction", string(req.Direction))
// Repeated rather than comma-joined, listDependencies' rule: the operation
// reads `type` with the repeatable list decoder and does no splitting.
for _, edgeType := range req.Types {
q.Add("type", string(edgeType))
}
if req.Status != "" {
q.Set("status", req.Status)
}
var body apigen.EdgeCounts
if err := c.store.dispatch(ctx, wire.Request{
Op: wire.OpCountDependencyEdges,
Method: http.MethodGet,
Path: wire.PathDependenciesCount,
Query: q,
}, &body); err != nil {
return issueops.EdgeCountResult{}, err
}
return edgeCountAnchors(ids, body)
}
// edgeCountAnchors reads the per-anchor answer back onto the caller's own list.
//
// IT WALKS THE REQUEST, NOT THE RESPONSE, for the reason httpEdgeReader's
// regrouping does — the order and the membership of the answer are the
// REQUEST's, and a projection driven by the body would inherit whatever the
// server happened to send. Here that is sharper than usual, because the two
// facts this role publishes are a COUNT and a MISSING flag, and both have a
// plausible-looking default: a dropped entry reads as 0, and a lost flag reads
// as an anchor that exists.
//
// So an anchor the answer does not carry is an ERROR rather than a zero. The
// operation promises one entry per distinct requested id; a body missing one is
// a server that did not answer the question, and the two readings a client could
// substitute — count 0, or missing — are the two answers this role exists to
// tell apart.
func edgeCountAnchors(ids []string, body apigen.EdgeCounts) (issueops.EdgeCountResult, error) {
answered := make(map[string]apigen.AnchorEdgeCount, len(body.Anchors))
for _, anchor := range body.Anchors {
answered[anchor.Id] = anchor
}
anchors := make([]issueops.AnchorEdgeCount, 0, len(ids))
for _, id := range ids {
entry, ok := answered[id]
if !ok {
return issueops.EdgeCountResult{}, fmt.Errorf(
"bd serve answered an edge count with no entry for anchor %q: the operation carries one per distinct requested id, "+
"and an absent one cannot be told from a count of 0 or from an anchor that is not there", id)
}
// Count is int64 on the wire, in apigen and on the role: a workspace's
// graph is not bounded by 2^53, and a narrowed read would answer a
// number NEAR the cardinality.
anchors = append(anchors, issueops.AnchorEdgeCount{ID: id, Count: entry.Count, Missing: entry.Missing})
}
return issueops.EdgeCountResult{Anchors: anchors}, nil
}
// httpBlockingAnnotator serves AnnotateBlocking from listBlockingAnnotations.
type httpBlockingAnnotator struct{ store *Store }
// AnnotateBlocking decorates one anchored set of ids.
//
// The wire already answers one entry per distinct id in first-mention order, so
// the projection is the identity — but the never-nil promise on the two lists is
// this layer's, because a JSON `[]` decodes to a non-nil empty slice while an
// absent member decodes to nil, and the role promises a caller may range over
// both without checking.
func (a httpBlockingAnnotator) AnnotateBlocking(ctx context.Context, req issueops.BlockingRequest) (issueops.BlockingResult, error) {
if err := validateAnchors(req.IDs); err != nil {
return issueops.BlockingResult{}, err
}
ids := distinct(req.IDs)
if len(ids) == 0 {
return issueops.BlockingResult{Items: []issueops.IssueBlocking{}}, nil
}
q := url.Values{}
for _, id := range ids {
q.Add("issue_id", id)
}
var body apigen.BlockingAnnotations
if err := a.store.dispatch(ctx, wire.Request{
Op: wire.OpListBlockingAnnotations,
Method: http.MethodGet,
Path: wire.PathDependenciesBlocking,
Query: q,
}, &body); err != nil {
return issueops.BlockingResult{}, err
}
items := make([]issueops.IssueBlocking, 0, len(body.Items))
for _, item := range body.Items {
if item.BlockedBy == nil {
item.BlockedBy = []string{}
}
if item.Blocks == nil {
item.Blocks = []string{}
}
items = append(items, item)
}
return issueops.BlockingResult{Items: items}, nil
}
// distinct collapses repeated anchors, keeping each at the position of its first
// mention — the order both roles answer in.
//
// It COPIES rather than sorting or compacting in place: the caller's slice is
// theirs, and both roles promise not to touch it.
func distinct(ids []string) []string {
seen := make(map[string]bool, len(ids))
out := make([]string, 0, len(ids))
for _, id := range ids {
if id == "" || seen[id] {
continue
}
seen[id] = true
out = append(out, id)
}
return out
}
// validateAnchors refuses an empty anchor id, and does so BEFORE the collapse.
//
// It is the one validation these two roles make for themselves, because the
// collapse would otherwise hide it in both directions: an empty entry alongside
// a real one would simply not be sent, and a request of nothing but empty
// entries would reach the empty-request arm looking like a request that named
// nothing. Those are different questions — an empty entry is ErrValidation, an
// empty slice is a success — and the server can only refuse what it receives.
func validateAnchors(ids []string) error {
for _, id := range ids {
if id == "" {
return fmt.Errorf("%w: an anchor id must not be empty", issueops.ErrValidation)
}
}
return nil
}

View file

@ -0,0 +1,59 @@
package httpclient
import (
"errors"
"testing"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/issueops"
)
// TestDetectCyclesIncludeTracksRefusesWithoutDialing is "L-cycles-tracks"'s
// pin: listDependencyCycles carries no include_tracks parameter at all, so a
// request that asks for the widened (tracks-following) walk is refused with a
// typed, ledger-cited error BEFORE any request reaches the wire, rather than
// silently answering the narrower default walk the server would have returned
// for a bare request.
//
// This is a unit pin rather than something the served tier proves: the
// refusal is pre-dial by design (mirrors TestEdgeCountRefusesMoreAnchorsThanTheWireCarries
// in counts_test.go), so a served run would only show that a request this
// client never sends would also have done something server-side. What has to
// be true here is that the client never dials at all.
func TestDetectCyclesIncludeTracksRefusesWithoutDialing(t *testing.T) {
w := newCountingWire(`{"items":[],"has_more":false}`)
detector, err := New(testTarget(t), w, nil).CycleDetector()
if err != nil {
t.Fatalf("CycleDetector(): %v", err)
}
_, err = detector.DetectCycles(t.Context(), issueops.DetectCyclesRequest{IncludeTracks: true})
if !errors.Is(err, encode.ErrRefused) {
t.Fatalf("IncludeTracks request encoded without a refusal: %v", err)
}
var refusal *encode.RefusedError
if !errors.As(err, &refusal) || refusal.Row.ID != "L-cycles-tracks" {
t.Errorf("refusal cites %+v, want ledger row L-cycles-tracks", err)
}
if len(w.dialed) != 0 {
t.Errorf("IncludeTracks refusal dialed %d requests, want 0", len(w.dialed))
}
}
// TestDetectCyclesWithoutIncludeTracksStillDials is the companion case: a
// request that leaves IncludeTracks false is unaffected by the refusal above
// and still reaches listDependencyCycles exactly as before.
func TestDetectCyclesWithoutIncludeTracksStillDials(t *testing.T) {
w := newCountingWire(`{"items":[],"has_more":false}`)
detector, err := New(testTarget(t), w, nil).CycleDetector()
if err != nil {
t.Fatalf("CycleDetector(): %v", err)
}
if _, err := detector.DetectCycles(t.Context(), issueops.DetectCyclesRequest{}); err != nil {
t.Fatalf("DetectCycles(IncludeTracks: false): %v", err)
}
if len(w.dialed) != 1 {
t.Errorf("dialed %d times, want exactly 1", len(w.dialed))
}
}

View file

@ -0,0 +1,445 @@
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/roles_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"math/rand"
"strconv"
"testing"
"time"
"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/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// The database-free half of the read roles: the dispatch policy, the two
// constants this package had to copy, and the refusal shapes. None of it needs
// a server, so all of it runs in the default build rather than behind the cgo
// tag the served composition lives under.
// recordingWire records the operations a role dispatched and answers each one
// with an empty body.
//
// The embedded WriteWire is nil for the reason fakeWire's is: it makes this
// double satisfy the transport seam however the write beads grow it, and a read
// role that somehow reached a write operation panics rather than getting a
// plausible zero.
type recordingWire struct {
WriteWire
preflighted []string
dispatched []string
requests []wire.Request
}
func (r *recordingWire) ServerContext(context.Context) (*apigen.ContextResponse, error) {
return &apigen.ContextResponse{}, nil
}
func (r *recordingWire) Preflight(_ context.Context, op string) error {
r.preflighted = append(r.preflighted, op)
return nil
}
func (r *recordingWire) Do(_ context.Context, req wire.Request, out any) error {
r.dispatched = append(r.dispatched, req.Op)
r.requests = append(r.requests, req)
switch body := out.(type) {
case *apigen.ReadyPage:
*body = apigen.ReadyPage{Items: []apigen.IssueWithCounts{}}
case *apigen.IssuesPage:
*body = apigen.IssuesPage{Items: []apigen.IssueWithCounts{}}
case *apigen.QueryPage:
*body = apigen.QueryPage{Items: []apigen.IssueWithCounts{}}
case *apigen.ReadyCount:
*body = apigen.ReadyCount{}
case *apigen.Setting:
*body = apigen.Setting{}
case *types.IssueDetails:
// Revision is required on every getIssue response
// (openapi.v0.yaml's IssueDetails schema), and Reader.Get now parses it
// back onto RowVersion (HIGH 5), so a canned response answering "" would
// be a server this client cannot follow, not the empty detail view this
// double meant to stand in for.
*body = types.IssueDetails{Revision: "1"}
}
return nil
}
func recordingStore(t *testing.T) (*Store, *recordingWire) {
t.Helper()
w := &recordingWire{}
return New(testTarget(t), w, &apigen.ContextResponse{}), w
}
// TestEveryDispatchSiteHonorsTheTwoSpeedPolicy is D6's mechanism, checked at
// the seam rather than at each call site.
//
// The POLICY lives in the wire package — a baseline operation returns from
// Preflight immediately, every other one forces the handshake and consults the
// advertised token — so what this store owes is that no operation reaches the
// transport without going through it. Routing every role through one dispatch
// helper is how that is made true; this is what proves the helper is the only
// route, and it names the baseline classification of each operation these roles
// use so a reclassification upstream lands here rather than silently.
func TestEveryDispatchSiteHonorsTheTwoSpeedPolicy(t *testing.T) {
ctx := context.Background()
s, w := recordingStore(t)
reader, err := s.IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
if _, err := reader.Ready(ctx, issueops.ReadyRequest{}); err != nil {
t.Fatalf("Ready: %v", err)
}
if _, err := reader.List(ctx, issueops.ListRequest{SortBy: "created"}); err != nil {
t.Fatalf("List: %v", err)
}
if _, err := reader.Get(ctx, issueops.GetRequest{ID: "bd-1"}); err != nil {
t.Fatalf("Get: %v", err)
}
querier, err := s.Querier()
if err != nil {
t.Fatalf("Querier(): %v", err)
}
if _, err := querier.Query(ctx, issueops.QueryRequest{Expression: "type=bug"}); err != nil {
t.Fatalf("Query: %v", err)
}
counter, err := s.ReadyCounter()
if err != nil {
t.Fatalf("ReadyCounter(): %v", err)
}
if _, err := counter.CountReady(ctx, issueops.ReadyRequest{}); err != nil {
t.Fatalf("CountReady: %v", err)
}
if _, err := s.GetConfig(ctx, "issue_prefix"); err != nil {
t.Fatalf("GetConfig: %v", err)
}
if _, err := s.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{"bd-1"}}); err != nil {
t.Fatalf("SearchIssues: %v", err)
}
if len(w.preflighted) != len(w.dispatched) {
t.Fatalf("%d pre-flights for %d dispatches (%v vs %v): a dispatch that skipped the pre-flight would "+
"answer an older server's bare 404 as an entity's not_found",
len(w.preflighted), len(w.dispatched), w.preflighted, w.dispatched)
}
for i, op := range w.dispatched {
if w.preflighted[i] != op {
t.Errorf("dispatch %d pre-flighted %q and dialed %q", i, w.preflighted[i], op)
}
}
// The classification the pre-flight then applies. Stated here so a change to
// the baseline set upstream is a failure in this package rather than an
// extra round trip nobody notices on the hot work-distribution path.
for op, baseline := range map[string]bool{
wire.OpListReadyWork: true,
wire.OpListIssues: true,
wire.OpGetIssue: true,
wire.OpQueryIssues: false,
wire.OpCountReadyWork: false,
wire.OpGetSetting: false,
// claimIssue is first-slice but NOT baseline: it forces the handshake so
// the identity gate runs before a write lands (ga-b8ddd.11).
wire.OpClaimIssue: false,
} {
if wire.IsBaseline(op) != baseline {
t.Errorf("wire.IsBaseline(%q) = %v, want %v", op, wire.IsBaseline(op), baseline)
}
}
}
// TestDispatchWithoutATransportIsABuildWiringFault: a binary that registered
// this backend without linking a wire client is a build fault, not a user's,
// and the store says so rather than panicking on a nil.
func TestDispatchWithoutATransportIsABuildWiringFault(t *testing.T) {
s := New(testTarget(t), nil, nil)
reader, err := s.IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
if _, err := reader.Ready(context.Background(), issueops.ReadyRequest{}); !errors.Is(err, ErrNoTransport) {
t.Errorf("Ready with no transport = %v, want ErrNoTransport", err)
}
}
// TestDefaultListLimitMatchesTheSharedDefault is the drift pin for the one
// constant this package had to copy. depguard denies internal/workapi here, but
// not to a test file, which is exactly the exemption this uses.
func TestDefaultListLimitMatchesTheSharedDefault(t *testing.T) {
if defaultListLimit != workapi.DefaultListLimit {
t.Errorf("defaultListLimit = %d, want workapi.DefaultListLimit = %d: a nil ListRequest.Limit would "+
"then trim to a different page over http than it does locally", defaultListLimit, workapi.DefaultListLimit)
}
}
// TestCompareIssuesByMatchesTheSharedComparator is the drift pin for the other
// copy: the display comparator the page epilogue applies.
//
// It is driven over a generated corpus rather than a handful of pairs because
// the interesting cases are the ones nobody writes down — equal keys, a nil
// ClosedAt against a set one, a title that differs only by case, ids whose
// natural and lexical orders disagree.
func TestCompareIssuesByMatchesTheSharedComparator(t *testing.T) {
rng := rand.New(rand.NewSource(1))
base := time.Date(2026, 8, 8, 12, 0, 0, 0, time.UTC)
titles := []string{"alpha", "Alpha", "beta", ""}
statuses := []types.Status{types.StatusOpen, types.StatusClosed, types.StatusInProgress}
assignees := []string{"", "ana", "Bo"}
corpus := make([]*types.Issue, 0, 40)
for i := 0; i < 40; i++ {
issue := &types.Issue{
ID: "bd-" + strconv.Itoa(rng.Intn(20)),
Title: titles[rng.Intn(len(titles))],
Status: statuses[rng.Intn(len(statuses))],
Priority: rng.Intn(4),
IssueType: types.TypeTask,
Assignee: assignees[rng.Intn(len(assignees))],
CreatedAt: base.Add(time.Duration(rng.Intn(5)) * time.Hour),
UpdatedAt: base.Add(time.Duration(rng.Intn(5)) * time.Hour),
}
if rng.Intn(2) == 0 {
closed := base.Add(time.Duration(rng.Intn(5)) * time.Hour)
issue.ClosedAt = &closed
}
corpus = append(corpus, issue)
}
for _, sortBy := range []string{"", "priority", "created", "updated", "closed", "status", "id", "title", "type", "assignee", "nonesuch"} {
for _, a := range corpus {
for _, b := range corpus {
if got, want := compareIssuesBy(a, b, sortBy), workapi.CompareIssuesBy(a, b, sortBy); got != want {
t.Fatalf("compareIssuesBy(%q) = %d, workapi.CompareIssuesBy = %d for\n a: %+v\n b: %+v",
sortBy, got, want, a, b)
}
}
}
}
}
// TestReadRolesRefuseWhatTheWireCannotCarry pins the refusal SHAPE the roles
// hand back, without a server: both sentinels are reachable off one value, and
// the ledger row travels with it so D7's third taxonomy text has a flag and a
// reason to print.
func TestReadRolesRefuseWhatTheWireCannotCarry(t *testing.T) {
ctx := context.Background()
s, w := recordingStore(t)
reader, err := s.IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
_, err = reader.List(ctx, issueops.ListRequest{IDFilter: "bd-1"})
var inexpressible *InexpressibleError
if !errors.As(err, &inexpressible) {
t.Fatalf("List with an IDFilter = %v, want *InexpressibleError", err)
}
if inexpressible.Refused.Row.Field != "IDFilter" {
t.Errorf("the refusal names %q, want IDFilter", inexpressible.Refused.Row.Field)
}
if inexpressible.Refused.Row.SpecRow == "" || inexpressible.Refused.Row.Why == "" {
t.Error("the refusal carries a ledger row with no reason or no citation")
}
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) || unsup.Backend != Backend {
t.Errorf("the refusal does not classify as *storage.ErrUnsupported for this backend: %v", err)
}
if !errors.Is(err, encode.ErrRefused) {
t.Errorf("the refusal does not classify as encode.ErrRefused: %v", err)
}
if unsup.Op != "Reader.List" {
t.Errorf("the refusal names Op %q, want the ROLE METHOD: nothing on the unsupported allowlist refuses this way", unsup.Op)
}
// A refusal never dials. The encoder decides it, so the round trip that
// would have carried a filter the server cannot apply never happens.
if len(w.dispatched) != 0 {
t.Errorf("a refused request dialed %v", w.dispatched)
}
}
// TestWriteRoleRefusalsMatchTheReadShape pins that a write-side refusal now
// satisfies errors.As(*storage.ErrUnsupported) exactly the way a read's does
// (TestReadRolesRefuseWhatTheWireCannotCarry, above): Sweeper.Sweep's Limit,
// CycleDetector.DetectCycles' IncludeTracks, and ReadyClaimer.ClaimNext's
// filter all raised a bare *encode.RefusedError before this review round and
// none of the three went through (*Store).inexpressible the way every read
// role already did. A caller classifying on *storage.ErrUnsupported (rather
// than reaching into the ledger row directly) got three different answers
// depending on which role it called; this is what makes it one answer.
func TestWriteRoleRefusalsMatchTheReadShape(t *testing.T) {
ctx := context.Background()
assertUnsupported := func(t *testing.T, err error, wantOp string) {
t.Helper()
var inexpressible *InexpressibleError
if !errors.As(err, &inexpressible) {
t.Fatalf("got %v, want *InexpressibleError", err)
}
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) || unsup.Backend != Backend {
t.Fatalf("the refusal does not classify as *storage.ErrUnsupported for this backend: %v", err)
}
if !errors.Is(err, encode.ErrRefused) {
t.Errorf("the refusal does not classify as encode.ErrRefused: %v", err)
}
if unsup.Op != wantOp {
t.Errorf("the refusal names Op %q, want %q", unsup.Op, wantOp)
}
}
t.Run("Sweeper.Sweep Limit", func(t *testing.T) {
s, w := recordingStore(t)
sweeper, err := s.Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
_, err = sweeper.Sweep(ctx, issueops.SweepRequest{Tier: "ephemeral", Limit: 5})
assertUnsupported(t, err, "Sweeper.Sweep")
if len(w.dispatched) != 0 {
t.Errorf("a refused sweep dialed %v", w.dispatched)
}
})
t.Run("CycleDetector.DetectCycles IncludeTracks", func(t *testing.T) {
s, w := recordingStore(t)
detector, err := s.CycleDetector()
if err != nil {
t.Fatalf("CycleDetector(): %v", err)
}
_, err = detector.DetectCycles(ctx, issueops.DetectCyclesRequest{IncludeTracks: true})
assertUnsupported(t, err, "CycleDetector.DetectCycles")
if len(w.dispatched) != 0 {
t.Errorf("a refused DetectCycles dialed %v", w.dispatched)
}
})
t.Run("ReadyClaimer.ClaimNext", func(t *testing.T) {
s, w := recordingStore(t)
claimer, err := s.ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer(): %v", err)
}
molType := issueops.MolType(types.MolTypeWork)
_, err = claimer.ClaimNext(ctx, issueops.ClaimNextRequest{
Actor: "ana",
Filter: issueops.ReadyRequest{MolType: &molType},
})
assertUnsupported(t, err, "ReadyClaimer.ClaimNext")
if len(w.dispatched) != 0 {
t.Errorf("a refused ClaimNext dialed %v", w.dispatched)
}
})
}
// TestTheRolesOwnPageRefusalsAreValidationNotCapability separates the two kinds
// of "no" a caller can get, because the recovery differs: a request the ROLE
// forbids is the caller's to fix, and a request the WIRE cannot carry is a
// statement about this backend.
func TestTheRolesOwnPageRefusalsAreValidationNotCapability(t *testing.T) {
ctx := context.Background()
s, _ := recordingStore(t)
counter, err := s.ReadyCounter()
if err != nil {
t.Fatalf("ReadyCounter(): %v", err)
}
for _, req := range []issueops.ReadyRequest{
{Limit: ptrTo(5)},
{Limit: ptrTo(0)},
{Offset: 1},
} {
if _, err := counter.CountReady(ctx, req); !errors.Is(err, issueops.ErrValidation) {
t.Errorf("CountReady(%+v) = %v, want ErrValidation: a cardinality has no page", req, err)
}
}
querier, err := s.Querier()
if err != nil {
t.Fatalf("Querier(): %v", err)
}
if _, err := querier.Query(ctx, issueops.QueryRequest{Expression: "type=bug", Offset: -1}); !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Query with a negative Offset = %v, want ErrValidation", err)
}
if _, err := querier.Query(ctx, issueops.QueryRequest{Expression: "type=bug", Offset: 1, SortBy: "priority"}); !errors.Is(err, issueops.ErrValidation) {
t.Errorf("Query with an Offset under a display order = %v, want ErrValidation", err)
}
// The one Offset shape that is this BACKEND's inability rather than the
// request's fault classifies the other way.
_, err = querier.Query(ctx, issueops.QueryRequest{Expression: "type=bug", Offset: 1})
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) {
t.Errorf("Query with a plain Offset = %v, want *ErrUnsupported", err)
}
}
// TestSearchIssuesRefusesAPartialIDWithItsOwnText pins D11's dedicated refusal.
// The raw "failed to search issues" fallthrough it replaces answers the wrong
// question: the input may be a partial id or a full id that does not exist.
func TestSearchIssuesRefusesAPartialIDWithItsOwnText(t *testing.T) {
s, w := recordingStore(t)
_, err := s.SearchIssues(context.Background(), "bd-a3f", types.IssueFilter{})
var partial *PartialIDSearchError
if !errors.As(err, &partial) {
t.Fatalf("a substring SearchIssues = %v, want *PartialIDSearchError", err)
}
if partial.Input != "bd-a3f" {
t.Errorf("the refusal echoes %q, want the caller's own input", partial.Input)
}
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) || unsup.Backend != Backend {
t.Errorf("the refusal does not classify as *storage.ErrUnsupported: %v", err)
}
if len(w.dispatched) != 0 {
t.Errorf("a partial-id refusal dialed %v; there is no operation to dial", w.dispatched)
}
}
// TestExactIDFanOutIsOneGetIssuePerID pins the D11 fast path's wire shape: one
// getIssue per named id, in the caller's order, with no listing call at all.
func TestExactIDFanOutIsOneGetIssuePerID(t *testing.T) {
s, w := recordingStore(t)
if _, err := s.SearchIssues(context.Background(), "", types.IssueFilter{IDs: []string{"bd-1", "bd-2", "bd-3"}}); err != nil {
t.Fatalf("SearchIssues: %v", err)
}
if len(w.requests) != 3 {
t.Fatalf("the fan-out issued %d requests, want one per id", len(w.requests))
}
for i, want := range []string{"bd-1", "bd-2", "bd-3"} {
if w.requests[i].Op != wire.OpGetIssue {
t.Errorf("request %d dialed %q, want getIssue", i, w.requests[i].Op)
}
if w.requests[i].IssueID != want {
t.Errorf("request %d names issue %q, want %q in the caller's order", i, w.requests[i].IssueID, want)
}
}
}
// TestTheExactIDsFanOutIsBounded: an unbounded id set would be an unbounded
// burst at one shared server, so the encoder bounds it and the store surfaces
// the refusal rather than the burst.
func TestTheExactIDsFanOutIsBounded(t *testing.T) {
s, w := recordingStore(t)
ids := make([]string, encode.MaxExactIDs+1)
for i := range ids {
ids[i] = "bd-" + strconv.Itoa(i)
}
if _, err := s.SearchIssues(context.Background(), "", types.IssueFilter{IDs: ids}); !errors.Is(err, encode.ErrRefused) {
t.Errorf("a fan-out past the bound = %v, want the ledgered refusal", err)
}
if len(w.dispatched) != 0 {
t.Errorf("a refused fan-out still dialed %d times", len(w.dispatched))
}
}
func ptrTo[T any](v T) *T { return &v }

View file

@ -0,0 +1,457 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_batch_apply_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"errors"
"strings"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The BatchApplier contract, run through client -> in-process bd serve ->
// reference store: the widest role on this surface and the last of the wire
// wave's three, wired by client wave ga-mijra.
//
// WHAT THE COMPOSITION BUYS HERE that the three in-tree legs cannot. Those legs
// run two bodies through different transaction wrappers; this one adds a fourth
// wrapper that is a NETWORK, and the states it can lose are exactly the ones
// this contract is built to separate: the ORDER of a heterogeneous plan, which
// becomes an array on a JSON wire and comes back positional; the row-version
// tokens, which are 64-bit and would corrupt through a float; the absent-versus-
// zero distinction on every guard; a metadata value's source literal; and the
// identity of the item that refused, which on an all-or-nothing operation
// exists nowhere but the problem document's item_* members.
//
// ONE ENVIRONMENT PER CASE, like the other per-role families here: the contract
// namespaces its ids by prefix precisely so it can be run that way, and a
// shared database would turn an id collision between two contracts into a
// debugging session.
// applyParkBead owns this family's two parks: L-apply-ref's unparks when the
// wire grows a typed ref-key member on the problem document, and
// W-DepAddItem.HasSpawner's when ApplyDepAddItem publishes a spawner member.
const applyParkBead = "ga-mijra"
func newServedBatchApplyFixture(t *testing.T, prefix string) conformance.BatchApplyFixture {
t.Helper()
env := newServedEnv(t, prefix)
applier, err := env.subject.BatchApplier()
if err != nil {
t.Fatalf("BatchApplier(): %v", err)
}
return conformance.BatchApplyFixture{
IssuePrefix: env.prefix,
BatchApplier: applier,
CreateIssue: env.createIssue,
CreateWisp: env.createWisp,
QueryScalar: env.queryScalar,
CountHistory: env.countHistory,
CountHistoryMatching: env.countHistoryMatching,
CommitPending: env.commitPending,
}
}
func TestServedBatchApplyAppliesEveryItemInDeclarationOrder(t *testing.T) {
conformance.RunBatchApplyAppliesEveryItemInDeclarationOrder(t, t.Context(), newServedBatchApplyFixture(t, "hba00"))
}
func TestServedBatchApplyBindsEachNamedKeyToItsMintedID(t *testing.T) {
conformance.RunBatchApplyBindsEachNamedKeyToItsMintedID(t, t.Context(), newServedBatchApplyFixture(t, "hba01"))
}
func TestServedBatchApplyResolvesABackwardKeyRef(t *testing.T) {
conformance.RunBatchApplyResolvesABackwardKeyRef(t, t.Context(), newServedBatchApplyFixture(t, "hba02"))
}
func TestServedBatchApplyRefusesAKeyDeclaredLater(t *testing.T) {
conformance.RunBatchApplyRefusesAKeyDeclaredLater(t, t.Context(), newServedBatchApplyFixture(t, "hba03"))
}
func TestServedBatchApplyRefusesAKeyNoItemDeclares(t *testing.T) {
conformance.RunBatchApplyRefusesAKeyNoItemDeclares(t, t.Context(), newServedBatchApplyFixture(t, "hba04"))
}
func TestServedBatchApplyRefusesARefNamingNeitherOrBoth(t *testing.T) {
conformance.RunBatchApplyRefusesARefNamingNeitherOrBoth(t, t.Context(), newServedBatchApplyFixture(t, "hba05"))
}
func TestServedBatchApplyRollsBackEverythingWhenTheLastItemRefuses(t *testing.T) {
conformance.RunBatchApplyRollsBackEverythingWhenTheLastItemRefuses(t, t.Context(), newServedBatchApplyFixture(t, "hba06"))
}
func TestServedBatchApplyNeverReordersItsItems(t *testing.T) {
conformance.RunBatchApplyNeverReordersItsItems(t, t.Context(), newServedBatchApplyFixture(t, "hba07"))
}
func TestServedBatchApplyEndGateRefusesAHierarchyTheRequestBuilt(t *testing.T) {
conformance.RunBatchApplyEndGateRefusesAHierarchyTheRequestBuilt(t, t.Context(), newServedBatchApplyFixture(t, "hba08"))
}
func TestServedBatchApplyEndGateCycleSurvivesSkipPerEdgeCycleCheck(t *testing.T) {
conformance.RunBatchApplyEndGateCycleSurvivesSkipPerEdgeCycleCheck(t, t.Context(), newServedBatchApplyFixture(t, "hba09"))
}
func TestServedBatchApplyExpectedVersionThatMatchesLetsTheItemThrough(t *testing.T) {
conformance.RunBatchApplyExpectedVersionThatMatchesLetsTheItemThrough(t, t.Context(), newServedBatchApplyFixture(t, "hba0a"))
}
func TestServedBatchApplyStaleExpectedVersionRefusesTheWholeRequest(t *testing.T) {
conformance.RunBatchApplyStaleExpectedVersionRefusesTheWholeRequest(t, t.Context(), newServedBatchApplyFixture(t, "hba0b"))
}
func TestServedBatchApplyRefusesExpectedVersionOnARowAnEarlierItemTouched(t *testing.T) {
conformance.RunBatchApplyRefusesExpectedVersionOnARowAnEarlierItemTouched(t, t.Context(), newServedBatchApplyFixture(t, "hba0c"))
}
func TestServedBatchApplyRefusesExpectedVersionOnARowAnEarlierItemCreated(t *testing.T) {
conformance.RunBatchApplyRefusesExpectedVersionOnARowAnEarlierItemCreated(t, t.Context(), newServedBatchApplyFixture(t, "hba0d"))
}
func TestServedBatchApplyEvaluatesExpectedStatusAsModified(t *testing.T) {
conformance.RunBatchApplyEvaluatesExpectedStatusAsModified(t, t.Context(), newServedBatchApplyFixture(t, "hba0e"))
}
func TestServedBatchApplyEvaluatesExpectedAssigneeAsModified(t *testing.T) {
conformance.RunBatchApplyEvaluatesExpectedAssigneeAsModified(t, t.Context(), newServedBatchApplyFixture(t, "hba0f"))
}
func TestServedBatchApplyClosePolicyEvaluatesAtTheCloseItem(t *testing.T) {
conformance.RunBatchApplyClosePolicyEvaluatesAtTheCloseItem(t, t.Context(), newServedBatchApplyFixture(t, "hba10"))
}
func TestServedBatchApplyAllowsAClosedParentToGainAnOpenChild(t *testing.T) {
conformance.RunBatchApplyAllowsAClosedParentToGainAnOpenChild(t, t.Context(), newServedBatchApplyFixture(t, "hba11"))
}
func TestServedBatchApplyUpdateAfterCloseInOneRequest(t *testing.T) {
conformance.RunBatchApplyUpdateAfterCloseInOneRequest(t, t.Context(), newServedBatchApplyFixture(t, "hba12"))
}
func TestServedBatchApplyReportsChangedPerItem(t *testing.T) {
conformance.RunBatchApplyReportsChangedPerItem(t, t.Context(), newServedBatchApplyFixture(t, "hba13"))
}
func TestServedBatchApplyANoOpBatchRecordsNoHistory(t *testing.T) {
conformance.RunBatchApplyANoOpBatchRecordsNoHistory(t, t.Context(), newServedBatchApplyFixture(t, "hba14"))
}
func TestServedBatchApplyRecordsOneEntryForAWriteThatLandedNothing(t *testing.T) {
conformance.RunBatchApplyRecordsOneEntryForAWriteThatLandedNothing(t, t.Context(), newServedBatchApplyFixture(t, "hba15"))
}
func TestServedBatchApplyRecordsExactlyOneHistoryEntry(t *testing.T) {
conformance.RunBatchApplyRecordsExactlyOneHistoryEntry(t, t.Context(), newServedBatchApplyFixture(t, "hba16"))
}
func TestServedBatchApplyHistoryNamesTheActorAndReadsTheProvenance(t *testing.T) {
conformance.RunBatchApplyHistoryNamesTheActorAndReadsTheProvenance(t, t.Context(), newServedBatchApplyFixture(t, "hba17"))
}
func TestServedBatchApplyARefusedRequestRecordsNoHistory(t *testing.T) {
conformance.RunBatchApplyARefusedRequestRecordsNoHistory(t, t.Context(), newServedBatchApplyFixture(t, "hba18"))
}
func TestServedBatchApplyAnEphemeralBatchKeepsItsWispsAndRecordsNoDurableHistory(t *testing.T) {
conformance.RunBatchApplyAnEphemeralBatchKeepsItsWispsAndRecordsNoDurableHistory(t, t.Context(), newServedBatchApplyFixture(t, "hba19"))
}
func TestServedBatchApplyRefusesACrossPlaneEdgeBetweenRowsItCreated(t *testing.T) {
conformance.RunBatchApplyRefusesACrossPlaneEdgeBetweenRowsItCreated(t, t.Context(), newServedBatchApplyFixture(t, "hba1a"))
}
func TestServedBatchApplyAcceptsAnExternalEdgeTarget(t *testing.T) {
conformance.RunBatchApplyAcceptsAnExternalEdgeTarget(t, t.Context(), newServedBatchApplyFixture(t, "hba1b"))
}
func TestServedBatchApplyNormalizesTheWaitsForGate(t *testing.T) {
conformance.RunBatchApplyNormalizesTheWaitsForGate(t, t.Context(), newServedBatchApplyFixture(t, "hba1c"))
}
// TestServedBatchApplyStampsSpawnerIDOnlyWhenNamed parks on the edge item's
// spawner flag. The case's second half, an edge that names no spawner, is what
// this wire writes for every waits-for edge; its first half is the item the
// client refuses.
func TestServedBatchApplyStampsSpawnerIDOnlyWhenNamed(t *testing.T) {
skipKnownDivergence(t, "W-DepAddItem.HasSpawner", applyParkBead,
"the case names a spawner on a waits-for edge (DepAddItem.HasSpawner), and ApplyDepAddItem publishes no "+
"spawner member, so the client refuses the item rather than letting the server store the edge without "+
"the spawner_id the role would stamp from its resolved target.")
conformance.RunBatchApplyStampsSpawnerIDOnlyWhenNamed(t, t.Context(), newServedBatchApplyFixture(t, "hba27"))
}
func TestServedBatchApplySplicesAForwardMetadataRef(t *testing.T) {
conformance.RunBatchApplySplicesAForwardMetadataRef(t, t.Context(), newServedBatchApplyFixture(t, "hba1d"))
}
func TestServedBatchApplySplicesASelfMetadataRef(t *testing.T) {
conformance.RunBatchApplySplicesASelfMetadataRef(t, t.Context(), newServedBatchApplyFixture(t, "hba1e"))
}
// TestServedBatchApplyRefusesAMetadataRefNoItemDeclares is the family's
// response-shape park, a divergence of shape rather than of behavior: the
// refusal happens, nothing is written, and the diagnosis a caller ACTS on —
// DeclaredLater — arrives whole. What the wire cannot carry is WHICH entry of
// the refs map failed.
func TestServedBatchApplyRefusesAMetadataRefNoItemDeclares(t *testing.T) {
skipKnownDivergence(t, "L-apply-ref", applyParkBead,
"the case binds RefError.Member to `metadata_ref <key>`, and the wire names the MEMBER that held the bad ref "+
"(`items[0].create.metadata_refs`) without saying which entry of it failed — RefError.Member is diagnostic "+
"prose on both sides rather than a vocabulary, so the server maps it onto the document's own member names. "+
"The refusal itself, the untouched tables and the false DeclaredLater are asserted by "+
"TestServedBatchApplyRefusesAMetadataRefWithoutNamingTheKey.")
// The call stays BELOW the skip and compiled, which is this package's park
// convention and is load-bearing rather than decorative: a parked case that
// only named its contract in prose is a dangling reference nothing
// type-checks, so a renamed entrypoint or a changed fixture would orphan the
// park silently. Here it breaks the build.
conformance.RunBatchApplyRefusesAMetadataRefNoItemDeclares(t, t.Context(), newServedBatchApplyFixture(t, "hba1f"))
}
func TestServedBatchApplyTheSpliceRecordsAnUpdateEvent(t *testing.T) {
conformance.RunBatchApplyTheSpliceRecordsAnUpdateEvent(t, t.Context(), newServedBatchApplyFixture(t, "hba20"))
}
func TestServedBatchApplyKeepsAStoredNullApartFromAnEmptyString(t *testing.T) {
conformance.RunBatchApplyKeepsAStoredNullApartFromAnEmptyString(t, t.Context(), newServedBatchApplyFixture(t, "hba21"))
}
func TestServedBatchApplyLandsAnIdempotencyRecordWithItsWork(t *testing.T) {
conformance.RunBatchApplyLandsAnIdempotencyRecordWithItsWork(t, t.Context(), newServedBatchApplyFixture(t, "hba22"))
}
func TestServedBatchApplyBoundsTheItemCount(t *testing.T) {
fixture := newServedBatchApplyFixture(t, "hba23")
if raceEnabled {
// Under -race the full 1000-item apply outlasts the client's 60s
// per-request timeout (wire.DefaultTimeout) on the embedded lane's
// executors, so only the "at bound" half's applied count drops, to
// 150 (the whole case then took 26s there), as the embedded tier's
// own TestBatchApplyContract does; see
// RunBatchApplyBoundsTheItemCountAtScale for what that leaves pinned.
// The refusing half still sends MaxApplyBatchItems+1 over the wire,
// and scripts/conformance.sh runs the full size without -race.
conformance.RunBatchApplyBoundsTheItemCountAtScale(t, t.Context(), fixture, 150)
return
}
conformance.RunBatchApplyBoundsTheItemCount(t, t.Context(), fixture)
}
func TestServedBatchApplyReplayMintsANewSetOfRows(t *testing.T) {
conformance.RunBatchApplyReplayMintsANewSetOfRows(t, t.Context(), newServedBatchApplyFixture(t, "hba24"))
}
func TestServedBatchApplyDoesNotMutateTheCallerRequest(t *testing.T) {
conformance.RunBatchApplyDoesNotMutateTheCallerRequest(t, t.Context(), newServedBatchApplyFixture(t, "hba25"))
}
func TestServedBatchApplyRefusesAnUnusableRequest(t *testing.T) {
conformance.RunBatchApplyRefusesAnUnusableRequest(t, t.Context(), newServedBatchApplyFixture(t, "hba26"))
}
// TestServedBatchApplyRefusesAMetadataRefWithoutNamingTheKey is the running pin
// beside the park above: the same request, driven end to end, asserting
// everything the contract asserts EXCEPT the key inside the member — the
// refusal is a *RefError matching ErrValidation, DeclaredLater is false, the
// item is named, and nothing was written.
//
// It is written so it CAN fail: the positive half re-runs the identical plan
// with the ref pointed at a key the request does declare, and the row lands
// with the resolved id spliced over the metadata key. A client that refused
// every metadata ref would pass the refusal half alone.
func TestServedBatchApplyRefusesAMetadataRefWithoutNamingTheKey(t *testing.T) {
ctx := t.Context()
fixture := newServedBatchApplyFixture(t, "hbaref")
id := fixture.IssuePrefix + "-ghostmeta-row"
item := issueops.ApplyItem{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{
Key: "only",
Issue: &issueops.Issue{ID: id, Title: "names a key nothing declares", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
MetadataRefs: map[string]issueops.Ref{"gc.retry_of": {Key: "never-declared"}},
}}
_, err := fixture.BatchApplier.ApplyBatch(ctx, issueops.ApplyBatchRequest{
Actor: "apply-writer", ForceIDPrefix: true, Items: []issueops.ApplyItem{item},
})
var refErr *issueops.RefError
if !errors.As(err, &refErr) {
t.Fatalf("a metadata_ref naming an undeclared key: error = %v, want *RefError", err)
}
if refErr.DeclaredLater {
t.Errorf("RefError = %#v, want DeclaredLater false: no item declares that key at all", refErr)
}
if refErr.Index != 0 {
t.Errorf("RefError.Index = %d, want 0", refErr.Index)
}
if refErr.Key != "never-declared" {
t.Errorf("RefError.Key = %q, want the unresolvable key", refErr.Key)
}
// The degraded half, asserted rather than left implicit: the member is
// named without the key inside it (L-apply-ref). Asserting it here is what
// makes the ledger row falsifiable — the day the wire carries the key, this
// fails and the park retires with it.
if refErr.Member != "metadata_refs" {
t.Errorf("RefError.Member = %q, want the member alone; L-apply-ref records that the key is not on the wire", refErr.Member)
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("error = %v, want ErrValidation through RefError.Unwrap", err)
}
var rows int
if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM issues WHERE id = ?", []any{id}, &rows); err != nil {
t.Fatalf("counting the refused row: %v", err)
}
if rows != 0 {
t.Errorf("the refused plan wrote %s anyway", id)
}
// The positive half. The identical plan with the ref pointed at a key the
// request DOES declare lands, and the splice writes the resolved id.
peer := fixture.IssuePrefix + "-ghostmeta-peer"
item.Create.MetadataRefs = map[string]issueops.Ref{"gc.retry_of": {Key: "peer"}}
if _, err := fixture.BatchApplier.ApplyBatch(ctx, issueops.ApplyBatchRequest{
Actor: "apply-writer", ForceIDPrefix: true,
Items: []issueops.ApplyItem{item, {Kind: issueops.ItemCreate, Create: &issueops.CreateItem{
Key: "peer",
Issue: &issueops.Issue{ID: peer, Title: "the key it names", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}}},
}); err != nil {
t.Fatalf("the same plan with a declared key refused: %v", err)
}
var metadata string
if err := fixture.QueryScalar(ctx, "SELECT COALESCE(metadata, '') FROM issues WHERE id = ?", []any{id}, &metadata); err != nil {
t.Fatalf("reading the spliced metadata: %v", err)
}
if !strings.Contains(metadata, peer) {
t.Errorf("metadata = %q, want the resolved id %s spliced over gc.retry_of", metadata, peer)
}
}
// TestServedBatchApplyStampsEachCreateItemsCreatedByFromTheActor is the served
// half of created_by on the plan: ApplyCreateItem publishes no created_by, so
// the stored creator exists only because the server stamps it from the actor
// (internal/httpapi's batch_apply.go). A create item whose CreatedBy names that
// actor — the shape the graph apply sends — is carried by the stamp rather than
// refused.
func TestServedBatchApplyStampsEachCreateItemsCreatedByFromTheActor(t *testing.T) {
ctx := t.Context()
env := newServedEnv(t, "hbacby")
applier, err := env.subject.BatchApplier()
if err != nil {
t.Fatalf("BatchApplier(): %v", err)
}
res, err := applier.ApplyBatch(ctx, issueops.ApplyBatchRequest{
Actor: "plan-writer",
Items: []issueops.ApplyItem{{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{
Key: "planned",
Issue: &issueops.Issue{Title: "planned", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, CreatedBy: "plan-writer"},
}}},
})
if err != nil {
t.Fatalf("ApplyBatch in the graph apply's shape = %v, want it served", err)
}
id := res.Keys["planned"]
if id == "" {
t.Fatalf("Keys = %v, want the minted id bound to %q", res.Keys, "planned")
}
stored, err := env.getIssue(ctx, id)
if err != nil {
t.Fatalf("read back %s: %v", id, err)
}
if stored.CreatedBy != "plan-writer" {
t.Errorf("stored created_by = %q, want the actor %q", stored.CreatedBy, "plan-writer")
}
}
// TestServedBatchApplyAnswersEveryItemWithoutASnapshot is the running pin on
// ledger row L-apply-snapshot, and it is a DIFFERENTIAL rather than a golden:
// the same plan is applied through the client and through the reference
// store's own role, and the two results are compared member for member EXCEPT
// the snapshot. What the row admits — that Issue is nil on this leg — is
// asserted beside a local run where it is not, so the divergence is measured
// rather than declared.
//
// The positive half is the whole comparison: a client that answered an empty
// result, or dropped a revision, or lost the edge's DependsOnID, would satisfy
// "no snapshot" and fail here.
func TestServedBatchApplyAnswersEveryItemWithoutASnapshot(t *testing.T) {
ctx := t.Context()
env := newServedEnv(t, "hbasnap")
remote, err := env.subject.BatchApplier()
if err != nil {
t.Fatalf("BatchApplier(): %v", err)
}
local, err := env.reference.BatchApplier()
if err != nil {
t.Fatalf("reference BatchApplier(): %v", err)
}
plan := func(tag string) issueops.ApplyBatchRequest {
root := env.prefix + "-snap-" + tag + "-root"
leaf := env.prefix + "-snap-" + tag + "-leaf"
issue := func(id string) *issueops.Issue {
return &issueops.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
}
return issueops.ApplyBatchRequest{
Actor: "apply-writer", ForceIDPrefix: true,
Items: []issueops.ApplyItem{
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Key: "root", Issue: issue(root)}},
{Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Key: "leaf", Issue: issue(leaf)}},
{Kind: issueops.ItemDepAdd, DepAdd: &issueops.DepAddItem{
Source: issueops.Ref{Key: "leaf"}, Target: issueops.Ref{Key: "root"}, Type: types.DepParentChild,
}},
{Kind: issueops.ItemClose, Close: &issueops.CloseItem{Target: issueops.Ref{Key: "leaf"}, Reason: "done"}},
},
}
}
through, err := remote.ApplyBatch(ctx, plan("wire"))
if err != nil {
t.Fatalf("ApplyBatch over the wire: %v", err)
}
beside, err := local.ApplyBatch(ctx, plan("local"))
if err != nil {
t.Fatalf("ApplyBatch through the reference store: %v", err)
}
if len(through.Items) != len(beside.Items) {
t.Fatalf("the wire answered %d items and the reference %d", len(through.Items), len(beside.Items))
}
if len(through.Keys) != len(beside.Keys) {
t.Errorf("the wire bound %d keys and the reference %d", len(through.Keys), len(beside.Keys))
}
for key, id := range through.Keys {
if id == "" {
t.Errorf("Keys[%q] is empty; the key binding is the one fact the request cannot carry", key)
}
}
for i := range through.Items {
remoteItem, localItem := through.Items[i], beside.Items[i]
if remoteItem.Kind != localItem.Kind || remoteItem.Changed != localItem.Changed {
t.Errorf("items[%d]: wire %s/changed=%v, reference %s/changed=%v",
i, remoteItem.Kind, remoteItem.Changed, localItem.Kind, localItem.Changed)
}
if (remoteItem.DependsOnID == "") != (localItem.DependsOnID == "") {
t.Errorf("items[%d]: wire DependsOnID %q, reference %q — the edge target is set for dep_add and absent elsewhere",
i, remoteItem.DependsOnID, localItem.DependsOnID)
}
if (remoteItem.RowVersion == 0) != (localItem.RowVersion == 0) {
t.Errorf("items[%d]: wire revision %d, reference %d — a dep_add is 0 on both and a row item is not on either",
i, remoteItem.RowVersion, localItem.RowVersion)
}
// The divergence the row admits, measured in both directions at once.
if remoteItem.Issue != nil {
t.Errorf("items[%d] came back with a snapshot; the wire result is lean (L-apply-snapshot)", i)
}
if localItem.Kind != issueops.ItemDepAdd && localItem.Issue == nil {
t.Errorf("items[%d] carries no snapshot on the REFERENCE leg either; this case would then be asserting "+
"nothing about the divergence L-apply-snapshot records", i)
}
}
}

View file

@ -0,0 +1,170 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_batch_close_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// The BatchCloser contract against the served surface.
//
// The client sends the whole CloseBatchRequest on one issues:batchClose call,
// and the reference store answers with the per-item outcomes. The transactional
// ClaimNext the storage-level contract composes onto CloseBatch has NO v0 wire
// expression: BatchCloseRequest/BatchCloseResponse publish no
// claim_next/claimed_next member, so the client refuses any non-nil
// req.ClaimNext (D8 refuse-not-drop) rather than silently dropping the claim.
// The seven cases that exercise a real ClaimNext are parked with
// skipKnownDivergence citing W-CloseBatchRequest.ClaimNext; everything else —
// including the two cases that merely validate a ClaimNext filter's shape
// before any capability question is reached — runs for real.
//
// Seeding still never goes through the client: every fixture takes its seed and
// post-state hooks from the reference store the server serves, and binds only the
// BatchCloser under test to the http client (checkFixtureBinding).
func newServedBatchCloserFixture(t *testing.T, prefix string) conformance.BatchCloserFixture {
t.Helper()
env := newServedEnv(t, prefix)
closer, err := env.subject.BatchCloser()
if err != nil {
t.Fatalf("BatchCloser(): %v", err)
}
return conformance.BatchCloserFixture{
IssuePrefix: env.prefix,
Closer: closer,
CreateIssue: env.createIssue,
AddDependency: env.addDependency,
CreateWisp: env.createWisp,
AddComment: env.reference.AddComment,
QueryScalar: env.queryScalar,
CountHistory: env.countHistory,
// The message-scoped hook the wisp-naming case needs. Without it that
// case skips as UNPINNED, which is a weaker claim than this tier can
// make: the reference store behind the composition is embedded Dolt, so
// its log is readable BY MESSAGE and the clause is checkable here.
CountHistoryMatching: env.countHistoryMatching,
}
}
func TestServedBatchCloserOutcomeSnapshotIsTheDocumentedShape(t *testing.T) {
conformance.RunBatchCloserOutcomeSnapshotIsTheDocumentedShape(t, t.Context(), newServedBatchCloserFixture(t, "hbcsnap"))
}
func TestServedBatchCloserBackendFailureReturnsNoOutcomes(t *testing.T) {
conformance.RunBatchCloserBackendFailureReturnsNoOutcomes(t, t.Context(), newServedBatchCloserFixture(t, "hbcfail"))
}
func TestServedBatchCloserOutcomesMirrorItemsIndexForIndex(t *testing.T) {
conformance.RunBatchCloserOutcomesMirrorItemsIndexForIndex(t, t.Context(), newServedBatchCloserFixture(t, "hbcmir"))
}
func TestServedBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit(t *testing.T) {
conformance.RunBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit(t, t.Context(), newServedBatchCloserFixture(t, "hbcperitem"))
}
func TestServedBatchCloserRequestValidationReturnsZeroResultAndChangesNothing(t *testing.T) {
conformance.RunBatchCloserRequestValidationReturnsZeroResultAndChangesNothing(t, t.Context(), newServedBatchCloserFixture(t, "hbcval"))
}
func TestServedBatchCloserClaimFilterValueFailureIsARequestValidationFailure(t *testing.T) {
conformance.RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure(t, t.Context(), newServedBatchCloserFixture(t, "hbccfilt"))
}
func TestServedBatchCloserIdempotentRecloseIsAPerItemSuccess(t *testing.T) {
conformance.RunBatchCloserIdempotentRecloseIsAPerItemSuccess(t, t.Context(), newServedBatchCloserFixture(t, "hbcidem"))
}
func TestServedBatchCloserAllIdempotentBatchLandsNothing(t *testing.T) {
skipKnownDivergence(t, "W-CloseBatchRequest.ClaimNext", parkBead,
"the case drives a real ClaimNext through CloseBatch; the v0 wire's "+
"BatchCloseRequest/BatchCloseResponse publish no claim_next/claimed_next "+
"member, so the client refuses it (D8 refuse-not-drop) rather than silently "+
"dropping the claim")
conformance.RunBatchCloserAllIdempotentBatchLandsNothing(t, t.Context(), newServedBatchCloserFixture(t, "hbcallid"))
}
func TestServedBatchCloserDuplicateItemRecloseAtItsOwnIndex(t *testing.T) {
conformance.RunBatchCloserDuplicateItemRecloseAtItsOwnIndex(t, t.Context(), newServedBatchCloserFixture(t, "hbcdup"))
}
func TestServedBatchCloserWispItemClosesAndEarnsTheClaim(t *testing.T) {
skipKnownDivergence(t, "W-CloseBatchRequest.ClaimNext", parkBead,
"the case asserts the wisp close earns a real ClaimNext; the v0 wire has no "+
"claim_next/claimed_next member on BatchClose, so the client refuses the "+
"request rather than earning a claim it cannot report back")
conformance.RunBatchCloserWispItemClosesAndEarnsTheClaim(t, t.Context(), newServedBatchCloserFixture(t, "hbcwisp"))
}
func TestServedBatchCloserDurableHistoryNeverNamesAWisp(t *testing.T) {
conformance.RunBatchCloserDurableHistoryNeverNamesAWisp(t, t.Context(), newServedBatchCloserFixture(t, "hbcwhist"))
}
func TestServedBatchCloserForceBypassesOnlyClosePolicy(t *testing.T) {
conformance.RunBatchCloserForceBypassesOnlyClosePolicy(t, t.Context(), newServedBatchCloserFixture(t, "hbcforce"))
}
func TestServedBatchCloserClaimNextHydratesWhenSomethingClosed(t *testing.T) {
skipKnownDivergence(t, "W-CloseBatchRequest.ClaimNext", parkBead,
"the case needs CloseBatch to hydrate a real ClaimNext result; the v0 wire "+
"carries no claim_next/claimed_next member, so the client refuses rather "+
"than hydrating a claim from nothing")
conformance.RunBatchCloserClaimNextHydratesWhenSomethingClosed(t, t.Context(), newServedBatchCloserFixture(t, "hbccnhy"))
}
func TestServedBatchCloserClaimNextIsNilWhenNothingClosed(t *testing.T) {
skipKnownDivergence(t, "W-CloseBatchRequest.ClaimNext", parkBead,
"the case asserts a nil ClaimedNext after a real ClaimNext request landed "+
"nothing to close; the v0 wire has no member to carry the request at all, "+
"so the client refuses it before the nil-vs-populated question is reachable")
conformance.RunBatchCloserClaimNextIsNilWhenNothingClosed(t, t.Context(), newServedBatchCloserFixture(t, "hbccnno"))
}
func TestServedBatchCloserClaimNextIsNilWhenTheFrontIsEmpty(t *testing.T) {
skipKnownDivergence(t, "W-CloseBatchRequest.ClaimNext", parkBead,
"same as the other ClaimNext-on-CloseBatch cases: the v0 wire has no "+
"claim_next/claimed_next member, so the client refuses the request")
conformance.RunBatchCloserClaimNextIsNilWhenTheFrontIsEmpty(t, t.Context(), newServedBatchCloserFixture(t, "hbccnempty"))
}
func TestServedBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch(t *testing.T) {
skipKnownDivergence(t, "W-CloseBatchRequest.ClaimNext", parkBead,
"the case needs the batch's own unblocking to be visible to a ClaimNext run "+
"in the same request; the v0 wire cannot carry ClaimNext on CloseBatch at "+
"all, so the client refuses before the ordering question is reachable")
conformance.RunBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch(t, t.Context(), newServedBatchCloserFixture(t, "hbccnunb"))
}
func TestServedBatchCloserRecordsOneHistoryEntryForWhatLanded(t *testing.T) {
conformance.RunBatchCloserRecordsOneHistoryEntryForWhatLanded(t, t.Context(), newServedBatchCloserFixture(t, "hbc1hist"))
}
func TestServedBatchCloserAllRefusedBatchRecordsNoHistory(t *testing.T) {
conformance.RunBatchCloserAllRefusedBatchRecordsNoHistory(t, t.Context(), newServedBatchCloserFixture(t, "hbcnohist"))
}
func TestServedBatchCloserDoesNotMutateTheCallerRequest(t *testing.T) {
skipKnownDivergence(t, "W-CloseBatchRequest.ClaimNext", parkBead,
"the case populates req.ClaimNext with a real ready filter and closes for "+
"real to prove the caller's request pointer survives untouched; the v0 "+
"wire cannot carry ClaimNext on CloseBatch, so the client refuses before "+
"any closing happens")
conformance.RunBatchCloserDoesNotMutateTheCallerRequest(t, t.Context(), newServedBatchCloserFixture(t, "hbcnomut"))
}
// TestServedBatchCloserSettlesTheDependersOfWhatItClosed is the blocked-state
// postcondition, and the only case here whose observable is a column no read on
// this surface hydrates — so it goes to the reference store directly.
//
// It is the batch's own version of the clause the single close carries, and the
// batch is where it is easiest to get wrong: two items land in ONE transaction,
// so a body that settled per item, or settled only the items it walked last,
// leaves a depender of the first item marked blocked by a row that is closed.
func TestServedBatchCloserSettlesTheDependersOfWhatItClosed(t *testing.T) {
conformance.RunBatchCloserSettlesTheDependersOfWhatItClosed(t, t.Context(), newServedBatchCloserFixture(t, "hbcbs"))
}

View file

@ -0,0 +1,63 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_batch_getter_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// The BatchGetter contract, run through the http client against a real bd
// serve.
//
// This is the role behind gc's ready veto and the CLI's own id-resolution
// passes once they move off one Get per id: a caller names up to
// issueops.MaxGetManyIDs ids and gets back every one the store holds,
// hydrated and in request order, plus a Missing sentinel for every id that
// named no row. The cap and the blank-id checks are refused CLIENT-SIDE, in
// checkGetManyIDs, before the dial — batch_get.go's failBatchGetErr collapses
// every validation failure on this surface into one generic,
// code-less InvalidArgument, so a round trip could never hand this client
// back the typed *issueops.TooManyIDsError the RefusesOverTheCap case
// requires.
func TestServedBatchGetterContract(t *testing.T) {
e := newServedEnv(t, "bge")
getter, err := e.subject.BatchGetter()
if err != nil {
t.Fatalf("BatchGetter(): %v", err)
}
fixture := conformance.BatchGetterFixture{
IssuePrefix: "bge",
BatchGetter: getter,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
CountHistory: e.countHistory,
}
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.BatchGetterFixture)
}{
{"FindsRequestedIssues", conformance.RunBatchGetterFindsRequestedIssues},
{"ReportsMissingIDs", conformance.RunBatchGetterReportsMissingIDs},
{"CollapsesRepeatedIDs", conformance.RunBatchGetterCollapsesRepeatedIDs},
{"AnswersInRequestOrder", conformance.RunBatchGetterAnswersInRequestOrder},
{"ResolvesIDsExactly", conformance.RunBatchGetterResolvesIDsExactly},
{"AnswersAnEmptyRequest", conformance.RunBatchGetterAnswersAnEmptyRequest},
{"RefusesAnUnusableRequest", conformance.RunBatchGetterRefusesAnUnusableRequest},
{"RefusesOverTheCap", conformance.RunBatchGetterRefusesOverTheCap},
{"AcceptsExactlyTheCap", conformance.RunBatchGetterAcceptsExactlyTheCap},
{"HydratesLabels", conformance.RunBatchGetterHydratesLabels},
{"LeavesTheRequestAlone", conformance.RunBatchGetterLeavesTheRequestAlone},
{"SharesOneReadStructurally", conformance.RunBatchGetterSharesOneReadStructurally},
{"CrossesBothPlanes", conformance.RunBatchGetterCrossesBothPlanes},
{"WritesNothing", conformance.RunBatchGetterWritesNothing},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}

View file

@ -0,0 +1,664 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_bridge_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"sort"
"testing"
"github.com/steveyegge/beads/internal/httpclient/encode"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// The off-role text-path bridge, run as a DUAL RUN: the same question asked of
// the reference store directly and of the http client, and the two answers
// compared.
//
// That is the only form in which D4's parent-walk inversion can be believed. The
// encode gate proves the parameters round-trip through the server's own decoder;
// what it cannot prove is that the ROWS come back the same, because the derived
// exclusions the inversion inverts are applied by a query neither side of that
// gate runs. Here both sides run it.
//
// The fixtures are the spec's own pin list: the default rendering, `--all`, the
// `--include-*` variants, and a residual refusal.
// seedWalkTree plants a two-level tree plus the rows the derived defaults are
// supposed to hide: a closed child, a template child and a gate child.
func seedWalkTree(t *testing.T, ctx context.Context, e *servedEnv) {
t.Helper()
rows := []*types.Issue{
{ID: "wlk-root", Title: "root", Status: types.StatusOpen, IssueType: types.TypeTask},
{ID: "wlk-open", Title: "open child", Status: types.StatusOpen, IssueType: types.TypeTask},
{ID: "wlk-deep", Title: "grandchild", Status: types.StatusOpen, IssueType: types.TypeTask},
{ID: "wlk-closed", Title: "closed child", Status: types.StatusClosed, IssueType: types.TypeTask},
{ID: "wlk-template", Title: "template child", Status: types.StatusOpen, IssueType: types.TypeTask, IsTemplate: true},
{ID: "wlk-gate", Title: "gate child", Status: types.StatusOpen, IssueType: types.IssueType("gate")},
}
for _, row := range rows {
if err := e.createIssue(ctx, row, "seed"); err != nil {
t.Fatalf("seed %s: %v", row.ID, err)
}
}
for _, edge := range []*types.Dependency{
{IssueID: "wlk-open", DependsOnID: "wlk-root", Type: types.DepParentChild},
{IssueID: "wlk-closed", DependsOnID: "wlk-root", Type: types.DepParentChild},
{IssueID: "wlk-template", DependsOnID: "wlk-root", Type: types.DepParentChild},
{IssueID: "wlk-gate", DependsOnID: "wlk-root", Type: types.DepParentChild},
{IssueID: "wlk-deep", DependsOnID: "wlk-open", Type: types.DepParentChild},
} {
if err := e.addDependency(ctx, edge, "seed"); err != nil {
t.Fatalf("seed edge %s: %v", edge.IssueID, err)
}
}
}
// walkOverBoth runs one level of the walk against both stores.
//
// It reproduces findAllDescendants' own mutation exactly — a value copy of the
// built filter with ParentID re-pointed and Limit zeroed — because the whole
// question is whether the filter the CLI hands the store crosses intact.
func walkOverBoth(t *testing.T, ctx context.Context, e *servedEnv, in issueops.ListRequest, parent string) (local, remote []string, remoteErr error) {
t.Helper()
cfg, err := workapi.LoadStoreListConfig(ctx, e.reference)
if err != nil {
t.Fatalf("load the reference vocabulary: %v", err)
}
filter, err := workapi.BuildListFilter(in, cfg)
if err != nil {
t.Fatalf("BuildListFilter: %v", err)
}
filter.ParentID = &parent
filter.Limit = 0
// Every text rendering of `bd list` sets this, so the filter under test is
// the one the walk really receives.
filter.SkipCounts = true
localRows, err := e.reference.SearchIssues(ctx, "", filter)
if err != nil {
t.Fatalf("reference SearchIssues: %v", err)
}
remoteRows, remoteErr := e.subject.SearchIssues(ctx, "", filter)
return issueIDs(localRows), issueIDs(remoteRows), remoteErr
}
func issueIDs(rows []*types.Issue) []string {
out := make([]string, 0, len(rows))
for _, row := range rows {
out = append(out, row.ID)
}
sort.Strings(out)
return out
}
// TestTheParentWalkAnswersTheSameRowsOverHTTP is the dual run D4's pin list asks
// for.
func TestTheParentWalkAnswersTheSameRowsOverHTTP(t *testing.T) {
e := newServedEnv(t, "wlk")
ctx := t.Context()
seedWalkTree(t, ctx, e)
for _, tc := range []struct {
name string
in issueops.ListRequest
want []string
}{
{
// The fixture D4 exists for: a bare `bd list --parent <id>`, whose
// filter carries ExcludeStatus, Pinned, IsTemplate, the gate and
// infra exclusions and SkipWisps — none of which the wire publishes,
// and all of which the server re-derives from their own absence. It
// fails outright if the inversion is wrong in either direction.
name: "the default text rendering",
in: issueops.ListRequest{},
want: []string{"wlk-open"},
},
{
name: "--all admits the closed child",
in: issueops.ListRequest{AllFlag: true},
want: []string{"wlk-closed", "wlk-open"},
},
{
name: "--include-templates admits the template child",
in: issueops.ListRequest{IncludeTemplates: true},
want: []string{"wlk-open", "wlk-template"},
},
{
name: "--include-gates admits the gate child",
in: issueops.ListRequest{IncludeGates: true},
want: []string{"wlk-gate", "wlk-open"},
},
{
name: "--status closed selects only the closed child",
in: issueops.ListRequest{Status: "closed"},
want: []string{"wlk-closed"},
},
} {
t.Run(tc.name, func(t *testing.T) {
local, remote, err := walkOverBoth(t, ctx, e, tc.in, "wlk-root")
if err != nil {
t.Fatalf("the http walk refused: %v", err)
}
if !equalIDs(local, tc.want) {
t.Fatalf("the REFERENCE answered %v, the fixture expects %v — the fixture is wrong, not the client", local, tc.want)
}
if !equalIDs(remote, local) {
t.Errorf("http answered %v, the reference answered %v", remote, local)
}
})
}
}
// TestTheParentWalkRefusesAResidualOverHTTP is the residual-refusal case from
// the same pin list, run end to end: the refusal has to happen in the client,
// before a request that would answer a wider question is built.
func TestTheParentWalkRefusesAResidualOverHTTP(t *testing.T) {
e := newServedEnv(t, "wlr")
ctx := t.Context()
seedWalkTree(t, ctx, e)
_, _, err := walkOverBoth(t, ctx, e, issueops.ListRequest{ExcludeTypes: []string{"chore"}}, "wlk-root")
if !errors.Is(err, encode.ErrRefused) {
t.Fatalf("a --exclude-type walk returned %v, want a refusal", err)
}
var refusal *encode.RefusedError
if errors.As(err, &refusal) && refusal.Row.ID != "P-IssueFilter.ExcludeTypes" {
t.Errorf("the refusal cites %q, want P-IssueFilter.ExcludeTypes", refusal.Row.ID)
}
}
// TestTheReadyBridgeAnswersTheSameRowsOverHTTP is the other half of the text
// bridge: `bd ready`'s listing, which is still raw at tip.
//
// It feeds the filter workapi.BuildReadyFilter actually builds — Status=StatusOpen
// and all — rather than a hand-built WorkFilter{}. That hand-built shape, whose
// empty status the reference store reads as open+in_progress, is exactly what
// masked the ship blocker: the pre-fix bridge refused the StatusOpen every real
// `bd ready` carries, and a fixture that never sent one could not see it. The
// seeded in_progress row makes the open-only derivation observable.
func TestTheReadyBridgeAnswersTheSameRowsOverHTTP(t *testing.T) {
e := newServedEnv(t, "rdy")
ctx := t.Context()
for _, row := range []*types.Issue{
{ID: "rdy-1", Title: "ready one", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 1},
{ID: "rdy-2", Title: "ready two", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 2, Assignee: "ada"},
{ID: "rdy-3", Title: "in progress", Status: types.StatusInProgress, IssueType: types.TypeTask, Priority: 1},
{ID: "rdy-4", Title: "closed", Status: types.StatusClosed, IssueType: types.TypeTask},
} {
if err := e.createIssue(ctx, row, "seed"); err != nil {
t.Fatalf("seed %s: %v", row.ID, err)
}
}
for _, tc := range []struct {
name string
req issueops.ReadyRequest
}{
{"an unfiltered listing", issueops.ReadyRequest{Sort: "priority"}},
{"an assignee filter", issueops.ReadyRequest{Assignee: "ada", Sort: "priority"}},
{"a bounded page", issueops.ReadyRequest{Sort: "priority", Limit: ptrTo(1)}},
} {
t.Run(tc.name, func(t *testing.T) {
// The one shape the CLI produces: workapi.BuildReadyFilter stamps
// Status=StatusOpen, which the pre-fix bridge refused on sight.
filter, err := workapi.BuildReadyFilter(tc.req)
if err != nil {
t.Fatalf("BuildReadyFilter: %v", err)
}
local, err := e.reference.GetReadyWork(ctx, filter)
if err != nil {
t.Fatalf("reference GetReadyWork: %v", err)
}
remote, err := e.subject.GetReadyWork(ctx, filter)
if err != nil {
t.Fatalf("http GetReadyWork: %v", err)
}
if !equalIDs(issueIDs(remote), issueIDs(local)) {
t.Errorf("http answered %v, the reference answered %v", issueIDs(remote), issueIDs(local))
}
})
}
}
// TestTheReadyBridgeDualRunsBuildReadyFilterOverBothReadPaths is the ship-blocker
// regression pin (ga-b8ddd.13). Every real `bd ready` and `bd ready --json` builds
// its filter through workapi.BuildReadyFilter, which stamps Status=StatusOpen — the
// value the pre-fix bridge refused, so every http invocation failed before it
// dialed. This pushes that exact filter through BOTH read paths, the text
// GetReadyWork and the --json GetReadyWorkWithCounts, and byte-compares the http
// answer against the reference store's own. The in_progress and closed rows make
// the open-only derivation observable: a bridge that sent the wrong status, or a
// server that re-derived open+in_progress, would diverge here rather than pass.
func TestTheReadyBridgeDualRunsBuildReadyFilterOverBothReadPaths(t *testing.T) {
e := newServedEnv(t, "rdd")
ctx := t.Context()
for _, row := range []*types.Issue{
{ID: "rdd-open-hi", Title: "open high", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 0},
{ID: "rdd-open-lo", Title: "open low", Status: types.StatusOpen, IssueType: types.TypeTask, Priority: 3, Assignee: "ada"},
{ID: "rdd-inprog", Title: "in progress", Status: types.StatusInProgress, IssueType: types.TypeTask, Priority: 0},
{ID: "rdd-closed", Title: "closed", Status: types.StatusClosed, IssueType: types.TypeTask},
} {
if err := e.createIssue(ctx, row, "seed"); err != nil {
t.Fatalf("seed %s: %v", row.ID, err)
}
}
for _, tc := range []struct {
name string
req issueops.ReadyRequest
}{
{"the default listing", issueops.ReadyRequest{Sort: "priority"}},
{"an assignee filter", issueops.ReadyRequest{Assignee: "ada", Sort: "priority"}},
{"a bounded page", issueops.ReadyRequest{Sort: "priority", Limit: ptrTo(1)}},
} {
t.Run(tc.name, func(t *testing.T) {
filter, err := workapi.BuildReadyFilter(tc.req)
if err != nil {
t.Fatalf("BuildReadyFilter: %v", err)
}
if filter.Status != types.StatusOpen {
t.Fatalf("BuildReadyFilter produced Status=%q, want the StatusOpen this regression is about", filter.Status)
}
// The text path (`bd ready`).
localText, err := e.reference.GetReadyWork(ctx, filter)
if err != nil {
t.Fatalf("reference GetReadyWork: %v", err)
}
remoteText, err := e.subject.GetReadyWork(ctx, filter)
if err != nil {
t.Fatalf("http GetReadyWork refused the BuildReadyFilter shape: %v", err)
}
assertSameJSON(t, "GetReadyWork", localText, remoteText)
// The --json path (`bd ready --json`).
localCounts, err := e.reference.GetReadyWorkWithCounts(ctx, filter)
if err != nil {
t.Fatalf("reference GetReadyWorkWithCounts: %v", err)
}
remoteCounts, err := e.subject.GetReadyWorkWithCounts(ctx, filter)
if err != nil {
t.Fatalf("http GetReadyWorkWithCounts refused the BuildReadyFilter shape: %v", err)
}
assertSameJSON(t, "GetReadyWorkWithCounts", localCounts, remoteCounts)
// The --json path with its in-band total (upstream #6731): the
// same page, and the size of the whole ready set. "a bounded
// page" comes back truncated, so it exercises the countReadyWork
// round trip; the others answer from has_more alone.
localPage, localTotal, err := e.reference.GetReadyWorkWithCountsAndTotal(ctx, filter)
if err != nil {
t.Fatalf("reference GetReadyWorkWithCountsAndTotal: %v", err)
}
remotePage, remoteTotal, err := e.subject.GetReadyWorkWithCountsAndTotal(ctx, filter)
if err != nil {
t.Fatalf("http GetReadyWorkWithCountsAndTotal: %v", err)
}
assertSameJSON(t, "GetReadyWorkWithCountsAndTotal", localPage, remotePage)
if remoteTotal != localTotal {
t.Errorf("http total = %d, the reference answered %d", remoteTotal, localTotal)
}
unbounded := filter
unbounded.Limit = 0
all, err := e.reference.GetReadyWorkWithCounts(ctx, unbounded)
if err != nil {
t.Fatalf("reference unbounded GetReadyWorkWithCounts: %v", err)
}
if remoteTotal != len(all) {
t.Errorf("http total = %d, want the unbounded listing's %d", remoteTotal, len(all))
}
// Open-only is re-derived server-side from the status the bridge
// dropped: neither the in_progress nor the closed row may appear.
for _, got := range issueIDs(remoteText) {
if got == "rdd-inprog" || got == "rdd-closed" {
t.Errorf("ready work admitted %q; open-only was not re-derived", got)
}
}
})
}
}
// TestTheReadyBridgeRefusesAnInexpressibleFilter is L12 at the seam: a filter
// field with no wire parameter refuses rather than being dropped, because a
// dropped filter widens the answer invisibly.
//
// The examples are GENUINELY non-default: an in_progress restriction and a
// multi-status OR set, neither of which workapi.BuildReadyFilter ever produces.
// StatusOpen is deliberately absent — it is the derived default the bridge now
// drops, and asserting a refusal on it (as this test once did) is what cemented
// the ship blocker.
func TestTheReadyBridgeRefusesAnInexpressibleFilter(t *testing.T) {
e := newServedEnv(t, "rdr")
for _, tc := range []struct {
name string
filter types.WorkFilter
row string
}{
{
"an in_progress restriction the wire cannot state",
types.WorkFilter{Status: types.StatusInProgress},
"E-WorkFilter.Status",
},
{
// The derived-default Status passes the inversion; the populated
// OR-set the wire cannot carry still refuses on the residual sweep.
"a multi-status OR set",
types.WorkFilter{Status: types.StatusOpen, Statuses: []types.Status{types.StatusOpen, types.StatusInProgress}},
"E-WorkFilter.Statuses",
},
{
// An id exclusion set has no ready parameter; dropping it would
// list (and count) the very rows the caller excluded.
"an id exclusion set",
types.WorkFilter{Status: types.StatusOpen, ExcludeIDs: []string{"rdr-1"}},
"E-WorkFilter.ExcludeIDs",
},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := e.subject.GetReadyWork(t.Context(), tc.filter)
if !errors.Is(err, encode.ErrRefused) {
t.Fatalf("%s returned %v, want a refusal", tc.name, err)
}
var refusal *encode.RefusedError
if errors.As(err, &refusal) && refusal.Row.ID != tc.row {
t.Errorf("the refusal cites %q, want %q", refusal.Row.ID, tc.row)
}
// The in-band-total listing refuses the same filter the same way,
// before either request: its count encoder is the listing's.
_, _, err = e.subject.GetReadyWorkWithCountsAndTotal(t.Context(), tc.filter)
if !errors.Is(err, encode.ErrRefused) {
t.Fatalf("GetReadyWorkWithCountsAndTotal: %s returned %v, want a refusal", tc.name, err)
}
if errors.As(err, &refusal) && refusal.Row.ID != tc.row {
t.Errorf("GetReadyWorkWithCountsAndTotal: the refusal cites %q, want %q", refusal.Row.ID, tc.row)
}
})
}
}
// TestTheReadyBridgeEnforcesMaxRowsClientSide is D12 on the cursorless
// operation: the wire publishes no max_rows, so the cap is synthesized into the
// sentinel `bd ready` classifies into exit 2.
func TestTheReadyBridgeEnforcesMaxRowsClientSide(t *testing.T) {
e := newServedEnv(t, "rmx")
ctx := t.Context()
for _, id := range []string{"rmx-1", "rmx-2"} {
if err := e.createIssue(ctx, &types.Issue{ID: id, Title: id, Status: types.StatusOpen, IssueType: types.TypeTask}, "seed"); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
}
// The derived-default status the bridge drops; an empty status now refuses,
// so the cap is exercised on the shape `bd ready` actually sends.
if _, err := e.subject.GetReadyWork(ctx, types.WorkFilter{Status: types.StatusOpen}); err != nil {
t.Fatalf("an uncapped listing: %v", err)
}
_, err := e.subject.GetReadyWork(ctx, types.WorkFilter{Status: types.StatusOpen, MaxRows: 1, MaxRowsSource: "--max-rows"})
var tooMany *storageops.ErrTooManyRows
if !errors.As(err, &tooMany) {
t.Fatalf("the cap did not fire: %v", err)
}
if tooMany.Cap != 1 || tooMany.Source != "--max-rows" {
t.Errorf("the synthesized cap error = %+v, want Cap 1 attributed to --max-rows", tooMany)
}
}
// TestTheParentExistenceProbeCrossesTheWire is the raw GetIssue the walk runs
// before it descends: a miss is (nil, nil), because getHierarchicalChildren
// reads a nil result as "parent issue not found" and an error would print the
// transport's vocabulary in its place.
func TestTheParentExistenceProbeCrossesTheWire(t *testing.T) {
e := newServedEnv(t, "prb")
ctx := t.Context()
if err := e.createIssue(ctx, &types.Issue{ID: "prb-1", Title: "present", Status: types.StatusOpen, IssueType: types.TypeTask}, "seed"); err != nil {
t.Fatalf("seed: %v", err)
}
got, err := e.subject.GetIssue(ctx, "prb-1")
if err != nil || got == nil || got.ID != "prb-1" {
t.Fatalf("GetIssue on a hit = (%v, %v)", got, err)
}
if got, err = e.subject.GetIssue(ctx, "prb-nope"); err != nil || got != nil {
t.Errorf("GetIssue on a miss = (%v, %v), want (nil, nil)", got, err)
}
}
// TestBridgeGetIssuePopulatesRowVersionForAGuardedWrite is HIGH 5's second pin:
// the raw bridge GetIssue above returns a hit by value with no RowVersion
// assertion, same as the molecule loader's existence probe
// (internal/molecules/molecules.go) that is this method's other caller — so a
// stitched-at-zero regression here would have shipped silently next to the
// passing test above it.
//
// types.Issue.RowVersion is json:"-"; getIssue's wire body carries the same
// token under Revision instead, and bridge.go's GetIssue must stitch it back
// onto the issue it returns, exactly as Reader.Get does in role_reader.go
// (pinned by TestServedReaderGetPopulatesRowVersionForAGuardedWrite). This
// proves it the same way: by guarding a write with whatever GetIssue just
// answered, over the same wire, and requiring a second write that reuses the
// now-stale token to be refused. A read alone cannot tell a stitched zero from
// a real one that happens to equal it on a fresh table — only a guard that
// the write actually enforces can.
func TestBridgeGetIssuePopulatesRowVersionForAGuardedWrite(t *testing.T) {
e := newServedEnv(t, "brgv")
ctx := t.Context()
lifecycle, err := e.subject.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
issue := &types.Issue{Title: "bridge row version round trip", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := e.createIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed: %v", err)
}
got, err := e.subject.GetIssue(ctx, issue.ID)
if err != nil || got == nil {
t.Fatalf("GetIssue: (%v, %v)", got, err)
}
if got.RowVersion == 0 {
t.Fatalf("GetIssue answered RowVersion 0; want the row's real token")
}
staleVersion := got.RowVersion
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "writer", IssueID: issue.ID, ExpectedVersion: &staleVersion,
Patch: issueops.IssuePatch{Title: set("first guarded write")},
}); err != nil {
t.Fatalf("Update guarded by the token GetIssue answered: %v", err)
}
_, err = lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "writer", IssueID: issue.ID, ExpectedVersion: &staleVersion,
Patch: issueops.IssuePatch{Title: set("second guarded write, same stale token")},
})
if err == nil {
t.Fatal("Update reused GetIssue's token after a write moved the row past it; want a version-guard refusal")
}
}
// TestSearchIssuesExactIDPopulatesRowVersionForAGuardedWrite pins the same
// stitch as TestBridgeGetIssuePopulatesRowVersionForAGuardedWrite, for
// SearchIssues' own exact-id fast path (getIssuesByExactID in resolve.go)
// rather than the raw bridge GetIssue. That path decodes the same
// apigen.ContextResponse-shaped IssueDetails getIssue does, but — unlike
// bridge.go's GetIssue and role_reader.go's Reader.Get — it never parsed
// details.Revision, so SearchIssues(ctx, "", IssueFilter{IDs: ...}) answered
// RowVersion 0 for a row every other read path reports a real token for. This
// proves the stitch the same way the bridge test does: by guarding a write
// with whatever the exact-id search just answered, over the same wire, and
// requiring a second write that reuses the now-stale token to be refused.
func TestSearchIssuesExactIDPopulatesRowVersionForAGuardedWrite(t *testing.T) {
e := newServedEnv(t, "sixi")
ctx := t.Context()
lifecycle, err := e.subject.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
issue := &types.Issue{Title: "exact-id search row version round trip", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := e.createIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed: %v", err)
}
rows, err := e.subject.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{issue.ID}})
if err != nil {
t.Fatalf("SearchIssues(exact id): %v", err)
}
if len(rows) != 1 || rows[0] == nil {
t.Fatalf("SearchIssues(exact id) = %+v, want exactly one hit", rows)
}
if rows[0].RowVersion == 0 {
t.Fatalf("SearchIssues(exact id) answered RowVersion 0; want the row's real token")
}
staleVersion := rows[0].RowVersion
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "writer", IssueID: issue.ID, ExpectedVersion: &staleVersion,
Patch: issueops.IssuePatch{Title: set("first guarded write")},
}); err != nil {
t.Fatalf("Update guarded by the token SearchIssues answered: %v", err)
}
_, err = lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "writer", IssueID: issue.ID, ExpectedVersion: &staleVersion,
Patch: issueops.IssuePatch{Title: set("second guarded write, same stale token")},
})
if err == nil {
t.Fatal("Update reused SearchIssues' token after a write moved the row past it; want a version-guard refusal")
}
}
// TestServedWorkspaceConfigWritesRefuse IS GONE, and what it asserted is worth a
// line rather than a silent deletion: while D8 row 11 was PARTIAL, the two write
// verbs refused per METHOD and named themselves, so the accessor could serve the
// reads without the writes silently becoming no-ops. Upstream #5596 published
// both operations and client wave ga-jpywb dials them, so there is no refusal
// left to pin — served_config_test.go runs the whole role contract instead, and
// served_config_write_test.go pins the three things only this leg has.
//
// TestServedRedactedSettingIsAbsentWithReason is ledger row L9, and the reason
// this backend gives ONE answer per key: a withheld value is not the same fact
// as an unset one, so both the raw probe and the role report the withholding
// rather than returning an empty string a caller would read as "nothing stored".
func TestServedRedactedSettingIsAbsentWithReason(t *testing.T) {
e := newServedEnv(t, "red")
ctx := t.Context()
if err := e.setConfig(ctx, "github.api_token", "ghp-supersecret"); err != nil {
t.Fatalf("seed the credential-bearing key: %v", err)
}
if _, err := e.subject.GetConfig(ctx, "github.api_token"); !errors.Is(err, ErrSettingRedacted) {
t.Errorf("GetConfig on a redacted key = %v, want ErrSettingRedacted", err)
}
settings, err := e.subject.WorkspaceConfig()
if err != nil {
t.Fatalf("WorkspaceConfig(): %v", err)
}
if _, err := settings.GetSetting(ctx, issueops.GetSettingRequest{Key: "github.api_token"}); !errors.Is(err, ErrSettingRedacted) {
t.Errorf("GetSetting on a redacted key = %v, want the same answer the raw probe gives", err)
}
// The ENUMERATION cannot fail over one key of many, so it lists the key with
// an empty value: the workspace really does store something there.
all, err := e.subject.GetAllConfig(ctx)
if err != nil {
t.Fatalf("GetAllConfig: %v", err)
}
if value, ok := all["github.api_token"]; !ok || value != "" {
t.Errorf("GetAllConfig gave the redacted key (%q, present=%v), want present and empty", value, ok)
}
}
// TestServedStatisticsProbeAnswersTruthfully is D4's off-role stats row: the
// empty-state probe `bd ready` prints "No open issues" from, which must answer
// from the SERVER rather than fail into a false statement.
func TestServedStatisticsProbeAnswersTruthfully(t *testing.T) {
e := newServedEnv(t, "stp")
ctx := t.Context()
before, err := e.subject.GetStatistics(ctx)
if err != nil {
t.Fatalf("GetStatistics on an empty workspace: %v", err)
}
if err := e.createIssue(ctx, &types.Issue{ID: "stp-1", Title: "open work", Status: types.StatusOpen, IssueType: types.TypeTask}, "seed"); err != nil {
t.Fatalf("seed: %v", err)
}
after, err := e.subject.GetStatistics(ctx)
if err != nil {
t.Fatalf("GetStatistics: %v", err)
}
if after.OpenIssues != before.OpenIssues+1 {
t.Errorf("open issues went %d -> %d across one seeded row", before.OpenIssues, after.OpenIssues)
}
}
// TestServedVocabularyReadsDegradeRatherThanFail is L7: the client-side status
// and type vocabulary comes from the pre-migration config keys, which are its
// only wire-visible source, and the reads must never hard-fail — every one of
// them is wrapped by LoadStoreListConfig in a failure that would kill `bd list`.
func TestServedVocabularyReadsDegradeRatherThanFail(t *testing.T) {
e := newServedEnv(t, "voc")
ctx := t.Context()
// Seeded OUT OF ALPHABETICAL ORDER on purpose: the read answers in NAME
// order, which is what every leg's projected-table read answers, and not in
// the order the config string happens to list them.
if err := e.setConfig(ctx, "types.custom", "spike,chore"); err != nil {
t.Fatalf("seed types.custom: %v", err)
}
if err := e.setConfig(ctx, "status.custom", "shipped:done"); err != nil {
t.Fatalf("seed status.custom: %v", err)
}
custom, err := e.subject.GetCustomTypes(ctx)
if err != nil {
t.Fatalf("GetCustomTypes: %v", err)
}
if len(custom) != 2 || custom[0] != "chore" || custom[1] != "spike" {
t.Errorf("GetCustomTypes = %v, want [chore spike] — ordered by name, as the table read every other leg makes is", custom)
}
statuses, err := e.subject.GetCustomStatusesDetailed(ctx)
if err != nil {
t.Fatalf("GetCustomStatusesDetailed: %v", err)
}
if len(statuses) != 1 || statuses[0].Name != "shipped" || statuses[0].Category != types.CategoryDone {
t.Errorf("GetCustomStatusesDetailed = %+v, want shipped:done", statuses)
}
// The infra vocabulary has no error channel at all, so an unconfigured
// workspace must still answer the defaults rather than an empty map — an
// empty one says "nothing is infrastructure" and admits agent and message
// rows into every default listing.
if infra := e.subject.GetInfraTypes(ctx); !infra["agent"] || !infra["message"] {
t.Errorf("GetInfraTypes = %v, want the defaults", infra)
}
}
func equalIDs(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}

View file

@ -0,0 +1,820 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_bulk_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"reflect"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The Sweeper, Deleter and BatchCreator contracts against the served surface.
//
// The three roles sit at very different distances from the wire, and the parks
// below say where each one stops:
//
// - SWEEP maps whole, in both directions. Every case runs.
// - DELETE maps its whole REQUEST and diverges only in its refusal
// VOCABULARY: the wire flattens *NotFoundError and
// *DependentsOutsideRequestError into a bare sentinel and a 400. Four cases
// bind those typed errors and park; the behavior underneath them — the
// request fails and nothing is deleted — is asserted for real by the two
// bespoke cases below, so the rows retire loudly rather than sitting behind
// a skip.
// - BATCH CREATE maps eight content members of a whole types.Issue, and every
// case that names an explicit id parks with it. That is most of the family,
// because the contract's own preamble says why: "Every case names its own
// ids under the fixture prefix and passes ForceIDPrefix." Three bespoke
// cases below cover the same ground with server-generated ids.
//
// The bead that owns every park here, and unparks each one as the wire grows
// the member behind it.
const bulkParkBead = "ga-6lbny"
// ── Sweeper ─────────────────────────────────────────────────────────────────
func newServedSweeperFixture(t *testing.T, prefix string) conformance.SweeperFixture {
t.Helper()
env := newServedEnv(t, prefix)
sweeper, err := env.subject.Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
return conformance.SweeperFixture{
IssuePrefix: env.prefix,
Sweeper: sweeper,
CreateIssue: env.createIssue,
CreateWisp: env.createWisp,
QueryScalar: env.queryScalar,
CountHistory: env.countHistory,
CommitPending: env.commitPending,
AddComment: env.addComment,
// Exec is the harness's own raw door, the one the close/reopen cases
// already use. The tier-boundary case needs a LEGACY typed wisp — issues
// plane, wisp_type set, ephemeral 0 — and no create verb can mint one,
// on this leg least of all: the wire has no raw-row surface, so the
// 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,
}
}
func TestServedSweeperRefusesAnUnfilteredDurableSweep(t *testing.T) {
conformance.RunSweeperRefusesAnUnfilteredDurableSweep(t, t.Context(), newServedSweeperFixture(t, "hs00"))
}
func TestServedSweeperRefusesAMalformedRequest(t *testing.T) {
conformance.RunSweeperRefusesAMalformedRequest(t, t.Context(), newServedSweeperFixture(t, "hs01"))
}
func TestServedSweeperClearsOneTierAndLeavesTheOther(t *testing.T) {
conformance.RunSweeperClearsOneTierAndLeavesTheOther(t, t.Context(), newServedSweeperFixture(t, "hs02"))
}
func TestServedSweeperTreatsALegacyTypedWispAsEphemeralTier(t *testing.T) {
conformance.RunSweeperTreatsALegacyTypedWispAsEphemeralTier(t, t.Context(), newServedSweeperFixture(t, "hs11"))
}
func TestServedSweeperLeavesNoHistoryBeadsToTheDurableTier(t *testing.T) {
conformance.RunSweeperLeavesNoHistoryBeadsToTheDurableTier(t, t.Context(), newServedSweeperFixture(t, "hs12"))
}
func TestServedSweeperProtectsPinnedRows(t *testing.T) {
conformance.RunSweeperProtectsPinnedRows(t, t.Context(), newServedSweeperFixture(t, "hs03"))
}
func TestServedSweeperHonorsTheCutoffAndThePattern(t *testing.T) {
conformance.RunSweeperHonorsTheCutoffAndThePattern(t, t.Context(), newServedSweeperFixture(t, "hs04"))
}
func TestServedSweeperDryRunChangesNothing(t *testing.T) {
conformance.RunSweeperDryRunChangesNothing(t, t.Context(), newServedSweeperFixture(t, "hs05"))
}
func TestServedSweeperProtectsRowsCitedFromAWispComment(t *testing.T) {
conformance.RunSweeperProtectsRowsCitedFromAWispComment(t, t.Context(), newServedSweeperFixture(t, "hs06"))
}
func TestServedSweeperProtectsCitedRows(t *testing.T) {
conformance.RunSweeperProtectsCitedRows(t, t.Context(), newServedSweeperFixture(t, "hs07"))
}
func TestServedSweeperEmptyMatchIsZeroAndNil(t *testing.T) {
conformance.RunSweeperEmptyMatchIsZeroAndNil(t, t.Context(), newServedSweeperFixture(t, "hs08"))
}
func TestServedSweeperRecordsExactlyOneHistoryEntry(t *testing.T) {
conformance.RunSweeperRecordsExactlyOneHistoryEntry(t, t.Context(), newServedSweeperFixture(t, "hs09"))
}
func TestServedSweeperDoesNotMutateTheCallerRequest(t *testing.T) {
conformance.RunSweeperDoesNotMutateTheCallerRequest(t, t.Context(), newServedSweeperFixture(t, "hs10"))
}
// ── Deleter ─────────────────────────────────────────────────────────────────
func newServedDeleterFixture(t *testing.T, prefix string) conformance.DeleterFixture {
t.Helper()
env := newServedEnv(t, prefix)
deleter, err := env.subject.Deleter()
if err != nil {
t.Fatalf("Deleter(): %v", err)
}
return conformance.DeleterFixture{
IssuePrefix: env.prefix,
Deleter: deleter,
CreateIssue: env.createIssue,
CreateWisp: env.createWisp,
AddDependency: env.addDependency,
QueryScalar: env.queryScalar,
CountHistory: env.countHistory,
CommitPending: env.commitPending,
}
}
func TestServedDeleterRefusesAMalformedRequest(t *testing.T) {
conformance.RunDeleterRefusesAMalformedRequest(t, t.Context(), newServedDeleterFixture(t, "hx00"))
}
func TestServedDeleterRefusesAnAbsentID(t *testing.T) {
skipKnownDivergence(t, "L-delete-notfound", bulkParkBead, parkDeleteNotFound)
conformance.RunDeleterRefusesAnAbsentID(t, t.Context(), newServedDeleterFixture(t, "hx01"))
}
func TestServedDeleterRefusesDependentsOutsideTheRequest(t *testing.T) {
skipKnownDivergence(t, "L-delete-dependents", bulkParkBead, parkDeleteDependents)
conformance.RunDeleterRefusesDependentsOutsideTheRequest(t, t.Context(), newServedDeleterFixture(t, "hx02"))
}
func TestServedDeleterForceOrphansDependents(t *testing.T) {
conformance.RunDeleterForceOrphansDependents(t, t.Context(), newServedDeleterFixture(t, "hx03"))
}
func TestServedDeleterCascadeDeletesTheClosure(t *testing.T) {
conformance.RunDeleterCascadeDeletesTheClosure(t, t.Context(), newServedDeleterFixture(t, "hx04"))
}
func TestServedDeleterCascadeFromAWispRootDeletesTheClosure(t *testing.T) {
conformance.RunDeleterCascadeFromAWispRootDeletesTheClosure(t, t.Context(), newServedDeleterFixture(t, "hx05"))
}
func TestServedDeleterGuardsAWispNamedWithADurableDependent(t *testing.T) {
skipKnownDivergence(t, "L-delete-dependents", bulkParkBead, parkDeleteDependents)
conformance.RunDeleterGuardsAWispNamedWithADurableDependent(t, t.Context(), newServedDeleterFixture(t, "hx06"))
}
func TestServedDeleterGuardsADurableNamedWithAWispDependent(t *testing.T) {
skipKnownDivergence(t, "L-delete-dependents", bulkParkBead, parkDeleteDependents)
conformance.RunDeleterGuardsADurableNamedWithAWispDependent(t, t.Context(), newServedDeleterFixture(t, "hx07"))
}
func TestServedDeleterCountsCrossPlaneEdgesItRemoves(t *testing.T) {
conformance.RunDeleterCountsCrossPlaneEdgesItRemoves(t, t.Context(), newServedDeleterFixture(t, "hx08"))
}
func TestServedDeleterNeverCallsALiveRowDeleted(t *testing.T) {
conformance.RunDeleterNeverCallsALiveRowDeleted(t, t.Context(), newServedDeleterFixture(t, "hx09"))
}
func TestServedDeleterErasesAcrossBothPlanes(t *testing.T) {
conformance.RunDeleterErasesAcrossBothPlanes(t, t.Context(), newServedDeleterFixture(t, "hx10"))
}
func TestServedDeleterCollapsesDuplicateIDs(t *testing.T) {
conformance.RunDeleterCollapsesDuplicateIDs(t, t.Context(), newServedDeleterFixture(t, "hx11"))
}
func TestServedDeleterRewritesReferencesInNeighbors(t *testing.T) {
conformance.RunDeleterRewritesReferencesInNeighbors(t, t.Context(), newServedDeleterFixture(t, "hx12"))
}
func TestServedDeleterDryRunChangesNothing(t *testing.T) {
conformance.RunDeleterDryRunChangesNothing(t, t.Context(), newServedDeleterFixture(t, "hx13"))
}
func TestServedDeleterRecordsExactlyOneHistoryEntry(t *testing.T) {
conformance.RunDeleterRecordsExactlyOneHistoryEntry(t, t.Context(), newServedDeleterFixture(t, "hx14"))
}
func TestServedDeleterDoesNotMutateTheCallerRequest(t *testing.T) {
conformance.RunDeleterDoesNotMutateTheCallerRequest(t, t.Context(), newServedDeleterFixture(t, "hx15"))
}
// The compare-and-delete precondition, end to end. It is the guard whose failure
// mode has no undo — a dropped one erases a row the caller asked not to erase,
// with nothing left to compare afterwards — so all four of its contracts run
// against a real server rather than stopping at the request assertion.
//
// The arity case is the one that could not have been anticipated client-side:
// the wire refuses a guard beside more than one DISTINCT id, and distinctness
// there is measured after trimming and collapsing duplicates, so `["x", " x "]`
// is ONE bead and legal. That normalization belongs to the server, and this is
// where the client's verbatim ids meet it.
func TestServedDeleterDeletesOnAMatchingExpectedVersion(t *testing.T) {
conformance.RunDeleterDeletesOnAMatchingExpectedVersion(t, t.Context(), newServedDeleterFixture(t, "hx16"))
}
func TestServedDeleterRefusesAStaleExpectedVersion(t *testing.T) {
conformance.RunDeleterRefusesAStaleExpectedVersion(t, t.Context(), newServedDeleterFixture(t, "hx17"))
}
func TestServedDeleterVersionOutranksForceAndCascade(t *testing.T) {
conformance.RunDeleterVersionOutranksForceAndCascade(t, t.Context(), newServedDeleterFixture(t, "hx18"))
}
func TestServedDeleterRefusesAnExpectedVersionAcrossSeveralIDs(t *testing.T) {
conformance.RunDeleterRefusesAnExpectedVersionAcrossSeveralIDs(t, t.Context(), newServedDeleterFixture(t, "hx19"))
}
// The three BLOCKED-STATE postconditions of a delete, which map onto the wire
// whole: the request is expressible, and what they assert is what the server's
// deleting transaction leaves behind in a column no read on this surface
// hydrates.
//
// They matter most on the SURVIVORS. A delete is the one write that removes the
// blocker rather than closing it, so a body that settled by re-reading the
// deleted row would find nothing and leave every depender marked blocked by an
// id that no longer exists — a row that can never become ready again and that
// no listing can explain.
func TestServedDeleterSettlesTheSurvivorsOfADeletedBlocker(t *testing.T) {
conformance.RunDeleterSettlesTheSurvivorsOfADeletedBlocker(t, t.Context(), newServedDeleterFixture(t, "hx20"))
}
func TestServedDeleterSettlesTheSurvivorsOfADeletedWispBlocker(t *testing.T) {
conformance.RunDeleterSettlesTheSurvivorsOfADeletedWispBlocker(t, t.Context(), newServedDeleterFixture(t, "hx21"))
}
// TestServedDeleterSettlesTheChildrenOfADeletedParent is the inherited half: a
// child orphaned from a blocked parent inherits nothing, so the same
// transaction has to unmark it.
func TestServedDeleterSettlesTheChildrenOfADeletedParent(t *testing.T) {
conformance.RunDeleterSettlesTheChildrenOfADeletedParent(t, t.Context(), newServedDeleterFixture(t, "hx22"))
}
const parkDeleteNotFound = "the case binds *NotFoundError.IDs, and the wire's 404 carries a FIXED detail that cannot echo caller input back, so the ids that did not resolve are unrecoverable (asserted by TestServedDeleteRefusesAnAbsentIDWithoutNamingIt)"
const parkDeleteDependents = "the case binds *DependentsOutsideRequestError, and the wire flattens the unforced dependents guard into a 400 invalid_argument with no param, so the blocked id and its dependents cannot be reconstructed without parsing detail prose. " +
"The GUARD is asserted for all three quadrants the contract covers: TestServedDeleteDependentsGuardRefusesAsValidation (durable named, durable dependent, plus the both-ends-named exception), " +
"TestServedDeleteGuardsAWispNamedWithADurableDependent and TestServedDeleteGuardsADurableNamedWithAWispDependent (the two cross-plane directions, unforced refusal AND forced orphan report)"
// TestServedDeleteRefusesAnAbsentIDWithoutNamingIt is L-delete-notfound's pin,
// and it RUNS.
//
// The row is a divergence in CLASSIFICATION, not in outcome, and the outcome is
// the half that matters: an id naming no row fails the whole request and
// deletes NOTHING — not even the id beside it that did resolve. Asserting the
// absence of the typed error is what makes the row retire the day the wire
// grows an ids extension member.
func TestServedDeleteRefusesAnAbsentIDWithoutNamingIt(t *testing.T) {
env := newServedEnv(t, "hxnf")
ctx := t.Context()
deleter, err := env.subject.Deleter()
if err != nil {
t.Fatalf("Deleter(): %v", err)
}
const stored = "hxnf-real"
seedServedIssue(t, ctx, env, stored, types.StatusOpen)
for _, dryRun := range []bool{false, true} {
result, err := deleter.Delete(ctx, issueops.DeleteRequest{
IDs: []string{stored, "hxnf-nosuchrow"}, Force: true, DryRun: dryRun,
})
if !errors.Is(err, issueops.ErrNotFound) {
t.Fatalf("Delete(dryRun=%v) error = %v, want ErrNotFound", dryRun, err)
}
var notFound *issueops.NotFoundError
if errors.As(err, &notFound) {
t.Errorf("the refusal carries *NotFoundError(%v); L-delete-notfound says the wire cannot express it — retire the row rather than the assertion", notFound.IDs)
}
if result.Deleted != 0 {
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
}
assertServedIssueRows(t, ctx, env, 1, stored)
}
}
// TestServedDeleteDependentsGuardRefusesAsValidation is L-delete-dependents'
// pin, and it RUNS. The guard itself is untouched: the request fails and the
// graph is whole.
func TestServedDeleteDependentsGuardRefusesAsValidation(t *testing.T) {
env := newServedEnv(t, "hxdg")
ctx := t.Context()
deleter, err := env.subject.Deleter()
if err != nil {
t.Fatalf("Deleter(): %v", err)
}
const blocker, dependent = "hxdg-blocker", "hxdg-dependent"
seedServedIssue(t, ctx, env, blocker, types.StatusOpen)
seedServedIssue(t, ctx, env, dependent, types.StatusOpen)
if err := env.addDependency(ctx, &types.Dependency{
IssueID: dependent, DependsOnID: blocker, Type: types.DepBlocks,
}, "seed"); err != nil {
t.Fatalf("seed the edge: %v", err)
}
result, err := deleter.Delete(ctx, issueops.DeleteRequest{IDs: []string{blocker}})
if err == nil {
t.Fatal("an unforced delete over an outside dependent succeeded; the guard is the role's and must survive the crossing")
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("refusal = %v, want ErrValidation — the wire spells this as a 400 invalid_argument", err)
}
if errors.Is(err, issueops.ErrDependentsOutsideRequest) {
t.Error("the refusal carries ErrDependentsOutsideRequest; L-delete-dependents says the wire cannot express it — retire the row rather than the assertion")
}
if result.Deleted != 0 {
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
}
assertServedIssueRows(t, ctx, env, 1, blocker, dependent)
// The EXCEPTION beside the guard, which the wire carries whole: a dependent
// INSIDE the request is not a dependent for this purpose. Refusing it would
// make `delete a b` fail on exactly the pair a caller took care to list
// together, and it is the one arm a body that partitioned the request by
// plane could still get wrong.
both, err := deleter.Delete(ctx, issueops.DeleteRequest{IDs: []string{blocker, dependent}})
if err != nil {
t.Fatalf("Delete() naming both ends of the edge: %v — a dependent INSIDE the request is not a dependent", err)
}
if both.Deleted != 2 {
t.Errorf("Deleted = %d, want 2", both.Deleted)
}
assertServedIssueRows(t, ctx, env, 0, blocker, dependent)
}
// TestServedDeleteGuardsAWispNamedWithADurableDependent and its sibling below
// are the two CROSS-PLANE quadrants of the dependents guard, over the wire.
//
// They exist because the contract cases that cover them park on the typed
// error, and parking all four quadrants on one durable-to-durable assertion
// would leave exactly the hole deleter_contract.go says it was written to
// close: a body that asked the guard about the durable half of the request only
// "orphaned a durable dependent without saying so and without being refused".
// The guard is the SERVER's here, but a client that partitioned a mixed request
// by plane would reintroduce it below the wire, and nothing else would see it.
//
// Both halves of the clause are asserted, because a body can get either one
// right on its own: the unforced refusal leaves both rows AND the edge, and the
// forced run deletes exactly the named row and NAMES the cross-plane orphan.
func TestServedDeleteGuardsAWispNamedWithADurableDependent(t *testing.T) {
env := newServedEnv(t, "hxwg")
ctx := t.Context()
deleter, err := env.subject.Deleter()
if err != nil {
t.Fatalf("Deleter(): %v", err)
}
// The NAMED row is the wisp; its dependent is durable, so the edge lives in
// `dependencies` with the wisp as the target.
const wisp, dependent = "hxwg-wisp", "hxwg-dependent"
seedServedWisp(t, ctx, env, wisp)
seedServedIssue(t, ctx, env, dependent, types.StatusOpen)
seedServedEdge(t, ctx, env, dependent, wisp)
assertServedEdgeRows(t, ctx, env, "dependencies", 1, dependent, wisp)
for _, dryRun := range []bool{false, true} {
result, err := deleter.Delete(ctx, issueops.DeleteRequest{IDs: []string{wisp}, DryRun: dryRun})
assertServedDependentsRefusal(t, err, dryRun)
if result.Deleted != 0 {
t.Errorf("refused delete (dryRun=%v) reported Deleted = %d, want 0", dryRun, result.Deleted)
}
assertServedWispRows(t, ctx, env, 1, wisp)
assertServedIssueRows(t, ctx, env, 1, dependent)
assertServedEdgeRows(t, ctx, env, "dependencies", 1, dependent, wisp)
}
forced, err := deleter.Delete(ctx, issueops.DeleteRequest{IDs: []string{wisp}, Force: true})
if err != nil {
t.Fatalf("forced delete of the wisp: %v", err)
}
if forced.Deleted != 1 {
t.Errorf("Deleted = %d, want 1 — force deletes the NAMED wisp and nothing else", forced.Deleted)
}
if !reflect.DeepEqual(forced.Orphaned, []string{dependent}) {
t.Errorf("Orphaned = %v, want [%s] — the cross-plane edge orphans a durable row too", forced.Orphaned, dependent)
}
assertServedWispRows(t, ctx, env, 0, wisp)
assertServedIssueRows(t, ctx, env, 1, dependent)
assertServedEdgeRows(t, ctx, env, "dependencies", 0, dependent, wisp)
}
// TestServedDeleteGuardsADurableNamedWithAWispDependent is the fourth quadrant:
// the WISP is the dependent, so the edge lands in wisp_dependencies, and the
// durable row it depends on is the one named unforced. The two planes are
// scanned by different queries below the wire, so this is a genuinely separate
// answer from the case above.
func TestServedDeleteGuardsADurableNamedWithAWispDependent(t *testing.T) {
env := newServedEnv(t, "hxdw")
ctx := t.Context()
deleter, err := env.subject.Deleter()
if err != nil {
t.Fatalf("Deleter(): %v", err)
}
const blocker, dependent = "hxdw-blocker", "hxdw-dependent"
seedServedIssue(t, ctx, env, blocker, types.StatusOpen)
seedServedWisp(t, ctx, env, dependent)
seedServedEdge(t, ctx, env, dependent, blocker)
assertServedEdgeRows(t, ctx, env, "wisp_dependencies", 1, dependent, blocker)
for _, dryRun := range []bool{false, true} {
result, err := deleter.Delete(ctx, issueops.DeleteRequest{IDs: []string{blocker}, DryRun: dryRun})
assertServedDependentsRefusal(t, err, dryRun)
if result.Deleted != 0 {
t.Errorf("refused delete (dryRun=%v) reported Deleted = %d, want 0", dryRun, result.Deleted)
}
assertServedIssueRows(t, ctx, env, 1, blocker)
assertServedWispRows(t, ctx, env, 1, dependent)
assertServedEdgeRows(t, ctx, env, "wisp_dependencies", 1, dependent, blocker)
}
forced, err := deleter.Delete(ctx, issueops.DeleteRequest{IDs: []string{blocker}, Force: true})
if err != nil {
t.Fatalf("forced delete of the durable row: %v", err)
}
if forced.Deleted != 1 {
t.Errorf("Deleted = %d, want 1 — force deletes the NAMED durable row and nothing else", forced.Deleted)
}
if !reflect.DeepEqual(forced.Orphaned, []string{dependent}) {
t.Errorf("Orphaned = %v, want [%s] — the orphan is a wisp, and it is still an orphan", forced.Orphaned, dependent)
}
assertServedIssueRows(t, ctx, env, 0, blocker)
assertServedWispRows(t, ctx, env, 1, dependent)
assertServedEdgeRows(t, ctx, env, "wisp_dependencies", 0, dependent, blocker)
}
// assertServedDependentsRefusal is the coarse shape L-delete-dependents leaves:
// ErrValidation, and NOT the typed sentinel the local role raises.
func assertServedDependentsRefusal(t *testing.T, err error, dryRun bool) {
t.Helper()
if err == nil {
t.Fatalf("an unforced delete (dryRun=%v) over a cross-plane dependent succeeded; the guard has no wisp exemption at either end", dryRun)
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("refusal (dryRun=%v) = %v, want ErrValidation — the wire spells this as a 400 invalid_argument", dryRun, err)
}
if errors.Is(err, issueops.ErrDependentsOutsideRequest) {
t.Errorf("the refusal (dryRun=%v) carries ErrDependentsOutsideRequest; L-delete-dependents says the wire cannot express it — retire the row rather than the assertion", dryRun)
}
}
// ── BatchCreator ────────────────────────────────────────────────────────────
func newServedBatchCreatorFixture(t *testing.T, prefix string) conformance.BatchCreatorFixture {
t.Helper()
env := newServedEnv(t, prefix)
creator, err := env.subject.BatchCreator()
if err != nil {
t.Fatalf("BatchCreator(): %v", err)
}
return conformance.BatchCreatorFixture{
IssuePrefix: env.prefix,
BatchCreator: creator,
CreateIssue: env.createIssue,
QueryScalar: env.queryScalar,
CountHistory: env.countHistory,
}
}
// TestServedBatchCreateStampsEachItemsCreatedByFromTheActor is the served half
// of created_by on the batch: BatchCreateItem publishes no created_by, so the
// stored creator exists only because the server stamps it from the actor
// (internal/httpapi's batch_create.go). An item whose CreatedBy names that actor
// — the shape `bd create --file` sends — is carried by the stamp rather than
// refused, and an item that names none is stamped all the same.
func TestServedBatchCreateStampsEachItemsCreatedByFromTheActor(t *testing.T) {
env := newServedEnv(t, "hbcby")
ctx := t.Context()
creator, err := env.subject.BatchCreator()
if err != nil {
t.Fatalf("BatchCreator(): %v", err)
}
res, err := creator.CreateBatch(ctx, issueops.CreateBatchRequest{
Actor: "file-writer",
Items: []issueops.BatchCreateItem{
{Issue: &issueops.Issue{Title: "named", Priority: 2, IssueType: types.TypeTask, CreatedBy: "file-writer"}},
{Issue: &issueops.Issue{Title: "unnamed", Priority: 2, IssueType: types.TypeTask}},
},
})
if err != nil {
t.Fatalf("CreateBatch in bd create --file's shape = %v, want it served", err)
}
for i, issue := range res.Issues {
stored, err := env.getIssue(ctx, issue.ID)
if err != nil {
t.Fatalf("read back items[%d] %s: %v", i, issue.ID, err)
}
if stored.CreatedBy != "file-writer" {
t.Errorf("items[%d] stored created_by = %q, want the actor %q", i, stored.CreatedBy, "file-writer")
}
}
}
func TestServedBatchCreatorCreatesEveryItemAsOneAct(t *testing.T) {
conformance.RunBatchCreatorCreatesEveryItemAsOneAct(t, t.Context(), newServedBatchCreatorFixture(t, "hb00"))
}
func TestServedBatchCreatorRefusesEverythingWhenOneItemRefuses(t *testing.T) {
skipKnownDivergence(t, "W-BatchCreateItem.Issue", bulkParkBead, parkBatchExplicitID)
conformance.RunBatchCreatorRefusesEverythingWhenOneItemRefuses(t, t.Context(), newServedBatchCreatorFixture(t, "hb01"))
}
func TestServedBatchCreatorRejectsAnUnusableRequest(t *testing.T) {
conformance.RunBatchCreatorRejectsAnUnusableRequest(t, t.Context(), newServedBatchCreatorFixture(t, "hb02"))
}
func TestServedBatchCreatorRefusesACrossPlaneInBatchEdge(t *testing.T) {
skipKnownDivergence(t, "W-BatchCreateItem.Issue", bulkParkBead,
"the case seeds an item with Issue.Ephemeral, and the wire's item publishes no wisp member at all — "+
"so the plane an item lands in is the server's to choose and a cross-plane in-batch edge cannot be asked for. "+parkBatchExplicitID)
conformance.RunBatchCreatorRefusesACrossPlaneInBatchEdge(t, t.Context(), newServedBatchCreatorFixture(t, "hb03"))
}
func TestServedBatchCreatorLinksAnEarlierItemOfTheSameBatch(t *testing.T) {
skipKnownDivergence(t, "L-batchcreate-inbatch", bulkParkBead,
"an edge onto an earlier item of the same batch needs that item to have named an id for itself, and BatchCreateItem publishes no id member (asserted by TestBatchCreateCannotNameAnItemOfItsOwnBatch)")
conformance.RunBatchCreatorLinksAnEarlierItemOfTheSameBatch(t, t.Context(), newServedBatchCreatorFixture(t, "hb04"))
}
func TestServedBatchCreatorRefusesAnAbsentEdgeTarget(t *testing.T) {
skipKnownDivergence(t, "L-batchcreate-target", bulkParkBead,
"the case binds ErrValidation WRAPPING ErrNotFound, and the wire answers a dangling target with a plain 400 invalid_argument (asserted by TestServedBatchCreateRefusesAnAbsentEdgeTargetAsValidation). "+parkBatchExplicitID)
conformance.RunBatchCreatorRefusesAnAbsentEdgeTarget(t, t.Context(), newServedBatchCreatorFixture(t, "hb05"))
}
func TestServedBatchCreatorAcceptsAForeignEdgeTarget(t *testing.T) {
skipKnownDivergence(t, "W-BatchCreateItem.Issue", bulkParkBead,
parkBatchExplicitID+" The rule itself is asserted by TestServedBatchCreateAcceptsAForeignEdgeTarget, over server-generated ids.")
conformance.RunBatchCreatorAcceptsAForeignEdgeTarget(t, t.Context(), newServedBatchCreatorFixture(t, "hb06"))
}
func TestServedBatchCreatorRecordsOneHistoryEntry(t *testing.T) {
skipKnownDivergence(t, "W-CreateBatchRequest.Provenance", bulkParkBead,
"half the case sends CreateBatchRequest.Provenance, which batchCreateIssues publishes no member for, so the client refuses it rather than letting the server's own label stand in silence. "+
"The one-entry-per-batch half is asserted by TestServedBatchCreateRecordsOneHistoryEntry.")
conformance.RunBatchCreatorRecordsOneHistoryEntry(t, t.Context(), newServedBatchCreatorFixture(t, "hb07"))
}
func TestServedBatchCreatorRecordsNoHistoryForAnEphemeralBatch(t *testing.T) {
skipKnownDivergence(t, "W-BatchCreateItem.Issue", bulkParkBead,
"the case seeds Issue.Ephemeral on every item, and the wire's item publishes no wisp member. "+parkBatchExplicitID)
conformance.RunBatchCreatorRecordsNoHistoryForAnEphemeralBatch(t, t.Context(), newServedBatchCreatorFixture(t, "hb08"))
}
// TestServedBatchCreatorEchoesSubSecondTimestamps is the batch half of the
// sub-second echo, parked on the item vocabulary like the eight above: its
// precision pin is a caller-supplied CreatedAt/UpdatedAt on every item, and
// apigen.BatchCreateItem carries no timestamp member. The client refuses
// items[0].Issue.CreatedAt before any request is sent, so there is no echo to
// measure — the case never reaches the wire, let alone the column.
func TestServedBatchCreatorEchoesSubSecondTimestamps(t *testing.T) {
skipKnownDivergence(t, "W-BatchCreateItem.Issue", bulkParkBead,
"the case seeds Issue.CreatedAt/UpdatedAt on every item, and the wire's item publishes no timestamp "+
"member — the client refuses items[0].Issue.CreatedAt before any request is sent, so the echo it "+
"asserts has nothing to echo. "+parkBatchExplicitID)
conformance.RunBatchCreatorEchoesSubSecondTimestamps(t, t.Context(), newServedBatchCreatorFixture(t, "hb12"))
}
// The last TWO items of the wire's item vocabulary, both on the EPHEMERAL half
// of it and both parked for the reason the eight above are: apigen.BatchCreateItem
// carries eight content members and no id and no wisp flag, so an item cannot
// ask for the plane it lands on and cannot be referred to by a later item.
//
// The ephemeral plane's own batch behavior is therefore unreachable from this
// role over http rather than merely unasserted, and no bespoke case stands in
// for it: there is no server-generated-id spelling of "put this item in the
// wisps table". That is what makes these the two parks with nothing beside them.
func TestServedBatchCreatorKeepsAnEphemeralItemsLabelsOffTheDurablePlane(t *testing.T) {
skipKnownDivergence(t, "W-BatchCreateItem.Issue", bulkParkBead,
"the case's single item sets Issue.Ephemeral, and the wire's item publishes no wisp member at all — "+
"so there is no request that puts a batch-created row on the ephemeral plane, and the labels this "+
"case follows there have nowhere to land. "+parkBatchExplicitID)
conformance.RunBatchCreatorKeepsAnEphemeralItemsLabelsOffTheDurablePlane(t, t.Context(), newServedBatchCreatorFixture(t, "hb10"))
}
func TestServedBatchCreatorLinksAnEarlierItemOnTheEphemeralPlane(t *testing.T) {
skipKnownDivergence(t, "L-batchcreate-inbatch", bulkParkBead,
"it is the in-batch edge of TestServedBatchCreatorLinksAnEarlierItemOfTheSameBatch on the ephemeral "+
"plane, so it needs BOTH members the item vocabulary withholds: an id for the earlier item to be "+
"named by, and a wisp flag for either item to land on that plane at all")
conformance.RunBatchCreatorLinksAnEarlierItemOnTheEphemeralPlane(t, t.Context(), newServedBatchCreatorFixture(t, "hb11"))
}
func TestServedBatchCreatorDoesNotMutateTheCallerRequest(t *testing.T) {
skipKnownDivergence(t, "W-CreateBatchRequest.Provenance", bulkParkBead,
"the case sends CreateBatchRequest.Provenance, which the client refuses; the no-mutation promise it is really about — the assigned id lands on the RESULT and never on the caller's issue — is asserted by TestBatchCreateDoesNotWriteThroughTheCallersItems.")
conformance.RunBatchCreatorDoesNotMutateTheCallerRequest(t, t.Context(), newServedBatchCreatorFixture(t, "hb09"))
}
const parkBatchExplicitID = "the case names its items' ids and passes ForceIDPrefix (the contract's own preamble says every case does), and neither is expressible: BatchCreateItem publishes no id member, so ids over http are the server's to assign."
// TestServedBatchCreateAcceptsAForeignEdgeTarget is the foreign-target half of
// the edge clause, over SERVER-GENERATED ids — the shape an http workspace can
// actually ask for.
//
// Both spellings are asserted because they are one rule: a target this database
// was never going to hold is not a miss, whether it is an `external:` reference
// or an id belonging to another repository.
func TestServedBatchCreateAcceptsAForeignEdgeTarget(t *testing.T) {
env := newServedEnv(t, "hbext")
ctx := t.Context()
creator, err := env.subject.BatchCreator()
if err != nil {
t.Fatalf("BatchCreator(): %v", err)
}
const externalTarget, foreignTarget = "external:JIRA-4471", "otherrig-9910"
result, err := creator.CreateBatch(ctx, issueops.CreateBatchRequest{
Actor: "batch-writer",
Items: []issueops.BatchCreateItem{
{
Issue: &issueops.Issue{Title: "depends on something outside beads", Priority: 2, IssueType: types.TypeTask},
Dependencies: []issueops.CreateDependency{{TargetID: externalTarget, Type: types.DepBlocks}},
},
{
Issue: &issueops.Issue{Title: "depends on another rig", Priority: 2, IssueType: types.TypeTask},
Dependencies: []issueops.CreateDependency{{TargetID: foreignTarget, Type: types.DepBlocks}},
},
},
})
if err != nil {
t.Fatalf("CreateBatch with foreign edge targets: %v", err)
}
if len(result.Issues) != 2 {
t.Fatalf("CreateBatch returned %d issues, want 2", len(result.Issues))
}
// The target column depends on what the target IS, and neither of these is a
// stored row: an `external:` reference and a foreign-prefix id both land in
// depends_on_external, which is the whole point of the rule.
for i, target := range []string{externalTarget, foreignTarget} {
var edges int
if err := env.queryScalar(ctx,
`SELECT COUNT(*) FROM dependencies WHERE issue_id = ?
AND (depends_on_issue_id = ? OR depends_on_external = ?)`,
[]any{result.Issues[i].ID, target, target}, &edges); err != nil {
t.Fatalf("count the edge onto %s: %v", target, err)
}
if edges != 1 {
t.Errorf("edges onto %s = %d, want 1", target, edges)
}
}
}
// TestServedBatchCreateRefusesAnAbsentEdgeTargetAsValidation is
// L-batchcreate-target's pin, and it RUNS.
//
// The half that still holds is the half worth having: a target naming nothing
// takes the WHOLE batch down, so a client cannot end up with issues whose
// declared relationships are missing. Only the second sentinel is lost.
func TestServedBatchCreateRefusesAnAbsentEdgeTargetAsValidation(t *testing.T) {
env := newServedEnv(t, "hbmiss")
ctx := t.Context()
creator, err := env.subject.BatchCreator()
if err != nil {
t.Fatalf("BatchCreator(): %v", err)
}
_, err = creator.CreateBatch(ctx, issueops.CreateBatchRequest{
Actor: "batch-writer",
Items: []issueops.BatchCreateItem{
{Issue: &issueops.Issue{Title: "would land", Priority: 2, IssueType: types.TypeTask}},
{
Issue: &issueops.Issue{Title: "names something absent", Priority: 2, IssueType: types.TypeTask},
Dependencies: []issueops.CreateDependency{{TargetID: "hbmiss-absent", Type: types.DepBlocks}},
},
},
})
if err == nil {
t.Fatal("a batch whose edge target names nothing was accepted; a create that dropped an edge is data loss the caller cannot learn about")
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("refusal = %v, want ErrValidation", err)
}
if errors.Is(err, issueops.ErrNotFound) {
t.Error("the refusal wraps ErrNotFound; L-batchcreate-target says the wire cannot express it — retire the row rather than the assertion")
}
// The sibling item is what an implementation that dropped the edge and kept
// the issues would leave behind.
var created int
if err := env.queryScalar(ctx, "SELECT COUNT(*) FROM issues", nil, &created); err != nil {
t.Fatalf("count the issues: %v", err)
}
if created != 0 {
t.Errorf("the refused batch created %d issue(s); it is all or nothing", created)
}
}
// TestServedBatchCreateRecordsOneHistoryEntry is the durable half of "at most
// one history entry", over a request with no Provenance — which is the only
// shape http can send.
func TestServedBatchCreateRecordsOneHistoryEntry(t *testing.T) {
env := newServedEnv(t, "hbhist")
ctx := t.Context()
creator, err := env.subject.BatchCreator()
if err != nil {
t.Fatalf("BatchCreator(): %v", err)
}
before, err := env.countHistory(ctx)
if err != nil {
t.Fatalf("count history: %v", err)
}
if _, err := creator.CreateBatch(ctx, issueops.CreateBatchRequest{
Actor: "batch-writer",
Items: []issueops.BatchCreateItem{
{Issue: &issueops.Issue{Title: "one", Priority: 2, IssueType: types.TypeTask}},
{Issue: &issueops.Issue{Title: "two", Priority: 2, IssueType: types.TypeTask}},
{Issue: &issueops.Issue{Title: "three", Priority: 2, IssueType: types.TypeTask}},
},
}); err != nil {
t.Fatalf("CreateBatch(3 durable items): %v", err)
}
after, err := env.countHistory(ctx)
if err != nil {
t.Fatalf("count history: %v", err)
}
if delta := after - before; delta != 1 {
t.Errorf("history entries += %d for a 3-item batch, want 1: the request is the transaction, so it records one entry", delta)
}
}
// The raw-row hooks the delete cases need. They read through the REFERENCE
// store's own SQL handle, because whether a row is really gone is the one claim
// a delete result cannot be trusted to make about itself.
func seedServedWisp(t *testing.T, ctx context.Context, env *servedEnv, id string) {
t.Helper()
issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := env.createWisp(ctx, issue, "seed"); err != nil {
t.Fatalf("seed wisp %s: %v", id, err)
}
}
// seedServedEdge makes dependent depend on blocker. The PLANE is the source's,
// resolved by the reference store itself, which is why a case can seed a
// cross-plane edge without naming a table.
func seedServedEdge(t *testing.T, ctx context.Context, env *servedEnv, dependent, blocker string) {
t.Helper()
if err := env.addDependency(ctx, &types.Dependency{
IssueID: dependent, DependsOnID: blocker, Type: types.DepBlocks,
}, "seed"); err != nil {
t.Fatalf("seed the edge %s -> %s: %v", dependent, blocker, err)
}
}
func assertServedIssueRows(t *testing.T, ctx context.Context, env *servedEnv, want int, ids ...string) {
t.Helper()
assertServedPlaneRows(t, ctx, env, "issues", want, ids...)
}
func assertServedWispRows(t *testing.T, ctx context.Context, env *servedEnv, want int, ids ...string) {
t.Helper()
assertServedPlaneRows(t, ctx, env, "wisps", want, ids...)
}
//nolint:gosec // G201: table is chosen by the caller from the two plane tables.
func assertServedPlaneRows(t *testing.T, ctx context.Context, env *servedEnv, table string, want int, ids ...string) {
t.Helper()
for _, id := range ids {
var rows int
query := "SELECT COUNT(*) FROM " + table + " WHERE id = ?"
if err := env.queryScalar(ctx, query, []any{id}, &rows); err != nil {
t.Fatalf("count %s in %s: %v", id, table, err)
}
if rows != want {
t.Errorf("%s rows for %s = %d, want %d", table, id, rows, want)
}
}
}
// assertServedEdgeRows counts one edge in the plane table its SOURCE lives in.
// The target column is COALESCEd across the three the schema publishes, so a
// cross-plane edge is counted whichever end of it is a wisp.
//
//nolint:gosec // G201: table is chosen by the caller from the two edge tables.
func assertServedEdgeRows(t *testing.T, ctx context.Context, env *servedEnv, table string, want int, dependent, blocker string) {
t.Helper()
var rows int
query := "SELECT COUNT(*) FROM " + table + " WHERE issue_id = ? AND " +
"COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?"
if err := env.queryScalar(ctx, query, []any{dependent, blocker}, &rows); err != nil {
t.Fatalf("count %s edges %s -> %s: %v", table, dependent, blocker, err)
}
if rows != want {
t.Errorf("%s rows %s -> %s = %d, want %d", table, dependent, blocker, rows, want)
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,196 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_commenter_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The Commenter contract, run through the http client against a real bd serve.
//
// NOTHING IS PARKED HERE: the request has three members, one of which is the
// path, and the answer has one, so there is no filter to drop and no shape for a
// refusal to hide in — the whole thirteen-case tier runs.
//
// THAT IS NOT THE SAME AS "NO DIVERGENCE", and one lives on the AUTHOR. The
// operation applies the `actor` rules to it — trim, then refuse a control rune —
// and passes the trimmed value on, while the role itself only checks the field
// is non-empty and stores what it was given. So the same request stores a
// different value on the two legs, and a value one leg stores the other refuses.
// No contract case reaches it, which is exactly why it needs a pin of its own:
// L-comment-author, asserted below by
// TestServedCommentAuthorTakesTheServersActorRule.
//
// TWO OF THE THIRTEEN ARE WHY THIS TIER EXISTS RATHER THAN A UNIT TEST.
//
// - THE WISP PLANE. `CommentOnAWispLandsOnTheWispThread` writes through the
// client to an EPHEMERAL anchor and reads the row back out of wisp_comments
// raw. Nothing above the storage seam picks that plane: the operation
// resolves the anchor inside the transaction it writes in, so the only way to
// know the comment landed on the ephemeral thread is to look at the ephemeral
// table — which a client cannot do and this harness can.
// - THE ABSENT DURABLE TRACE. `RecordsExactlyOneHistoryEntry` measures the
// version history around the call: exactly one entry for a durable comment
// and exactly ZERO for an ephemeral one, because the wisp tables are
// dolt-ignored. That is a fact about what the server did NOT write, and no
// answer this client receives carries it.
//
// THE 1 MiB BOUND IS ONE NUMBER ON BOTH PLANES ONLY BECAUSE OF MIGRATION 0065,
// which widened wisp_comments.text from TEXT's 65535 bytes to match the durable
// column. Before it, this operation — which resolves its anchor across both
// planes — put a caller under a bound that depended on which plane its id
// happened to name, with nothing above the storage seam able to say which. There
// is no client-side length check to add; the fix was the column, and the cases
// below exercise both planes through the same body.
//
// SEEDING STAYS ON THE REFERENCE STORE even though this client now HAS a
// Commenter. That is the harness rule and it bites hardest exactly here: a
// Commenter contract whose preconditions were seeded through the Commenter under
// test would prove only that the client agrees with itself.
func newServedCommenterFixture(t *testing.T, prefix string) conformance.CommenterFixture {
t.Helper()
env := newServedEnv(t, prefix)
commenter, err := env.subject.Commenter()
if err != nil {
t.Fatalf("Commenter(): %v", err)
}
return conformance.CommenterFixture{
IssuePrefix: env.prefix,
Commenter: commenter,
CreateIssue: env.createIssue,
CreateWisp: env.createWisp,
QueryScalar: env.queryScalar,
CountHistory: env.countHistory,
SeedCommentAt: env.seedCommentAt,
}
}
func TestServedCommenterContract(t *testing.T) {
fixture := newServedCommenterFixture(t, "hcm")
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.CommenterFixture)
}{
{"StoresTextVerbatim", conformance.RunCommenterStoresTextVerbatim},
{"ResultMirrorsTheStoredRow", conformance.RunCommenterResultMirrorsTheStoredRow},
{"AdvancesALiveStampPastTheThreadsNewestComment", conformance.RunCommenterAdvancesALiveStampPastTheThreadsNewestComment},
{"TakesTheClockWhenTheThreadIsBehindIt", conformance.RunCommenterTakesTheClockWhenTheThreadIsBehindIt},
{"CommentOnAWispLandsOnTheWispThread", conformance.RunCommenterCommentOnAWispLandsOnTheWispThread},
{"RefusesAnIDOnNeitherPlane", conformance.RunCommenterRefusesAnIDOnNeitherPlane},
{"RefusesAnEmptyIssueID", conformance.RunCommenterRefusesAnEmptyIssueID},
{"DoesNotResolvePrefixes", conformance.RunCommenterDoesNotResolvePrefixes},
{"RecordsExactlyOneHistoryEntry", conformance.RunCommenterRecordsExactlyOneHistoryEntry},
{"LeavesTheAnchorIssueUntouched", conformance.RunCommenterLeavesTheAnchorIssueUntouched},
{"RefusesBlankText", conformance.RunCommenterRefusesBlankText},
{"RefusesAnEmptyAuthor", conformance.RunCommenterRefusesAnEmptyAuthor},
{"LeavesTheCallersRequestAlone", conformance.RunCommenterLeavesTheCallersRequestAlone},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}
// TestServedCommentAuthorTakesTheServersActorRule is L-comment-author's pin, and
// it RUNS.
//
// BOTH HALVES, because they are one rule with two consequences and a pin that
// checked one would let the other rot. The stored half is read RAW out of the
// comments table rather than off the result: a body that trimmed on the way in
// and echoed the caller's own string back would pass a result-only check, which
// is the same trap the contract's own verbatim-text case is written around.
//
// The premise is asserted before the divergence is: the reference store is asked
// the SAME question through its own Commenter, so "the two legs differ" is a
// measurement rather than an assumption. Without it a server that stopped
// trimming and a role that started would both read as this test passing.
func TestServedCommentAuthorTakesTheServersActorRule(t *testing.T) {
env := newServedEnv(t, "hcma")
commenter, err := env.subject.Commenter()
if err != nil {
t.Fatalf("Commenter(): %v", err)
}
reference, err := env.reference.Commenter()
if err != nil {
t.Fatalf("reference Commenter(): %v", err)
}
ctx := t.Context()
served, local := env.prefix+"-served", env.prefix+"-local"
for _, id := range []string{served, local} {
if err := env.createIssue(ctx, &types.Issue{
ID: id, Title: "author rule", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask,
}, "seed"); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
}
// ── The stored value ───────────────────────────────────────────────────
const padded = " Ada Lovelace "
const trimmed = "Ada Lovelace"
if _, err := commenter.AddComment(ctx, issueops.AddCommentRequest{
Author: padded, IssueID: served, Text: "over the wire",
}); err != nil {
t.Fatalf("AddComment over http: %v", err)
}
if got := servedCommentAuthor(t, ctx, env, served); got != trimmed {
t.Errorf("the http leg stored author %q, want %q — the operation applies the actor rule's trim (L-comment-author)", got, trimmed)
}
if _, err := reference.AddComment(ctx, issueops.AddCommentRequest{
Author: padded, IssueID: local, Text: "through the reference role",
}); err != nil {
t.Fatalf("AddComment through the reference store: %v", err)
}
if got := servedCommentAuthor(t, ctx, env, local); got != padded {
t.Errorf("the local leg stored author %q, want %q verbatim; if this leg started trimming too, "+
"L-comment-author has retired and the row should go rather than this test being relaxed", got, padded)
}
// ── The refusal ────────────────────────────────────────────────────────
//
// A C1 introducer, which is the value the server's rule exists for: it lands
// in a column every renderer of the thread prints.
const escaping = "ada\x1b[31m"
err = func() error {
_, err := commenter.AddComment(ctx, issueops.AddCommentRequest{
Author: escaping, IssueID: served, Text: "refused",
})
return err
}()
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("AddComment with a control rune over http = %v, want ErrValidation", err)
}
if _, err := reference.AddComment(ctx, issueops.AddCommentRequest{
Author: escaping, IssueID: local, Text: "stored",
}); err != nil {
t.Fatalf("AddComment with a control rune through the reference store = %v, want it STORED; "+
"if the role started refusing this too, L-comment-author has retired", err)
}
}
// servedCommentAuthor reads the newest comment's author column raw, which is the
// only place the stored value can be observed: the role's own result echoes what
// the write produced, and this case is about what LANDED.
func servedCommentAuthor(t *testing.T, ctx context.Context, env *servedEnv, issueID string) string {
t.Helper()
var author string
if err := env.queryScalar(ctx,
"SELECT author FROM comments WHERE issue_id = ? ORDER BY id DESC LIMIT 1", []any{issueID},
&author); err != nil {
t.Fatalf("read the stored author for %s: %v", issueID, err)
}
return author
}

View file

@ -0,0 +1,140 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_config_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// The WorkspaceConfig contract against the served surface — the WHOLE tier,
// reads and writes, now that #5596's two verbs are wired.
//
// IT USED TO BE HAND-WRITTEN, and the reason it was is worth recording rather
// than deleting: every case in the shared suite writes through the role, this
// backend's writes refused, so adopting the tier would have parked twenty-one
// cases to run four. What stood in its place asserted the subset a refusing
// backend could reach. Client wave ga-jpywb wires SetSetting and UnsetSetting,
// so the suite is adoptable whole and the stand-in is gone — it asserted a
// strict subset of what runs below, which is the retirement condition a
// stand-in should have.
//
// ONE ENVIRONMENT FOR THE WHOLE SUITE, and here that is a correctness
// requirement rather than a saving, exactly as it is on the two store legs:
// config keys are global to a workspace, the two projected keys are written by
// NAME (their whole point is that those exact names project), and the
// refused-write case takes a history delta. All three need the subtests
// sequential over one plane.
func TestServedWorkspaceConfigContract(t *testing.T) {
e := newServedEnv(t, "hwcfg")
ctx := t.Context()
fixture := newServedWorkspaceConfigFixture(t, e)
t.Run("StoresAValueVerbatim", func(t *testing.T) {
conformance.RunWorkspaceConfigStoresAValueVerbatim(t, ctx, fixture)
})
t.Run("ReplacesAnExistingValue", func(t *testing.T) {
conformance.RunWorkspaceConfigReplacesAnExistingValue(t, ctx, fixture)
})
t.Run("ConflatesAnUnsetKeyWithAnEmptyValue", func(t *testing.T) {
conformance.RunWorkspaceConfigConflatesAnUnsetKeyWithAnEmptyValue(t, ctx, fixture)
})
t.Run("ListsEveryStoredSetting", func(t *testing.T) {
conformance.RunWorkspaceConfigListsEveryStoredSetting(t, ctx, fixture)
})
t.Run("ListExcludesTheKVPlane", func(t *testing.T) {
conformance.RunWorkspaceConfigListExcludesTheKVPlane(t, ctx, fixture)
})
t.Run("PointReadRefusesTheKVPlane", func(t *testing.T) {
conformance.RunWorkspaceConfigPointReadRefusesTheKVPlane(t, ctx, fixture)
})
t.Run("UnsetRemovesTheSetting", func(t *testing.T) {
conformance.RunWorkspaceConfigUnsetRemovesTheSetting(t, ctx, fixture)
})
t.Run("UnsetOfAnAbsentKeySucceeds", func(t *testing.T) {
conformance.RunWorkspaceConfigUnsetOfAnAbsentKeySucceeds(t, ctx, fixture)
})
t.Run("RefusesAnEmptyKey", func(t *testing.T) {
conformance.RunWorkspaceConfigRefusesAnEmptyKey(t, ctx, fixture)
})
t.Run("RefusesTheProtectedKeyOnSet", func(t *testing.T) {
conformance.RunWorkspaceConfigRefusesTheProtectedKeyOnSet(t, ctx, fixture)
})
t.Run("UnsetDoesNotRefuseTheProtectedKey", func(t *testing.T) {
conformance.RunWorkspaceConfigUnsetDoesNotRefuseTheProtectedKey(t, ctx, fixture)
})
t.Run("RefusesAnUnparseableCustomStatus", func(t *testing.T) {
conformance.RunWorkspaceConfigRefusesAnUnparseableCustomStatus(t, ctx, fixture)
})
t.Run("ProjectsCustomStatuses", func(t *testing.T) {
conformance.RunWorkspaceConfigProjectsCustomStatuses(t, ctx, fixture)
})
t.Run("ProjectsCustomTypes", func(t *testing.T) {
conformance.RunWorkspaceConfigProjectsCustomTypes(t, ctx, fixture)
})
t.Run("UnsetLeavesTheProjectionBehind", func(t *testing.T) {
conformance.RunWorkspaceConfigUnsetLeavesTheProjectionBehind(t, ctx, fixture)
})
t.Run("ARefusedWriteRecordsNoHistory", func(t *testing.T) {
conformance.RunWorkspaceConfigARefusedWriteRecordsNoHistory(t, ctx, fixture)
})
t.Run("KeysAreCaseSensitive", func(t *testing.T) {
conformance.RunWorkspaceConfigKeysAreCaseSensitive(t, ctx, fixture)
})
t.Run("CustomStatusReadsAreOrderedByName", func(t *testing.T) {
conformance.RunWorkspaceConfigCustomStatusReadsAreOrderedByName(t, ctx, fixture)
})
t.Run("CustomTypeReadsAreOrderedByName", func(t *testing.T) {
conformance.RunWorkspaceConfigCustomTypeReadsAreOrderedByName(t, ctx, fixture)
})
t.Run("ConfiguredInfraTypesReplaceTheDefaultSet", func(t *testing.T) {
conformance.RunWorkspaceConfigConfiguredInfraTypesReplaceTheDefaultSet(t, ctx, fixture)
})
t.Run("UnconfiguredVocabularyReadsAreEmptyNotErrors", func(t *testing.T) {
conformance.RunWorkspaceConfigUnconfiguredVocabularyReadsAreEmptyNotErrors(t, ctx, fixture)
})
}
// newServedWorkspaceConfigFixture binds the ROLE to the client and everything
// else to the reference store, which is this harness's standing rule.
//
// THE VOCABULARY READER IS THE ONE EXCEPTION, and it is the same exception the
// ReadyClaimer fixture makes for its Reader: the three reads it holds are the
// SUBJECT's own (vocabulary.go), so the projection cases compare two of this
// client's surfaces — a write through the role, and a vocabulary read that goes
// back over the wire for the key it wrote — against each other. Binding the
// server's would compare the server to itself and prove nothing about the
// client.
func newServedWorkspaceConfigFixture(t *testing.T, e *servedEnv) conformance.WorkspaceConfigFixture {
t.Helper()
settings, err := e.subject.WorkspaceConfig()
if err != nil {
t.Fatalf("WorkspaceConfig(): %v", err)
}
// The protected-key cases need an issue_prefix to remove and restore, and
// they need it written PAST the role, which refuses to write it. newServedEnv
// already seeds one through the reference store; this restates it so the
// fixture does not depend on the harness's own seeding order.
if err := e.setConfig(t.Context(), "issue_prefix", e.prefix); err != nil {
t.Fatalf("seed issue_prefix: %v", err)
}
return conformance.WorkspaceConfigFixture{
IssuePrefix: e.prefix,
WorkspaceConfig: settings,
SetConfig: e.setConfig,
QueryScalar: e.queryScalar,
CountHistory: e.countHistory,
Vocabulary: &conformance.WorkspaceVocabularyReader{
CustomStatuses: e.subject.GetCustomStatusesDetailed,
CustomTypes: e.subject.GetCustomTypes,
InfraTypes: func(ctx context.Context) (map[string]bool, error) {
return e.subject.GetInfraTypes(ctx), nil
},
},
}
}

View file

@ -0,0 +1,236 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_config_write_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"errors"
"strings"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The three claims about the config WRITE half that the shared contract cannot
// make, because each of them is about something only THIS leg has: an operation
// that redacts its own answer, an operation that bounds a value the role does
// not, and a PUT whose second call must not be short-circuited.
//
// They are here rather than in the unit tier because each needs a real server:
// the redaction predicate, the two edge bounds and the write-through are all the
// SERVER's, and a stub transport would let this file assert whatever it liked
// about them.
// TestServedConfigWriteAnswersTheReadThatFollowsIt is the redaction doctrine,
// pinned on both sides of the one key it changes anything for.
//
// The operation PERMITS a credential-bearing write and WITHHOLDS the value from
// its own answer — one projection serves the write and the read, so the body of
// a PUT is byte-identical to the body of the GET after it. That leaves a
// successful write whose `value` member is absent, and the role's result has no
// spelling for "withheld": reporting "" would tell a caller the plane holds
// nothing under that key, which is the write-side version of the confusion
// RedactedSettingError exists to prevent on the read side.
//
// So the client answers with the value it SENT, and this asserts why that is
// honest rather than convenient: the value really is stored, read RAW from the
// reference store past the wire that hid it.
//
// WHAT THIS CASE CANNOT SAY is that the ordinary key beside it is TRANSCRIBED
// off the answer rather than echoed from the request. Against a correct server
// the two are byte-identical — the operation promises the stored value equals
// the value sent for every key it accepts — so the difference is pinned where it
// is observable, against a transport that answers something else:
// TestSetSettingTranscribesTheAnswerRatherThanEchoingTheRequest. The ordinary
// key runs here anyway, because a client that transcribed the WRONG member would
// fail it.
func TestServedConfigWriteAnswersTheReadThatFollowsIt(t *testing.T) {
e := newServedEnv(t, "hcfgw1")
ctx := t.Context()
settings := servedSettings(t, e)
const secretKey = "notion.token"
const secret = "shhh-real-secret"
res, err := settings.SetSetting(ctx, issueops.SetSettingRequest{Key: secretKey, Value: secret})
if err != nil {
t.Fatalf("SetSetting on a credential-bearing key = %v; the write is permitted and only the ANSWER withholds", err)
}
if res.Key != secretKey {
t.Errorf("SetSetting echoed key %q, want %q", res.Key, secretKey)
}
if res.Value != secret {
t.Errorf("SetSetting reported value %q, want %q: the answer withheld it, and \"\" would say the plane stores nothing there",
res.Value, secret)
}
// Read RAW, past the role and past the wire: the point is that the value the
// response would not repeat IS the value the workspace now holds.
stored, err := e.reference.GetConfig(ctx, secretKey)
if err != nil {
t.Fatalf("read the stored credential back from the reference store: %v", err)
}
if stored != secret {
t.Errorf("the workspace stores %q under %q, want %q", stored, secretKey, secret)
}
// And the READ that follows still withholds, which is the other half of "the
// PUT body is the GET body": a write does not unlock the key it just wrote.
if _, err := settings.GetSetting(ctx, issueops.GetSettingRequest{Key: secretKey}); !errors.Is(err, ErrSettingRedacted) {
t.Errorf("GetSetting after the write = %v, want ErrSettingRedacted; the write does not unlock the read", err)
}
// The ordinary key is TRANSCRIBED, not echoed. The server answers this one
// with the stored value on the wire, so a client that reported the request
// unconditionally would be indistinguishable here — until a server stored
// something else.
const plainKey = "custom.hcfgw1-plain"
const plain = " spaces and , commas "
res, err = settings.SetSetting(ctx, issueops.SetSettingRequest{Key: plainKey, Value: plain})
if err != nil {
t.Fatalf("SetSetting on an ordinary key: %v", err)
}
if res.Value != plain {
t.Errorf("SetSetting reported %q, want the verbatim %q", res.Value, plain)
}
got, err := settings.GetSetting(ctx, issueops.GetSettingRequest{Key: plainKey})
if err != nil || got.Value != plain {
t.Errorf("GetSetting after the write = (%q, %v), want (%q, nil)", got.Value, err, plain)
}
}
// TestServedConfigSetTwiceReachesTheRoleBothTimes pins that this client adds no
// idempotence of its own.
//
// The role's contract is explicit that a write of the value already there still
// performs the write and its projection — a no-op detection would make repairing
// a normalized table that had drifted from its row depend on the row having
// changed — and the wire carries no `changed` member to tempt one. A client that
// compared first would be the only leg on which that repair silently stopped
// happening, and nothing else in this tree would notice.
//
// It is measured through the PROJECTION rather than through the row, because the
// row is what a short-circuit would leave looking correct: the table is
// desynchronized out of band, the same value is written again, and the table has
// to come back.
func TestServedConfigSetTwiceReachesTheRoleBothTimes(t *testing.T) {
e := newServedEnv(t, "hcfgw2")
ctx := t.Context()
settings := servedSettings(t, e)
const value = "research,ops"
first, err := settings.SetSetting(ctx, issueops.SetSettingRequest{Key: issueops.SettingKeyTypesCustom, Value: value})
if err != nil {
t.Fatalf("the first SetSetting: %v", err)
}
if got := servedCustomTypeRows(t, ctx, e); got != 2 {
t.Fatalf("custom_types holds %d rows after the first write, want 2", got)
}
// Desynchronize the projection PAST the role, which is the state the role's
// contract says a repeated write exists to repair.
if err := e.exec(ctx, []conformance.SQLStatement{{Query: "DELETE FROM custom_types"}}); err != nil {
t.Fatalf("desynchronize the projection: %v", err)
}
if got := servedCustomTypeRows(t, ctx, e); got != 0 {
t.Fatalf("custom_types holds %d rows after the delete, want 0; the case proves nothing", got)
}
second, err := settings.SetSetting(ctx, issueops.SetSettingRequest{Key: issueops.SettingKeyTypesCustom, Value: value})
if err != nil {
t.Fatalf("the second SetSetting: %v", err)
}
if got := servedCustomTypeRows(t, ctx, e); got != 2 {
t.Errorf("custom_types holds %d rows after re-writing the same value, want 2: the second write did not reach the role, "+
"so a table that had drifted from its row can never be repaired through this client", got)
}
// And the two answers are the same answer. There is no `already_set` on this
// surface and this client must not invent one.
if first != second {
t.Errorf("the two writes answered %+v and %+v; a PUT's second answer is its first", first, second)
}
}
// TestServedConfigWriteBoundsAreTheServersAndNotThisClients is L-config-bounds,
// measured against the reference store through its OWN role so "the two legs
// differ" is observed rather than asserted.
//
// Both bounds are the OPERATION's: internal/httpapi checks them before the role
// is called, and workapi.ValidateSettingWrite — the rule every leg shares —
// applies neither. So the same request is a typed, member-named refusal here and
// a raw column overflow there, and this client restates nothing, for the reason
// the ledger row gives.
//
// THE CEILING ITSELF IS ASSERTED FIRST. Without it the case would pass against a
// client that refused every value: what makes the refusal a BOUND rather than a
// blanket is that exactly types.MaxTextBytes bytes is stored.
func TestServedConfigWriteBoundsAreTheServersAndNotThisClients(t *testing.T) {
e := newServedEnv(t, "hcfgw3")
ctx := t.Context()
settings := servedSettings(t, e)
reference, err := e.reference.WorkspaceConfig()
if err != nil {
t.Fatalf("the reference store's WorkspaceConfig(): %v", err)
}
atCeiling := strings.Repeat("y", types.MaxTextBytes)
if _, err := settings.SetSetting(ctx, issueops.SetSettingRequest{Key: "custom.hcfgw3-at", Value: atCeiling}); err != nil {
t.Fatalf("a value of exactly %d bytes was refused: %v", types.MaxTextBytes, err)
}
past := strings.Repeat("y", types.MaxTextBytes+1)
httpErr := setSettingErr(ctx, settings, "custom.hcfgw3-past", past)
if !errors.Is(httpErr, issueops.ErrValidation) {
t.Errorf("a value one byte past the column = %v, want ErrValidation carried back from the operation's 400", httpErr)
}
if refErr := setSettingErr(ctx, reference, "custom.hcfgw3-past-local", past); errors.Is(refErr, issueops.ErrValidation) {
t.Errorf("the reference store answered ErrValidation for the same value (%v); if both legs now classify it, "+
"L-config-bounds has retired and this pin should go with it", refErr)
} else if refErr == nil {
t.Error("the reference store STORED a value past the column; the bound this row is about does not exist")
}
// The KEY bound splits the same way — and only on the WRITE. The remove
// checks that the key names something and nothing more, on both legs.
longKey := "custom.hcfgw3-" + strings.Repeat("k", types.MaxFieldLen)
if err := setSettingErr(ctx, settings, longKey, "v"); !errors.Is(err, issueops.ErrValidation) {
t.Errorf("a key past the column on the write = %v, want ErrValidation", err)
}
if err := setSettingErr(ctx, reference, longKey+"2", "v"); errors.Is(err, issueops.ErrValidation) {
t.Errorf("the reference store answered ErrValidation for the same key (%v); the key half of L-config-bounds has retired", err)
}
if _, err := settings.UnsetSetting(ctx, issueops.UnsetSettingRequest{Key: longKey}); err != nil {
t.Errorf("removing an over-long key = %v, want success: the remove carries no length bound on either leg", err)
}
}
// servedSettings is the SUBJECT's settings role, which every case here drives.
func servedSettings(t *testing.T, e *servedEnv) issueops.WorkspaceConfig {
t.Helper()
settings, err := e.subject.WorkspaceConfig()
if err != nil {
t.Fatalf("WorkspaceConfig(): %v", err)
}
return settings
}
// setSettingErr is the error half of a write, for the arms that are about the
// refusal rather than the result.
func setSettingErr(ctx context.Context, settings issueops.WorkspaceConfig, key, value string) error {
_, err := settings.SetSetting(ctx, issueops.SetSettingRequest{Key: key, Value: value})
return err
}
// servedCustomTypeRows counts the projected table the write re-synchronizes.
func servedCustomTypeRows(t *testing.T, ctx context.Context, e *servedEnv) int {
t.Helper()
var rows int
if err := e.queryScalar(ctx, "SELECT COUNT(*) FROM custom_types", nil, &rows); err != nil {
t.Fatalf("count custom_types: %v", err)
}
return rows
}

View file

@ -0,0 +1,96 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_counter_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// The Counter contract, run through the http client against a real bd serve.
//
// NOTHING IS PARKED HERE, and on this role that is a statement rather than a
// happy accident. Every case scopes itself with IDFilter — the count publishes
// `id` where the LISTING does not, which is why the Reader family parks nine
// cases on E-ListRequest.IDFilter and this one parks none — and every filter the
// contract reaches for is a parameter this operation carries. The plane cases in
// particular cross whole: `include_infra` is one flag on the wire and one flag
// on the request, and what it MEANS is four decisions the server's own role
// makes from the workspace's infra vocabulary, which is a config load this
// client could not perform and does not have to.
func servedCounterFixture(t *testing.T, e *servedEnv, prefix string) conformance.CounterFixture {
t.Helper()
counter, err := e.subject.Counter()
if err != nil {
t.Fatalf("Counter(): %v", err)
}
return conformance.CounterFixture{
IssuePrefix: prefix,
Counter: counter,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
CountHistory: e.countHistory,
AddDependency: e.addDependency,
// List is deliberately left nil (unlike the dolt leg's wiring in
// internal/storage/dolt/counter_contract_test.go). This client's OWN
// ListRequest encoder table (encode/table.go's listTable) has
// pre-existing, permanent refusals for NoParent and ExcludeTypes
// (E-ListRequest.NoParent, E-ListRequest.ExcludeTypes) — a divergence
// on the LISTING operation unrelated to S8 — so wiring List here would
// make RunCounterNoParentMatchesListCardinality and
// RunCounterExcludeTypesMatchesListCardinality FAIL rather than the
// requireCounterList skip this fixture's own documented design
// intends for a leg that cannot express the comparison.
}
}
func TestServedCounterContract(t *testing.T) {
e := newServedEnv(t, "cnt")
fixture := servedCounterFixture(t, e, "cnt")
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.CounterFixture)
}{
{"CountsTheDurablePlaneByDefault", conformance.RunCounterCountsTheDurablePlaneByDefault},
{"IncludeInfraMergesTheWispTier", conformance.RunCounterIncludeInfraMergesTheWispTier},
{"IncludeInfraExcludesGates", conformance.RunCounterIncludeInfraExcludesGates},
{"CountsClosedRows", conformance.RunCounterCountsClosedRows},
{"AnUnknownStatusMatchesNothing", conformance.RunCounterAnUnknownStatusMatchesNothing},
{"GroupsPartitionTheScalarSet", conformance.RunCounterGroupsPartitionTheScalarSet},
{"LabelBucketsOverlapSoTotalIsNotTheirSum", conformance.RunCounterLabelBucketsOverlapSoTotalIsNotTheirSum},
{"NamesTheEmptyBuckets", conformance.RunCounterNamesTheEmptyBuckets},
{"PrefixesPriorityBuckets", conformance.RunCounterPrefixesPriorityBuckets},
{"PriorityBucketsCountZeroAndCountEveryRow", conformance.RunCounterPriorityBucketsCountZeroAndCountEveryRow},
{"TheNoLabelBucketIsAbsentWhenEveryRowIsLabeled", conformance.RunCounterTheNoLabelBucketIsAbsentWhenEveryRowIsLabeled},
{"TypeBucketsAreTheRawTypeNames", conformance.RunCounterTypeBucketsAreTheRawTypeNames},
{"RefusesAnUnknownGroup", conformance.RunCounterRefusesAnUnknownGroup},
{"NormalizesLabelsAndLeavesTheRequestAlone", conformance.RunCounterNormalizesLabelsAndLeavesTheRequestAlone},
{"WritesNothing", conformance.RunCounterWritesNothing},
// S8 (#7199) count scope, served for real against a running bd serve:
// ParentID, NoParent, ExcludeTypes and ExcludeStatus each narrow the
// predicate over the http wire, exercising the client's encoding
// (counts_test.go covers the unit-level encoding and the pre-dial
// skew refusal; these confirm the served round trip). The three
// *MatchesListCardinality cases SKIP here (requireCounterList) rather
// than fail, since this fixture leaves List unwired — see
// servedCounterFixture's comment.
{"ParentIDScopesToChildren", conformance.RunCounterParentIDScopesToChildren},
{"NoParentExcludesChildren", conformance.RunCounterNoParentExcludesChildren},
{"ExcludeTypesNarrowsThePredicate", conformance.RunCounterExcludeTypesNarrowsThePredicate},
{"ExcludeStatusNarrowsThePredicate", conformance.RunCounterExcludeStatusNarrowsThePredicate},
{"ParentIDMatchesListCardinality", conformance.RunCounterParentIDMatchesListCardinality},
{"NoParentMatchesListCardinality", conformance.RunCounterNoParentMatchesListCardinality},
{"ExcludeTypesMatchesListCardinality", conformance.RunCounterExcludeTypesMatchesListCardinality},
{"ParentIDIncludesAWispChild", conformance.RunCounterParentIDIncludesAWispChild},
{"ParentIDAndExcludeStatusComposeOnAClosedChild", conformance.RunCounterParentIDAndExcludeStatusComposeOnAClosedChild},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}

View file

@ -0,0 +1,380 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_detail_reads_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"sort"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// The four getIssue riders and the anchored dependency-records read, run as a
// DUAL RUN: the same off-role method asked of the reference store directly and
// of the http client, and the two answers compared (ga-b8ddd.30).
//
// These are raw methods rather than roles, so they carry no backend/conformance
// contract — the audit tier and this served parity file are the right shape. The
// comparison is what the encode gate cannot make: the parameters round-trip
// through the server's decoder there, but whether the ROWS come back the same is
// a fact only a run against the served reference can establish. Here both sides
// run it.
//
// Ordering is normalized before every comparison. None of these reads promises a
// stable order across the two code paths — the reference reads them straight off
// the table, the wire assembles them through the detail view — so the parity that
// matters is the row SET and each row's fields, not the sequence.
func sortMetadata(rows []*types.IssueWithDependencyMetadata) {
sort.SliceStable(rows, func(i, j int) bool {
if rows[i].Issue.ID != rows[j].Issue.ID {
return rows[i].Issue.ID < rows[j].Issue.ID
}
return rows[i].DependencyType < rows[j].DependencyType
})
}
func sortComments(rows []*types.Comment) {
sort.SliceStable(rows, func(i, j int) bool { return rows[i].ID < rows[j].ID })
}
// shallowMetadata projects a dependents list onto the identity-and-shape fields
// its callers consume, mirroring workapi.shallowDep. The include_dependents arm
// of getIssue streams dependents in exactly this shape (be-4d36f2: hub beads
// with thousands of dependents made the full-row marshal allocate gigabytes), so
// it is the shape a dependents read answers over http and the shape `bd show`
// renders — id, status, type, priority, title, plus the edge type. Comparing the
// full local rows would fail on free-form fields no dependents consumer reads;
// comparing this projection is the parity that is actually promised.
func shallowMetadata(rows []*types.IssueWithDependencyMetadata) []*types.IssueWithDependencyMetadata {
out := make([]*types.IssueWithDependencyMetadata, 0, len(rows))
for _, row := range rows {
if row == nil {
out = append(out, nil)
continue
}
out = append(out, &types.IssueWithDependencyMetadata{
Issue: types.Issue{
ID: row.Issue.ID,
Status: row.Issue.Status,
IssueType: row.Issue.IssueType,
Priority: row.Issue.Priority,
Title: row.Issue.Title,
},
DependencyType: row.DependencyType,
})
}
return out
}
func sortRecords(rows []*types.Dependency) {
sort.SliceStable(rows, func(i, j int) bool {
if rows[i].DependsOnID != rows[j].DependsOnID {
return rows[i].DependsOnID < rows[j].DependsOnID
}
return rows[i].Type < rows[j].Type
})
}
// seedDetailReadsFixture plants a subject issue with labels, a comment, one
// outgoing dependency and one incoming dependent, so every one of the five reads
// has a non-empty answer to compare.
func seedDetailReadsFixture(t *testing.T, ctx context.Context, e *servedEnv) {
t.Helper()
rows := []*types.Issue{
{ID: "drd-root", Title: "root", Status: types.StatusOpen, IssueType: types.TypeTask, Labels: []string{"drd-alpha", "drd-beta"}},
{ID: "drd-dep", Title: "a dependency of root", Status: types.StatusOpen, IssueType: types.TypeTask},
{ID: "drd-ant", Title: "a dependent of root", Status: types.StatusOpen, IssueType: types.TypeTask},
}
for _, row := range rows {
if err := e.createIssue(ctx, row, "seed"); err != nil {
t.Fatalf("seed %s: %v", row.ID, err)
}
}
// root depends on drd-dep; drd-ant depends on root.
for _, edge := range []*types.Dependency{
{IssueID: "drd-root", DependsOnID: "drd-dep", Type: types.DepBlocks},
{IssueID: "drd-ant", DependsOnID: "drd-root", Type: types.DepBlocks},
} {
if err := e.addDependency(ctx, edge, "seed"); err != nil {
t.Fatalf("seed edge %s -> %s: %v", edge.IssueID, edge.DependsOnID, err)
}
}
// Two comments, by different authors, so the thread read is exercised for
// ORDERING and PER-FIELD carriage rather than for a single row that could pass
// a shallow projection by accident.
for _, c := range []struct{ author, text string }{
{"seed", "a comment the detail view carries"},
{"reviewer", "a second comment, so ordering and per-field parity are exercised"},
} {
if err := e.addComment(ctx, "drd-root", c.author, c.text); err != nil {
t.Fatalf("seed the comment %q: %v", c.text, err)
}
}
}
// TestServedDetailReadsAgreeWithTheReferenceStore is the parity pin for all five
// flips: each off-role read answers the same value over http that it answers
// locally.
func TestServedDetailReadsAgreeWithTheReferenceStore(t *testing.T) {
e := newServedEnv(t, "drd")
ctx := t.Context()
seedDetailReadsFixture(t, ctx, e)
t.Run("GetLabels", func(t *testing.T) {
want, err := e.reference.GetLabels(ctx, "drd-root")
if err != nil {
t.Fatalf("reference GetLabels: %v", err)
}
got, err := e.subject.GetLabels(ctx, "drd-root")
if err != nil {
t.Fatalf("http GetLabels: %v", err)
}
sort.Strings(want)
sort.Strings(got)
assertSameJSON(t, "GetLabels", want, got)
})
t.Run("GetDependenciesWithMetadata", func(t *testing.T) {
want, err := e.reference.GetDependenciesWithMetadata(ctx, "drd-root")
if err != nil {
t.Fatalf("reference GetDependenciesWithMetadata: %v", err)
}
got, err := e.subject.GetDependenciesWithMetadata(ctx, "drd-root")
if err != nil {
t.Fatalf("http GetDependenciesWithMetadata: %v", err)
}
if len(want) != 1 || want[0].Issue.ID != "drd-dep" {
t.Fatalf("the REFERENCE answered %+v, the fixture expects one edge onto drd-dep", want)
}
sortMetadata(want)
sortMetadata(got)
assertSameJSON(t, "GetDependenciesWithMetadata", want, got)
})
t.Run("GetDependentsWithMetadata is carried only when asked", func(t *testing.T) {
want, err := e.reference.GetDependentsWithMetadata(ctx, "drd-root")
if err != nil {
t.Fatalf("reference GetDependentsWithMetadata: %v", err)
}
got, err := e.subject.GetDependentsWithMetadata(ctx, "drd-root")
if err != nil {
t.Fatalf("http GetDependentsWithMetadata: %v", err)
}
if len(want) != 1 || want[0].Issue.ID != "drd-ant" {
t.Fatalf("the REFERENCE answered %+v, the fixture expects one dependent drd-ant", want)
}
// The dependents arm answers the shallow include_dependents shape, so the
// parity is over the fields that shape carries and `bd show` renders.
wantShallow := shallowMetadata(want)
gotShallow := shallowMetadata(got)
sortMetadata(wantShallow)
sortMetadata(gotShallow)
assertSameJSON(t, "GetDependentsWithMetadata", wantShallow, gotShallow)
})
t.Run("GetIssueComments carry the WHOLE comment, not a shallow projection", func(t *testing.T) {
want, err := e.reference.GetIssueComments(ctx, "drd-root")
if err != nil {
t.Fatalf("reference GetIssueComments: %v", err)
}
got, err := e.subject.GetIssueComments(ctx, "drd-root")
if err != nil {
t.Fatalf("http GetIssueComments: %v", err)
}
if len(want) != 2 {
t.Fatalf("the REFERENCE answered %d comments, the fixture seeded two", len(want))
}
sortComments(want)
sortComments(got)
// The comment thread rides include_comments as the FULL types.Comment —
// unlike the shallow dependents arm — so the http answer must carry every
// field a reply renders. A zeroed CreatedAt would sort a reply ahead of the
// root and blank its byline, and an empty Author/Text would gut the render.
// Assert the carriage BY FIELD before the whole-value parity, so a future
// shallow projection fails here by name rather than only through the opaque
// assertSameJSON diff. This is the pin the too-shallow prior test lacked.
if len(got) != len(want) {
t.Fatalf("http answered %d comments, want %d", len(got), len(want))
}
for i, c := range got {
if c.CreatedAt.IsZero() {
t.Errorf("http comment %d has a zero CreatedAt: the wire dropped it, which would break thread ordering", i)
}
if c.Author == "" || c.Text == "" {
t.Errorf("http comment %d dropped Author/Text: %+v", i, c)
}
}
assertSameJSON(t, "GetIssueComments", want, got)
})
t.Run("GetDependentsWithMetadata is SHALLOW over http (why bd show --thread/--refs/--children refuse)", func(t *testing.T) {
ref, err := e.reference.GetDependentsWithMetadata(ctx, "drd-root")
if err != nil {
t.Fatalf("reference GetDependentsWithMetadata: %v", err)
}
got, err := e.subject.GetDependentsWithMetadata(ctx, "drd-root")
if err != nil {
t.Fatalf("http GetDependentsWithMetadata: %v", err)
}
if len(ref) != 1 || len(got) != 1 {
t.Fatalf("fixture expects one dependent on each side, got ref=%d http=%d", len(ref), len(got))
}
// The reference reads the full row off the table; the wire answers the
// collectDependents shallow projection (be-4d36f2), which drops the
// free-form fields. CreatedAt is the reliable discriminator — the store
// stamps it on create, so the full row carries it and the shallow one
// zeroes it. This divergence is deliberate and is EXACTLY why the three
// reverse-view show modes refuse rather than render off it; pin it so a
// change that makes the wire look full also has to revisit those refusals.
if ref[0].Issue.CreatedAt.IsZero() {
t.Fatalf("the reference dependent has a zero CreatedAt, so this test cannot tell shallow from full")
}
if !got[0].Issue.CreatedAt.IsZero() {
t.Errorf("http dependent CreatedAt = %v, want zero: the wire is supposed to answer the shallow projection", got[0].Issue.CreatedAt)
}
// The shallow fields the show-text renderer consumes DO ride the wire.
if got[0].Issue.ID != "drd-ant" || got[0].Issue.Title != ref[0].Issue.Title || got[0].Issue.Status != ref[0].Issue.Status {
t.Errorf("the shallow fields diverged: ref=%+v http=%+v", ref[0].Issue, got[0].Issue)
}
})
t.Run("GetDependencyRecords", func(t *testing.T) {
want, err := e.reference.GetDependencyRecords(ctx, "drd-root")
if err != nil {
t.Fatalf("reference GetDependencyRecords: %v", err)
}
got, err := e.subject.GetDependencyRecords(ctx, "drd-root")
if err != nil {
t.Fatalf("http GetDependencyRecords: %v", err)
}
if len(want) != 1 || want[0].DependsOnID != "drd-dep" {
t.Fatalf("the REFERENCE answered %+v, the fixture expects one record onto drd-dep", want)
}
sortRecords(want)
sortRecords(got)
assertSameJSON(t, "GetDependencyRecords", want, got)
})
}
// TestServedDetailReadsMissParity is the (nil, nil) contract each flip carries:
// a nonexistent id answers empty with no error on BOTH sides, because the front
// doors read a nil result as "not found" and an error would print the
// transport's vocabulary in its place.
func TestServedDetailReadsMissParity(t *testing.T) {
e := newServedEnv(t, "drm")
ctx := t.Context()
const absent = "drm-nope"
labels, err := e.subject.GetLabels(ctx, absent)
if err != nil || labels != nil {
t.Errorf("GetLabels on a miss = (%v, %v), want (nil, nil)", labels, err)
}
deps, err := e.subject.GetDependenciesWithMetadata(ctx, absent)
if err != nil || deps != nil {
t.Errorf("GetDependenciesWithMetadata on a miss = (%v, %v), want (nil, nil)", deps, err)
}
dependents, err := e.subject.GetDependentsWithMetadata(ctx, absent)
if err != nil || dependents != nil {
t.Errorf("GetDependentsWithMetadata on a miss = (%v, %v), want (nil, nil)", dependents, err)
}
comments, err := e.subject.GetIssueComments(ctx, absent)
if err != nil || comments != nil {
t.Errorf("GetIssueComments on a miss = (%v, %v), want (nil, nil)", comments, err)
}
records, err := e.subject.GetDependencyRecords(ctx, absent)
if err != nil || records != nil {
t.Errorf("GetDependencyRecords on a miss = (%v, %v), want (nil, nil)", records, err)
}
// The reference answers the same way, so the parity is a shared contract
// rather than a client-side convention. ALL FIVE flipped reads are pinned on
// the reference, not just two: the "answer a miss with empty-and-no-error,
// never the transport's 404 vocabulary" contract has to hold for every read
// the http client mirrors, and spot-checking two of five left the other three
// free to drift.
if got, err := e.reference.GetLabels(ctx, absent); err != nil || got != nil {
t.Errorf("reference GetLabels on a miss = (%v, %v), want (nil, nil)", got, err)
}
if got, err := e.reference.GetDependenciesWithMetadata(ctx, absent); err != nil || got != nil {
t.Errorf("reference GetDependenciesWithMetadata on a miss = (%v, %v), want (nil, nil)", got, err)
}
if got, err := e.reference.GetDependentsWithMetadata(ctx, absent); err != nil || got != nil {
t.Errorf("reference GetDependentsWithMetadata on a miss = (%v, %v), want (nil, nil)", got, err)
}
if got, err := e.reference.GetIssueComments(ctx, absent); err != nil || got != nil {
t.Errorf("reference GetIssueComments on a miss = (%v, %v), want (nil, nil)", got, err)
}
if got, err := e.reference.GetDependencyRecords(ctx, absent); err != nil || got != nil {
t.Errorf("reference GetDependencyRecords on a miss = (%v, %v), want (nil, nil)", got, err)
}
}
// TestServedDependencyRecordsSurfaceUnresolvedRowsVerbatim is L17's dual run: the
// question the flip of GetDependencyRecords waited on.
//
// `bd dep remove`'s GH#5005 guard (exactDependencyTarget) reads the raw
// dependency rows and matches DependsOnID against the bare target the user typed,
// so a wrong-edge deletion is prevented only if an UNRESOLVED depends_on_id —
// one the database cannot resolve to any issue — is surfaced verbatim rather than
// dropped or normalized. This seeds exactly such a row (an external reference the
// workspace holds no issue for) beside a normal edge and compares the client's
// GetDependencyRecords against the reference's. If the unresolved row survives
// the wire whole, there is no divergence to ledger — which is the outcome this
// asserts and which retired L17.
func TestServedDependencyRecordsSurfaceUnresolvedRowsVerbatim(t *testing.T) {
e := newServedEnv(t, "drx")
ctx := t.Context()
for _, row := range []*types.Issue{
{ID: "drx-src", Title: "source", Status: types.StatusOpen, IssueType: types.TypeTask},
{ID: "drx-tgt", Title: "a real target", Status: types.StatusOpen, IssueType: types.TypeTask},
} {
if err := e.createIssue(ctx, row, "seed"); err != nil {
t.Fatalf("seed %s: %v", row.ID, err)
}
}
// A normal, resolvable edge, and an UNRESOLVED one whose target names no
// issue this workspace holds — the shape the guard exists to see. The
// external reference routes into depends_on_external and skips the target
// existence check, so it is stored verbatim exactly as the pre-GH#5005 bare
// slug was.
for _, edge := range []*types.Dependency{
{IssueID: "drx-src", DependsOnID: "drx-tgt", Type: types.DepBlocks},
{IssueID: "drx-src", DependsOnID: "external:ghost-slug", Type: types.DepRelated},
} {
if err := e.addDependency(ctx, edge, "seed"); err != nil {
t.Fatalf("seed edge %s -> %s: %v", edge.IssueID, edge.DependsOnID, err)
}
}
want, err := e.reference.GetDependencyRecords(ctx, "drx-src")
if err != nil {
t.Fatalf("reference GetDependencyRecords: %v", err)
}
got, err := e.subject.GetDependencyRecords(ctx, "drx-src")
if err != nil {
t.Fatalf("http GetDependencyRecords: %v", err)
}
// The reference is the oracle: assert the fixture really produced the
// unresolved row before comparing, so a fixture that stopped seeding it
// cannot make the parity pass vacuously.
var haveUnresolved bool
for _, r := range want {
if r.DependsOnID == "external:ghost-slug" {
haveUnresolved = true
}
}
if len(want) != 2 || !haveUnresolved {
t.Fatalf("the REFERENCE answered %+v, want two records including the unresolved external:ghost-slug", want)
}
sortRecords(want)
sortRecords(got)
assertSameJSON(t, "GetDependencyRecords over an unresolved target", want, got)
}

View file

@ -0,0 +1,495 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_dualrun_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"encoding/json"
"errors"
"slices"
"strconv"
"testing"
"time"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// Dual runs: the same store call, answered twice.
//
// Once by the reference store's own role, and once by the http client through
// the server that serves that very store. The two answers have to agree, and
// they are compared as the BYTES a caller receives rather than as a row count —
// `bd show --json` and `bd list --json` marshal these exact structs, so a field
// the wire round trip dropped or reshaped is a user-visible divergence even
// when the row set is right.
//
// The pair is the whole point. Every other test in this package asserts against
// values a human wrote down, which can only catch what that human thought to
// check; this one asserts against the local answer, which is the thing the
// backend is actually promising to reproduce.
func dualRunFixture(t *testing.T, name string) (*servedComposition, issueops.Reader, issueops.Reader, string) {
t.Helper()
ctx := t.Context()
c, remote := servedReader(t)
local, err := c.reference.IssueReader()
if err != nil {
t.Fatalf("reference IssueReader(): %v", err)
}
scope := servedIssuePrefix + "-dual-" + name
base := time.Now().UTC().Truncate(time.Second).Add(-3 * time.Hour)
for i, seed := range []struct {
tag string
priority int
}{{"a", 2}, {"b", 0}, {"c", 1}} {
id := scope + "-" + seed.tag
seedListIssue(t, ctx, c, id, scope, base.Add(time.Duration(i)*time.Minute), seed.priority)
}
// One edge and one comment, so the detail view and the cardinalities are
// nonzero on at least one row: a dual run over rows with nothing hanging off
// them cannot see a projection that drops a list.
if err := c.seedDependency(ctx, &types.Dependency{
IssueID: scope + "-a", DependsOnID: scope + "-b", Type: types.DepBlocks,
}, "seed"); err != nil {
t.Fatalf("seed the edge: %v", err)
}
if err := c.seedComment(ctx, scope+"-a", "seed", "a comment the detail view carries"); err != nil {
t.Fatalf("seed the comment: %v", err)
}
return c, local, remote, scope
}
func assertSameJSON(t *testing.T, what string, local, remote any) {
t.Helper()
wantBytes, err := json.Marshal(local)
if err != nil {
t.Fatalf("marshal the reference answer for %s: %v", what, err)
}
gotBytes, err := json.Marshal(remote)
if err != nil {
t.Fatalf("marshal the http answer for %s: %v", what, err)
}
if string(wantBytes) != string(gotBytes) {
t.Errorf("%s diverges\n http: %s\n local: %s", what, gotBytes, wantBytes)
}
}
// TestDualRunReaderAgreesWithTheReferenceStore is the smoke the composition
// exists for: Ready, List and Get answered by both, byte for byte.
func TestDualRunReaderAgreesWithTheReferenceStore(t *testing.T) {
ctx := t.Context()
_, local, remote, scope := dualRunFixture(t, "reader")
ready := issueops.ReadyRequest{Labels: []string{scope}, Sort: "priority", Limit: ptrTo(0)}
wantReady, err := local.Ready(ctx, ready)
if err != nil {
t.Fatalf("reference Ready: %v", err)
}
gotReady, err := remote.Ready(ctx, ready)
if err != nil {
t.Fatalf("http Ready: %v", err)
}
assertSameJSON(t, "Reader.Ready", wantReady, gotReady)
for _, sortBy := range []string{"", "created", "priority", "id"} {
list := issueops.ListRequest{Labels: []string{scope}, SortBy: sortBy, Limit: ptrTo(0)}
wantList, err := local.List(ctx, list)
if err != nil {
t.Fatalf("reference List (sort %q): %v", sortBy, err)
}
gotList, err := remote.List(ctx, list)
if err != nil {
t.Fatalf("http List (sort %q): %v", sortBy, err)
}
assertSameJSON(t, "Reader.List (sort "+sortBy+")", wantList, gotList)
}
for _, get := range []issueops.GetRequest{
{ID: scope + "-a"},
{ID: scope + "-a", IncludeDependents: true, IncludeComments: true},
{ID: scope + "-b", IncludeDependents: true},
} {
wantGet, err := local.Get(ctx, get)
if err != nil {
t.Fatalf("reference Get(%+v): %v", get, err)
}
gotGet, err := remote.Get(ctx, get)
if err != nil {
t.Fatalf("http Get(%+v): %v", get, err)
}
assertSameJSON(t, "Reader.Get", wantGet, gotGet)
}
}
// TestDualRunCloseHistoryAgreesWithTheReferenceStore is the write-side dual run:
// the same multi-item batch close, answered once by the reference store's own
// BatchCloser and once by the http client through the server that serves it.
//
// It is the atomicity claim spelled as a comparison. Serving a batch close on ONE
// issues:batchClose call rather than a loop of closeIssue exists to keep the
// request's one-transaction/at-most-one-history-entry contract, and only a dual
// run against the local answer can show the wire round trip did not quietly turn
// N closes into N entries. Two mirror batches are seeded so each door closes its
// own, and both the durable history footprint and the per-item outcome shapes
// have to agree.
func TestDualRunCloseHistoryAgreesWithTheReferenceStore(t *testing.T) {
ctx := t.Context()
c, _, _, scope := dualRunFixture(t, "closehist")
localCloser, err := c.reference.BatchCloser()
if err != nil {
t.Fatalf("reference BatchCloser(): %v", err)
}
remoteCloser, err := c.client.BatchCloser()
if err != nil {
t.Fatalf("http BatchCloser(): %v", err)
}
seed := func(prefix string, n int) []issueops.BatchCloseItem {
items := make([]issueops.BatchCloseItem, n)
for i := range items {
id := scope + "-" + prefix + "-" + strconv.Itoa(i)
issue := &types.Issue{
ID: id, Title: id, Status: types.StatusOpen,
IssueType: types.TypeTask, Labels: []string{scope},
}
if err := c.seedIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
items[i] = issueops.BatchCloseItem{IssueID: id, Reason: "done"}
}
return items
}
// Both mirror batches are seeded up front, so the only history the deltas
// below can see is the close each door makes.
localItems := seed("local", 3)
remoteItems := seed("remote", 3)
closeAndCount := func(name string, closer issueops.BatchCloser, items []issueops.BatchCloseItem) (issueops.CloseBatchResult, int) {
before, err := c.countHistory(ctx)
if err != nil {
t.Fatalf("%s history before: %v", name, err)
}
res, err := closer.CloseBatch(ctx, issueops.CloseBatchRequest{Actor: "closer", Items: items, Session: "s"})
if err != nil {
t.Fatalf("%s CloseBatch: %v", name, err)
}
after, err := c.countHistory(ctx)
if err != nil {
t.Fatalf("%s history after: %v", name, err)
}
return res, after - before
}
localRes, localDelta := closeAndCount("reference", localCloser, localItems)
remoteRes, remoteDelta := closeAndCount("http", remoteCloser, remoteItems)
// The load-bearing parity: the wire round trip records the same durable
// footprint the local batch does. A loop of closeIssue would show up here as
// three entries against the reference's one.
if remoteDelta != localDelta {
t.Errorf("history delta diverges: the http batch close wrote %d entries, the reference wrote %d for the same batch shape",
remoteDelta, localDelta)
}
// And the shape that parity is measured against: one transaction, at most one
// entry, for a batch where every item landed.
if localDelta != 1 {
t.Errorf("a %d-item reference batch recorded %d history entries, want exactly one (batchcloser.go's atomicity clause)",
len(localItems), localDelta)
}
assertBatchOutcomesAgree(t, localRes, remoteRes)
}
// assertBatchOutcomesAgree compares two batch results that closed mirror issue
// sets. The ids differ by construction, so the comparison is structural: the
// same count, the same landed/refused verdict per index, and the same Changed
// and OpenChildren — the fields a wire round trip could drop or reshape.
func assertBatchOutcomesAgree(t *testing.T, local, remote issueops.CloseBatchResult) {
t.Helper()
if len(local.Outcomes) != len(remote.Outcomes) {
t.Fatalf("outcome counts diverge: reference %d, http %d", len(local.Outcomes), len(remote.Outcomes))
}
for i := range local.Outcomes {
l, r := local.Outcomes[i], remote.Outcomes[i]
if (l.Err == nil) != (r.Err == nil) {
t.Errorf("outcome %d: reference err=%v, http err=%v — the landed/refused verdict diverges", i, l.Err, r.Err)
continue
}
if (l.Issue == nil) != (r.Issue == nil) {
t.Errorf("outcome %d: reference issue-present=%t, http issue-present=%t", i, l.Issue != nil, r.Issue != nil)
}
if l.Changed != r.Changed {
t.Errorf("outcome %d: reference Changed=%t, http Changed=%t", i, l.Changed, r.Changed)
}
if l.OpenChildren != r.OpenChildren {
t.Errorf("outcome %d: reference OpenChildren=%d, http OpenChildren=%d", i, l.OpenChildren, r.OpenChildren)
}
}
if (local.ClaimedNext == nil) != (remote.ClaimedNext == nil) {
t.Errorf("ClaimedNext presence diverges: reference=%t, http=%t", local.ClaimedNext != nil, remote.ClaimedNext != nil)
}
}
// TestDualRunQuerierAndReadyCounterAgreeWithTheReferenceStore is the same smoke
// for the other two roles this bead flipped.
func TestDualRunQuerierAndReadyCounterAgreeWithTheReferenceStore(t *testing.T) {
ctx := t.Context()
c, _, _, scope := dualRunFixture(t, "roles")
localQuerier, err := c.reference.Querier()
if err != nil {
t.Fatalf("reference Querier(): %v", err)
}
remoteQuerier, err := c.client.Querier()
if err != nil {
t.Fatalf("http Querier(): %v", err)
}
for _, req := range []issueops.QueryRequest{
{Expression: "type=task AND label=" + scope, Limit: ptrTo(0)},
{Expression: "(type=task OR type=bug) AND label=" + scope, SortBy: "priority", Limit: ptrTo(0)},
{Expression: "(type=task OR type=bug) AND label=" + scope, SortBy: "priority", Reverse: true, Limit: ptrTo(2)},
} {
want, err := localQuerier.Query(ctx, req)
if err != nil {
t.Fatalf("reference Query(%q): %v", req.Expression, err)
}
got, err := remoteQuerier.Query(ctx, req)
if err != nil {
t.Fatalf("http Query(%q): %v", req.Expression, err)
}
assertSameJSON(t, "Querier.Query("+req.Expression+")", want, got)
}
localCounter, err := c.reference.ReadyCounter()
if err != nil {
t.Fatalf("reference ReadyCounter(): %v", err)
}
remoteCounter, err := c.client.ReadyCounter()
if err != nil {
t.Fatalf("http ReadyCounter(): %v", err)
}
req := issueops.ReadyRequest{Labels: []string{scope}, Sort: "priority"}
want, err := localCounter.CountReady(ctx, req)
if err != nil {
t.Fatalf("reference CountReady: %v", err)
}
got, err := remoteCounter.CountReady(ctx, req)
if err != nil {
t.Fatalf("http CountReady: %v", err)
}
assertSameJSON(t, "ReadyCounter.CountReady", want, got)
}
// TestDualRunIDResolutionProbesAgreeWithTheReferenceStore covers D11's three
// store probes as ResolvePartialID makes them: the exact-ids fast path, the two
// prefix config reads, and the substring pass that has no wire operation.
func TestDualRunIDResolutionProbesAgreeWithTheReferenceStore(t *testing.T) {
ctx := t.Context()
c, _, _, scope := dualRunFixture(t, "resolve")
present, absent := scope+"-a", scope+"-never-seeded"
// The shapeless filter — neither an id set nor a parent — is the unbounded
// "everything" question, and it refuses rather than answering it.
if _, err := c.client.SearchIssues(ctx, "", types.IssueFilter{}); err == nil {
t.Error("a shapeless SearchIssues answered instead of refusing")
} else if !errors.Is(err, encode.ErrRefused) {
t.Errorf("a shapeless SearchIssues refused with %v, want the encoder's ledgered refusal", err)
}
for _, ids := range [][]string{{present}, {absent}, {present, absent}} {
filter := types.IssueFilter{IDs: ids}
want, err := c.reference.SearchIssues(ctx, "", filter)
if err != nil {
t.Fatalf("reference SearchIssues(%v): %v", ids, err)
}
got, err := c.client.SearchIssues(ctx, "", filter)
if err != nil {
t.Fatalf("http SearchIssues(%v): %v", ids, err)
}
if len(got) != len(want) {
t.Fatalf("SearchIssues(%v) returned %d rows, reference returned %d", ids, len(got), len(want))
}
for i := range want {
assertSameJSON(t, "SearchIssues row", want[i], got[i])
}
}
// The exact-hit fast path is the one ResolvePartialID reads as `err == nil &&
// len(issues) > 0`, and the exact MISS has to be an empty result with a NIL
// error or resolution stops where it should fall through.
miss, err := c.client.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{absent}})
if err != nil || len(miss) != 0 {
t.Errorf("SearchIssues on an exact miss = (%d rows, %v), want (0, nil): a 404 is the empty result the resolver expects", len(miss), err)
}
// The prefix probes.
if err := c.reference.SetConfig(ctx, "allowed_prefixes", "bd,http"); err != nil {
t.Fatalf("seed allowed_prefixes: %v", err)
}
// "no-such-setting" rather than "no-such-key": the server redacts by KEY
// SPELLING, and anything containing "key" is one of the spellings it treats
// as credential-bearing — which is ledger row L9 and is asserted on its own
// below, not by accident here.
for _, key := range []string{"issue_prefix", "allowed_prefixes", "no-such-setting"} {
want, err := c.reference.GetConfig(ctx, key)
if err != nil {
t.Fatalf("reference GetConfig(%q): %v", key, err)
}
got, err := c.client.GetConfig(ctx, key)
if err != nil {
t.Fatalf("http GetConfig(%q): %v", key, err)
}
if got != want {
t.Errorf("GetConfig(%q) = %q, reference answered %q", key, got, want)
}
}
// Ledger row L9: a credential-bearing key is absent WITH A REASON rather than
// absent as an empty string. The server decides redaction from the key alone,
// so this holds whether or not the workspace stores anything under it — and
// "" would be a dropped read dressed as an unset key.
if _, err := c.client.GetConfig(ctx, "some.api_key"); !errors.Is(err, ErrSettingRedacted) {
t.Errorf("GetConfig on a credential-bearing key = %v, want the withheld-with-reason refusal", err)
}
// The substring pass. It has no wire operation, and the refusal is D11's own
// text rather than a bare sentinel, because the input may be a partial id OR
// a full id that does not exist and the client cannot tell which.
_, err = c.client.SearchIssues(ctx, "partial", types.IssueFilter{})
var partial *PartialIDSearchError
if !errors.As(err, &partial) {
t.Fatalf("a substring SearchIssues = %v, want *PartialIDSearchError", err)
}
if partial.Input != "partial" || partial.ServerURL != c.baseURL {
t.Errorf("the refusal names input %q on server %q, want %q on %q", partial.Input, partial.ServerURL, "partial", c.baseURL)
}
if !errors.Is(err, ErrPartialIDSearch) {
t.Errorf("the refusal does not classify as ErrPartialIDSearch: %v", err)
}
}
// TestTheCompositionCatchesAWrongParameter is the RED evidence.
//
// Each arm rewrites one correctly encoded request into a subtly wrong one and
// asserts the composition NOTICES. Without them every green test in this file
// would be equally green against a client that dropped a filter, because a
// dropped filter answers with MORE rows and every assertion here is written
// against rows that exist.
func TestTheCompositionCatchesAWrongParameter(t *testing.T) {
ctx := t.Context()
c, _, remote, scope := dualRunFixture(t, "tamper")
honest, err := remote.List(ctx, issueops.ListRequest{Labels: []string{scope}, SortBy: "id", Limit: ptrTo(0)})
if err != nil {
t.Fatalf("the honest List: %v", err)
}
if len(honest.Items) != 3 {
t.Fatalf("the honest List returned %v, want the three rows this case seeded", pageIDs(honest))
}
t.Run("a dropped filter widens the answer", func(t *testing.T) {
// Its own row outside the scope, so the unfiltered answer is wider
// whatever else the shared composition holds. Without it the case
// leaned on rows earlier tests had seeded: run alone, or first in its
// shard, the scope's three rows were the whole workspace, and dropping
// the filter answered the same.
outside := &types.Issue{
ID: scope + "-outside", Title: "outside", Status: types.StatusOpen, Priority: 2,
IssueType: types.TypeTask, Labels: []string{scope + "-outside"}, CreatedAt: time.Now().UTC(),
}
if err := c.seedIssue(ctx, outside, "seed"); err != nil {
t.Fatalf("seed %s: %v", outside.ID, err)
}
dropped := c.tamperedClient(t, func(req *wire.Request) { req.Query.Del("label") })
reader, err := dropped.IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
page, err := reader.List(ctx, issueops.ListRequest{Labels: []string{scope}, SortBy: "id", Limit: ptrTo(0)})
if err != nil {
t.Fatalf("List with the label parameter dropped: %v", err)
}
if slices.Equal(pageIDs(page), pageIDs(honest)) {
t.Fatal("dropping the `label` parameter changed nothing: this composition cannot see a dropped filter, " +
"which is the one failure class no server-side gate can observe")
}
})
t.Run("a misspelled parameter is refused rather than ignored", func(t *testing.T) {
misspelled := c.tamperedClient(t, func(req *wire.Request) {
if req.Query.Has("include_comments") {
req.Query.Del("include_comments")
req.Query.Set("includeComments", "true")
}
})
reader, err := misspelled.IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
_, err = reader.Get(ctx, issueops.GetRequest{ID: scope + "-a", IncludeComments: true})
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("a misspelled parameter = %v, want the server's unknown_parameter refusal", err)
}
var problem *wire.ProblemError
if !errors.As(err, &problem) || problem.Reason != "unknown_parameter" {
t.Errorf("the refusal is %v, want reason \"unknown_parameter\" — the signal D7's case-3 text is built from", err)
}
})
t.Run("a wrong sort policy answers a different order", func(t *testing.T) {
// Its own rows, chosen so the two policies DISAGREE: the newer row is
// the higher priority, so `priority` leads with it and `oldest` leads
// with the other. Against rows where the orders coincide, a client that
// sent the wrong policy would be invisible — which is the whole reason
// the encoder sends a concrete policy rather than omitting an empty one.
sortScope := scope + "-sort"
now := time.Now().UTC()
urgent := &types.Issue{
ID: sortScope + "-urgent", Title: "urgent", Status: types.StatusOpen, Priority: 0,
IssueType: types.TypeTask, Labels: []string{sortScope}, CreatedAt: now.Add(-time.Hour),
}
ancient := &types.Issue{
ID: sortScope + "-ancient", Title: "ancient", Status: types.StatusOpen, Priority: 3,
IssueType: types.TypeTask, Labels: []string{sortScope}, CreatedAt: now.Add(-90 * 24 * time.Hour),
}
for _, issue := range []*types.Issue{urgent, ancient} {
if err := c.seedIssue(ctx, issue, "seed"); err != nil {
t.Fatalf("seed %s: %v", issue.ID, err)
}
}
req := issueops.ReadyRequest{Labels: []string{sortScope}, Sort: "priority", Limit: ptrTo(0)}
honestReady, err := remote.Ready(ctx, req)
if err != nil {
t.Fatalf("the honest Ready: %v", err)
}
if want := []string{urgent.ID, ancient.ID}; !slices.Equal(pageIDs(honestReady), want) {
t.Fatalf("the honest Ready --sort priority = %v, want %v", pageIDs(honestReady), want)
}
flipped := c.tamperedClient(t, func(req *wire.Request) {
if req.Query.Get("sort") == "priority" {
req.Query.Set("sort", "oldest")
}
})
reader, err := flipped.IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
tamperedReady, err := reader.Ready(ctx, req)
if err != nil {
t.Fatalf("Ready with the sort policy rewritten: %v", err)
}
if slices.Equal(pageIDs(honestReady), pageIDs(tamperedReady)) {
t.Fatalf("rewriting `sort` changed nothing (%v): the ready policy this client sends is unobservable here",
pageIDs(honestReady))
}
})
}

View file

@ -0,0 +1,255 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_graph_aux_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// The per-role contract wirings for the graph and aux read roles.
//
// Every case here is the SHARED contract, unmodified: the same function the
// embedded-Dolt and unit-of-work backends run, bound to a fixture whose subject
// is the http client and whose seed hooks come off the reference store the
// server serves. A case that passes has proved the behavior ACROSS THE WIRE
// rather than proving the client agrees with itself.
//
// NOTHING IS PARKED IN THIS FILE, and that is worth saying because an earlier
// revision parked thirteen cases. The two hooks they needed — Exec, for seeding
// a cycle past every gate, and CountHistory, for the writes-nothing clause — are
// raw SQL, and holding a SQL handle open alongside the live server deadlocks the
// engine. servedEnv opens one PER CALL and closes it, which is what the embedded
// backend's own frozen fixture kit does, so both hooks are real here and every
// case runs.
func TestServedCycleDetectorContract(t *testing.T) {
e := newServedEnv(t, "cyc")
detector, err := e.subject.CycleDetector()
if err != nil {
t.Fatalf("CycleDetector(): %v", err)
}
fixture := conformance.CycleDetectorFixture{
IssuePrefix: "cyc",
Detector: detector,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
Exec: e.exec,
CountHistory: e.countHistory,
}
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.CycleDetectorFixture)
}{
{"ReportsNoCycleForAnAcyclicSubgraph", conformance.RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph},
{"FindsADurableCycleRotatedToItsLowestID", conformance.RunCycleDetectorFindsADurableCycleRotatedToItsLowestID},
{"ReportsTheSameCyclesEveryRun", conformance.RunCycleDetectorReportsTheSameCyclesEveryRun},
{"MergesTheDurableAndEphemeralPlanes", conformance.RunCycleDetectorMergesTheDurableAndEphemeralPlanes},
{"FollowsOnlyBlockingEdges", conformance.RunCycleDetectorFollowsOnlyBlockingEdges},
{"ReportsAnHonestPartial", conformance.RunCycleDetectorReportsAnHonestPartial},
{"CountsAWhollyUndescribableCycle", conformance.RunCycleDetectorCountsAWhollyUndescribableCycle},
{"WritesNothing", conformance.RunCycleDetectorWritesNothing},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}
func TestServedTreeWalkerContract(t *testing.T) {
e := newServedEnv(t, "tre")
walker, err := e.subject.TreeWalker()
if err != nil {
t.Fatalf("TreeWalker(): %v", err)
}
fixture := conformance.TreeWalkerFixture{
IssuePrefix: "tre",
TreeWalker: walker,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
AddDependency: e.addDependency,
Exec: e.exec,
CountHistory: e.countHistory,
}
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.TreeWalkerFixture)
}{
{"WalksTheDependenciesOfARoot", conformance.RunTreeWalkerWalksTheDependenciesOfARoot},
{"WalksDependentsWhenAskedUp", conformance.RunTreeWalkerWalksDependentsWhenAskedUp},
{"BoundsTheDescentAtMaxDepth", conformance.RunTreeWalkerBoundsTheDescentAtMaxDepth},
{"TerminatesOnACycle", conformance.RunTreeWalkerTerminatesOnACycle},
{"RendersASharedSubtreeOnce", conformance.RunTreeWalkerRendersASharedSubtreeOnce},
{"MergesTheDurableAndEphemeralPlanes", conformance.RunTreeWalkerMergesTheDurableAndEphemeralPlanes},
{"FollowsEveryTypeButRelatesTo", conformance.RunTreeWalkerFollowsEveryTypeButRelatesTo},
{"PrunesEachHalfOfABothWalk", conformance.RunTreeWalkerPrunesEachHalfOfABothWalk},
{"AnswersBothDirectionsWithTheRootOnce", conformance.RunTreeWalkerAnswersBothDirectionsWithTheRootOnce},
{"PrunesByStatusKeepingAncestors", conformance.RunTreeWalkerPrunesByStatusKeepingAncestors},
{"PrunesEverythingWhenNothingMatches", conformance.RunTreeWalkerPrunesEverythingWhenNothingMatches},
{"AnswersARootWithNoEdges", conformance.RunTreeWalkerAnswersARootWithNoEdges},
{"RefusesAnAbsentRoot", conformance.RunTreeWalkerRefusesAnAbsentRoot},
{"ResolvesTheRootIDExactly", conformance.RunTreeWalkerResolvesTheRootIDExactly},
{"CrossesPlanesFromAWispRootAndUpward", conformance.RunTreeWalkerCrossesPlanesFromAWispRootAndUpward},
{"RefusesAnInvalidRequest", conformance.RunTreeWalkerRefusesAnInvalidRequest},
{"RefusesAWalkOverTheRowCap", conformance.RunTreeWalkerRefusesAWalkOverTheRowCap},
{"WritesNothing", conformance.RunTreeWalkerWritesNothing},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}
func TestServedEdgeReaderContract(t *testing.T) {
e := newServedEnv(t, "edg")
reader, err := e.subject.EdgeReader()
if err != nil {
t.Fatalf("EdgeReader(): %v", err)
}
fixture := conformance.EdgeReaderFixture{
IssuePrefix: "edg",
EdgeReader: reader,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
AddDependency: e.addDependency,
CountHistory: e.countHistory,
}
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.EdgeReaderFixture)
}{
{"AnswersOnePerAnchorInRequestOrder", conformance.RunEdgeReaderAnswersOnePerAnchorInRequestOrder},
{"ReportsAMissingAnchorRatherThanFailing", conformance.RunEdgeReaderReportsAMissingAnchorRatherThanFailing},
{"DistinguishesNoEdgesFromNoAnchor", conformance.RunEdgeReaderDistinguishesNoEdgesFromNoAnchor},
{"ReturnsTargetsVerbatim", conformance.RunEdgeReaderReturnsTargetsVerbatim},
{"CollapsesRepeatedAnchors", conformance.RunEdgeReaderCollapsesRepeatedAnchors},
{"OrdersEdgesByTarget", conformance.RunEdgeReaderOrdersEdgesByTarget},
{"FiltersEdgesNotAnchors", conformance.RunEdgeReaderFiltersEdgesNotAnchors},
{"ReadsBothPlanes", conformance.RunEdgeReaderReadsBothPlanes},
{"ResolvesExactIDsOnly", conformance.RunEdgeReaderResolvesExactIDsOnly},
{"AnswersAnEmptyRequest", conformance.RunEdgeReaderAnswersAnEmptyRequest},
{"RefusesAnEmptyID", conformance.RunEdgeReaderRefusesAnEmptyID},
{"RefusesAnUnusableType", conformance.RunEdgeReaderRefusesAnUnusableType},
{"LeavesTheRequestAlone", conformance.RunEdgeReaderLeavesTheRequestAlone},
{"WritesNothing", conformance.RunEdgeReaderWritesNothing},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}
func TestServedBlockingAnnotatorContract(t *testing.T) {
e := newServedEnv(t, "blk")
annotator, err := e.subject.BlockingAnnotator()
if err != nil {
t.Fatalf("BlockingAnnotator(): %v", err)
}
fixture := conformance.BlockingAnnotatorFixture{
IssuePrefix: "blk",
Annotator: annotator,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
AddDependency: e.addDependency,
CountHistory: e.countHistory,
}
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.BlockingAnnotatorFixture)
}{
{"AnswersOnePerIDInRequestOrder", conformance.RunBlockingAnnotatorAnswersOnePerIDInRequestOrder},
{"CollapsesRepeatedIDs", conformance.RunBlockingAnnotatorCollapsesRepeatedIDs},
{"ReportsOpenBlockersOnly", conformance.RunBlockingAnnotatorReportsOpenBlockersOnly},
{"ReportsTheInboundDirection", conformance.RunBlockingAnnotatorReportsTheInboundDirection},
{"SeparatesParentFromBlockers", conformance.RunBlockingAnnotatorSeparatesParentFromBlockers},
{"DropsAClosedParent", conformance.RunBlockingAnnotatorDropsAClosedParent},
{"OrdersAndCollapsesEachList", conformance.RunBlockingAnnotatorOrdersAndCollapsesEachList},
{"CountsAnUnresolvableBlockerAsOpen", conformance.RunBlockingAnnotatorCountsAnUnresolvableBlockerAsOpen},
{"ReadsBothPlanes", conformance.RunBlockingAnnotatorReadsBothPlanes},
{"IgnoresNonBlockingEdgeTypes", conformance.RunBlockingAnnotatorIgnoresNonBlockingEdgeTypes},
{"AnnotatesAnAbsentIDBare", conformance.RunBlockingAnnotatorAnnotatesAnAbsentIDBare},
{"ResolvesExactIDsOnly", conformance.RunBlockingAnnotatorResolvesExactIDsOnly},
{"ReportsAtMostOneParent", conformance.RunBlockingAnnotatorReportsAtMostOneParent},
{"AnswersAnEmptyRequest", conformance.RunBlockingAnnotatorAnswersAnEmptyRequest},
{"RefusesAnEmptyID", conformance.RunBlockingAnnotatorRefusesAnEmptyID},
{"LeavesTheRequestAlone", conformance.RunBlockingAnnotatorLeavesTheRequestAlone},
{"WritesNothing", conformance.RunBlockingAnnotatorWritesNothing},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}
// TestServedStatsReporterContract runs its cases SEQUENTIALLY against one store,
// which the contract requires: the workspace-wide cases assert before/after
// DELTAS rather than absolutes, so a concurrent writer would make them read each
// other's rows.
func TestServedStatsReporterContract(t *testing.T) {
e := newServedEnv(t, "sts")
reporter, err := e.subject.StatsReporter()
if err != nil {
t.Fatalf("StatsReporter(): %v", err)
}
fixture := conformance.StatsReporterFixture{
IssuePrefix: "sts",
StatsReporter: reporter,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
AddDependency: e.addDependency,
CountHistory: e.countHistory,
}
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.StatsReporterFixture)
}{
{"CountsEveryDurableRowByStatus", conformance.RunStatsReporterCountsEveryDurableRowByStatus},
{"ExcludesTheWispTier", conformance.RunStatsReporterExcludesTheWispTier},
{"BreaksOutTheRowsTheDefaultListingSuppresses", conformance.RunStatsReporterBreaksOutTheRowsTheDefaultListingSuppresses},
{"BreaksOutAGateThatIsAlsoATemplate", conformance.RunStatsReporterBreaksOutAGateThatIsAlsoATemplate},
{"AStatusOutsideTheTalliesIsCountedOnlyInTotal", conformance.RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal},
{"BlockedCountsTheGraphNotTheStatus", conformance.RunStatsReporterBlockedCountsTheGraphNotTheStatus},
{"BlockedExcludesByStatusNotByThePinnedFlag", conformance.RunStatsReporterBlockedExcludesByStatusNotByThePinnedFlag},
{"BlockedCountsEveryUnfinishedStatusNotJustOpen", conformance.RunStatsReporterBlockedCountsEveryUnfinishedStatusNotJustOpen},
{"ReadyIsOpenMinusBlocked", conformance.RunStatsReporterReadyIsOpenMinusBlocked},
{"SkipBlockedPairsTheTwoPointers", conformance.RunStatsReporterSkipBlockedPairsTheTwoPointers},
{"ExtendedFieldsAreAlwaysZero", conformance.RunStatsReporterExtendedFieldsAreAlwaysZero},
{"WritesNothing", conformance.RunStatsReporterWritesNothing},
{"AssigneeStatsScopesToOneActor", conformance.RunStatsReporterAssigneeStatsScopesToOneActor},
{"AssigneeBlockedCountsTheStatusNotTheGraph", conformance.RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph},
{"AssigneeStatsMergesTheWispTier", conformance.RunStatsReporterAssigneeStatsMergesTheWispTier},
{"AssigneeStatsPopulatesBothPointers", conformance.RunStatsReporterAssigneeStatsPopulatesBothPointers},
{"AssigneeStatsBreaksOutTheSuppressedRows", conformance.RunStatsReporterAssigneeStatsBreaksOutTheSuppressedRows},
{"AssigneeStatsRefusesAnEmptyAssignee", conformance.RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}
// THE WorkspaceConfig CONTRACT IS WIRED, and this block used to explain why it
// could not be. It is kept rather than deleted because the reason it gave was
// right, and because what retired it is not the reason it predicted.
//
// EVERY CASE IN THAT SUITE REACHES THE ROLE THROUGH SetSetting OR UnsetSetting —
// including the ones whose SUBJECT is a read, which seed the key they then read
// back, and including RefusesAnEmptyKey, which asserts ErrValidation from
// SetSetting("") itself. While settings were read-only over v0 (D8 row 11), a
// backend that cannot write could not adopt a suite whose every case writes, and
// the role was proved instead by two hand-written tests seeded PAST it plus one
// that pinned the two verbs as refusals naming themselves.
//
// The retirement path this block named was upstream's — "an accessor-only
// contract whose read cases seed out of band" — and that is NOT what happened.
// Upstream #5596 published both write operations and client wave ga-jpywb dials
// them, so the suite became adoptable WHOLE with no change to a single case: all
// twenty-one run in served_config_test.go, and the three hand-written stand-ins
// are gone, each having asserted a strict subset of what replaced it.
//
// THE LESSON WORTH KEEPING is which of the two retirement paths arrived. A
// contract this leg cannot adopt is a statement about the WIRE far more often
// than about the contract's shape, and rewriting a suite to accommodate a
// partial backend would have bought nothing that two operations did not buy
// outright. See D8 row 16's Lifecycle.Update ask, which is still open and is
// still the other kind.

View file

@ -0,0 +1,68 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_graph_counter_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// The GraphCounter contract, run through the http client against a real bd
// serve.
//
// NOTHING IS PARKED HERE. Every member of the request is a published parameter
// and both members of the answer are required ones, so the two facts the role
// is written around cross intact: the count SPANS BOTH DEPENDENCY PLANES — a
// durable anchor's inbound count includes the wisps that depend on it, which is
// one number the server sums over two tables and this client never recomputes —
// and Missing is a SENTINEL rather than a zero, which is the whole of the
// difference between a typo and an issue with no edges.
//
// The status filter's direction=out refusal is here too, and it is the one
// refusal on this role that a client could have quietly softened: the parameter
// is legal on the operation and illegal in one direction, so a client that
// simply forwarded it would earn a 400 with a param name and pass this case for
// the wrong reason. It does not forward it: the role's own validator refuses
// first, in the role's own order.
func TestServedGraphCounterContract(t *testing.T) {
e := newServedEnv(t, "gcn")
counter, err := e.subject.GraphCounter()
if err != nil {
t.Fatalf("GraphCounter(): %v", err)
}
fixture := conformance.GraphCounterFixture{
IssuePrefix: "gcn",
GraphCounter: counter,
CreateIssue: e.createIssue,
CreateWisp: e.createWisp,
AddDependency: e.addDependency,
CountHistory: e.countHistory,
}
for _, tc := range []struct {
name string
run func(*testing.T, context.Context, conformance.GraphCounterFixture)
}{
{"CountsOutboundEdges", conformance.RunGraphCounterCountsOutboundEdges},
{"CountsInboundEdges", conformance.RunGraphCounterCountsInboundEdges},
{"AnswersOnePerAnchorInRequestOrder", conformance.RunGraphCounterAnswersOnePerAnchorInRequestOrder},
{"DistinguishesNoEdgesFromNoAnchor", conformance.RunGraphCounterDistinguishesNoEdgesFromNoAnchor},
{"CollapsesRepeatedAnchors", conformance.RunGraphCounterCollapsesRepeatedAnchors},
{"FiltersEdgesNotAnchors", conformance.RunGraphCounterFiltersEdgesNotAnchors},
{"NarrowsInboundByDependentStatus", conformance.RunGraphCounterNarrowsInboundByDependentStatus},
{"CountsAcrossBothPlanes", conformance.RunGraphCounterCountsAcrossBothPlanes},
{"NarrowsAWispDependentByStatus", conformance.RunGraphCounterNarrowsAWispDependentByStatus},
{"ResolvesIDsExactly", conformance.RunGraphCounterResolvesIDsExactly},
{"AnswersAnEmptyRequest", conformance.RunGraphCounterAnswersAnEmptyRequest},
{"RefusesAnUnusableRequest", conformance.RunGraphCounterRefusesAnUnusableRequest},
{"LeavesTheRequestAlone", conformance.RunGraphCounterLeavesTheRequestAlone},
{"WritesNothing", conformance.RunGraphCounterWritesNothing},
} {
t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) })
}
}

View file

@ -0,0 +1,540 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_harness_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"io"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/httpapi"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The SERVED-SURFACE conformance harness: client → in-process bd serve →
// reference store.
//
// This is the composition design D8's lane row specifies, and it is what a
// per-role contract binds against. The binding rule is the one composition_test
// states and checkFixtureBinding enforces: SEEDING NEVER GOES THROUGH THE
// CLIENT. Every fixture below takes its seed and post-state hooks from the
// reference store the server serves, and binds only the ROLE under test to the
// http client. A fixture that seeded through the client would prove that the
// client agrees with itself.
//
// Bare RunAll is deliberately absent. Its Factory contract wants a write-ready
// store and its cases seed through raw CreateIssue and SetConfig, both of which
// this backend refuses — so it would prove nothing about a partial backend
// except that it is partial.
//
// One environment per case. Standing up an embedded engine and an HTTP listener
// per case costs about a second; sharing one across cases would make an id
// collision between two contracts a debugging session instead of a rename, and
// the contracts namespace their ids by prefix precisely so they can be run this
// way.
// servedEnv is one client-server-store triple and the hooks a fixture needs.
type servedEnv struct {
reference *embeddeddolt.EmbeddedDoltStore
subject *Store
dataDir string
database string
prefix string
}
const servedDatabase = "httpconf"
// servedProjectID is the identity the in-process server publishes in its
// handshake. Most fixtures leave the client's ExpectProjectID empty and never
// consult it, but the wrong-server cases (served_wrong_server_test.go) pin the
// client against this value — one matching it, one not — to drive the
// project-identity gate (ga-b8ddd.11).
const servedProjectID = "proj-httpconf"
// This file is the served tier's cgo half; see TestServedTierIsLinkedWhenRequired.
func init() { servedTierLinked = true }
// skipUnlessEmbeddedDolt gates the tier on the engine it needs.
//
// It is a skip rather than a failure for a DEVELOPER, for the reason the
// embedded backend's own conformance wiring skips: the engine is a cgo-linked
// build-time capability, not a service the environment forgot to start.
//
// It is a FAILURE for the lane that stands the tier up. BEADS_HTTP_TEST_REQUIRED=1
// is how scripts/conformance.sh and the embedded lane's
// //internal/httpclient:httpclient_served_test say "this tier is the required
// home of the served surface" — the same shape as BEADS_PG_TEST_REQUIRED for the
// live PostgreSQL tier and BEADS_TEST_EMBEDDED_DOLT for the oracle. Without it,
// a dropped env key in the lane, or a rename of the variable, would restore
// exactly the state this wiring exists to end: hundreds of served cases
// skipping themselves while the gate reports success.
//
// Two checks sit outside this one. TestServedTierIsLinkedWhenRequired fails a
// required run built without cgo, which compiles this file out. And a tier that
// stopped being invoked at all, which no in-process check can see, is a
// failure of scripts' TestBazelRetiredLanesCannotBeNarrowed, which pins
// httpclient_served_test's env to both variables.
func skipUnlessEmbeddedDolt(t *testing.T) {
t.Helper()
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") == "1" {
return
}
if os.Getenv("BEADS_HTTP_TEST_REQUIRED") == "1" {
t.Fatal("BEADS_HTTP_TEST_REQUIRED=1 but BEADS_TEST_EMBEDDED_DOLT is not 1; " +
"the served-surface conformance tier is not enforced")
}
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run the served-surface conformance tier")
}
// newServedEnv boots a reference store, serves its roles over an in-process
// listener, and points an http client store at the bound address. The client
// pins no expected identity, so the project-identity gate is inert — which is
// what every role contract below wants, since none of them is about identity.
//
// The optional config tweaks run against the served Config after the roles are
// bound and before Listen, so a case can slow the watch cadence or serve a
// journal-OFF workspace without a second harness. They are variadic so the many
// callers that need none stay unchanged.
func newServedEnv(t *testing.T, prefix string, opts ...func(*httpapi.Config)) *servedEnv {
t.Helper()
return newServedEnvExpecting(t, prefix, "", opts...)
}
// newServedEnvExpecting is newServedEnv with the client's ExpectProjectID
// pinned. The wrong-server cases use it to arm the identity gate the plain
// harness deliberately leaves off (ga-b8ddd.11).
func newServedEnvExpecting(t *testing.T, prefix, expectID string, opts ...func(*httpapi.Config)) *servedEnv {
t.Helper()
skipUnlessEmbeddedDolt(t)
beadsDir := t.TempDir()
ctx := t.Context()
reference, err := embeddeddolt.Open(ctx, beadsDir, servedDatabase, "main")
if err != nil {
t.Fatalf("open the reference store: %v", err)
}
t.Cleanup(func() { _ = reference.Close() })
if err := reference.SetConfig(ctx, "issue_prefix", prefix); err != nil {
t.Fatalf("set the issue prefix: %v", err)
}
cfg := serveConfig(t, reference)
for _, opt := range opts {
opt(&cfg)
}
srv, err := httpapi.Listen(cfg)
if err != nil {
t.Fatalf("bind the in-process server: %v", err)
}
serveCtx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { defer close(done); _ = srv.Serve(serveCtx) }()
t.Cleanup(func() {
cancel()
select {
case <-done:
case <-time.After(30 * time.Second):
t.Error("the in-process server did not shut down")
}
})
base, err := url.Parse("http://" + srv.Addr())
if err != nil {
t.Fatalf("parse the bound address: %v", err)
}
client, err := wire.New(base, nil, wire.Options{ExpectProjectID: expectID})
if err != nil {
t.Fatalf("build the client: %v", err)
}
// ExpectProjectID is the identity pin `bd connect` records and D6 checks.
// The plain harness leaves it empty so the gate is inert for the role
// contracts; the wrong-server cases pass a value to arm it.
subject := New(Target{BaseURL: base}, client, nil)
return &servedEnv{
reference: reference,
subject: subject,
// The SQL handle addresses the engine's data directory, which the
// store creates one level under the workspace. Passing beadsDir here
// finds no database at all.
dataDir: filepath.Join(beadsDir, "embeddeddolt"),
database: servedDatabase,
prefix: prefix,
}
}
// serveConfig binds every served role to the reference store.
//
// Every one of them is taken through the store's own capability accessor rather
// than a constructor: a store that stopped offering a role is the regression
// this catches, and a constructor call would hide it. The server refuses a
// partial role set outright, which is why there is no shortcut here.
func serveConfig(t *testing.T, s storage.DoltStorage) httpapi.Config {
t.Helper()
cfg := httpapi.Config{
Addr: "127.0.0.1:0",
Stdout: io.Discard,
Stderr: io.Discard,
// The handshake's published identity. Role contracts never read it, but
// the wrong-server cases compare the client's ExpectProjectID against it.
Workspace: domain.ContextInfo{ProjectID: servedProjectID, Database: servedDatabase},
}
var err error
fail := func(name string) {
t.Helper()
if err != nil {
t.Fatalf("%s(): %v", name, err)
}
}
cfg.Reader, err = s.IssueReader()
fail("IssueReader")
cfg.Claimer, err = s.IssueClaimer()
fail("IssueClaimer")
cfg.ReadyClaimer, err = s.ReadyClaimer()
fail("ReadyClaimer")
cfg.Releaser, err = s.Releaser()
fail("Releaser")
cfg.Lifecycle, err = s.IssueLifecycle()
fail("IssueLifecycle")
cfg.Settings, err = s.WorkspaceConfig()
fail("WorkspaceConfig")
cfg.Stats, err = s.StatsReporter()
fail("StatsReporter")
cfg.CycleDetector, err = s.CycleDetector()
fail("CycleDetector")
cfg.EdgeReader, err = s.EdgeReader()
fail("EdgeReader")
cfg.GraphCounter, err = s.GraphCounter()
fail("GraphCounter")
cfg.Relations, err = s.IssueRelations()
fail("IssueRelations")
cfg.Commenter, err = s.Commenter()
fail("Commenter")
cfg.BlockingAnnotator, err = s.BlockingAnnotator()
fail("BlockingAnnotator")
cfg.TreeWalker, err = s.TreeWalker()
fail("TreeWalker")
cfg.ReadyCounter, err = s.ReadyCounter()
fail("ReadyCounter")
cfg.Counter, err = s.Counter()
fail("Counter")
cfg.Querier, err = s.Querier()
fail("Querier")
cfg.Sweeper, err = s.Sweeper()
fail("Sweeper")
cfg.Deleter, err = s.Deleter()
fail("Deleter")
cfg.BatchCreator, err = s.BatchCreator()
fail("BatchCreator")
cfg.BatchCloser, err = s.BatchCloser()
fail("BatchCloser")
cfg.DependencyEditor, err = s.DependencyEditor()
fail("DependencyEditor")
cfg.MetadataCAS, err = s.MetadataCAS()
fail("MetadataCAS")
cfg.BatchApplier, err = s.BatchApplier()
fail("BatchApplier")
cfg.Memories, err = s.Memories()
fail("Memories")
cfg.BatchGetter, err = s.BatchGetter()
fail("BatchGetter")
// THE JOURNAL IS NOT AN ACCESSOR, alone among the roles above: it is reached
// by TYPE ASSERTION, because it is not on storage.DoltStorage and a backend
// is free not to implement it at all. This is verbatim the expression
// cmd/bd's serveJournalCursor makes.
//
// EventsJournalEnabled is hard-set rather than resolved, and it has to be:
// the flag is read per REQUEST off this config, the store's own
// SetEventsJournalEnabled is what decides whether anything is RECORDED, and
// the Journal fixture flips that after Listen has already bound. A config
// resolved from the workspace would leave every read a 409. Serving with it
// on costs the other contracts nothing — no rows exist until a case asks for
// them — and Listen refuses to bind an enabled workspace with no reader, so
// the two lines travel together.
cursor, ok := any(s).(storage.EventsJournalCursor)
if !ok {
t.Fatalf("%T does not implement storage.EventsJournalCursor; the served journal has nothing to read", s)
}
cfg.EventsJournal = cursor
cfg.EventsJournalEnabled = true
return cfg
}
// The reference store's roles, seeded through the store rather than the client.
func (e *servedEnv) createIssue(ctx context.Context, issue *types.Issue, actor string) error {
return e.reference.CreateIssue(ctx, issue, actor)
}
// createWisp seeds into the EPHEMERAL plane. The flag is set here rather than by
// the caller because the contracts hand the same issue value to both hooks and
// expect the hook to decide the plane.
func (e *servedEnv) createWisp(ctx context.Context, issue *types.Issue, actor string) error {
// A NoHistory bead is routed into the wisps plane by the CREATE verb
// itself, and upstream (#5191) refuses ephemeral AND no_history on one
// row — so the flag is forced only for the plain ephemeral shape, the
// same way the Dolt role kit's CreateWisp leaves the routing to the verb.
if !issue.NoHistory {
issue.Ephemeral = true
}
return e.reference.CreateIssue(ctx, issue, actor)
}
func (e *servedEnv) addDependency(ctx context.Context, dep *types.Dependency, actor string) error {
return e.reference.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{EmitEvent: true})
}
// addComment seeds through the reference store's Commenter ROLE, which resolves
// the plane itself — so a case can cite a sweep candidate from a WISP's comment
// without knowing how the backend reaches wisp_comments.
//
// IT STAYS ON THE REFERENCE SIDE NOW THAT THE CLIENT HAS A COMMENTER of its own
// (client wave ga-f352s), and the reason is the harness rule rather than the old
// absence: SEEDING NEVER GOES THROUGH THE CLIENT. A fixture that seeded its
// preconditions through the subject would prove the client agrees with itself,
// which is exactly what the Commenter contract must not be able to do.
func (e *servedEnv) addComment(ctx context.Context, issueID, author, text string) error {
commenter, err := e.reference.Commenter()
if err != nil {
return err
}
_, err = commenter.AddComment(ctx, issueops.AddCommentRequest{IssueID: issueID, Author: author, Text: text})
return err
}
// seedCommentAt appends a comment to an existing thread at a chosen created_at.
//
// It is the IMPORT shape and it has to be: the served operation deliberately
// publishes no created_at member — a stored time the caller supplied makes the
// row disagree with the entry that records it — so the client's own Commenter
// cannot place a comment anywhere but now. That is what makes this the one hook
// here with no client-side equivalent even in principle, and it is why the
// timing clauses of the Commenter contract are observable at all: the seeded
// comment sits an hour from the clock, so the right answer and the wrong one are
// an hour apart rather than a runner's margin.
func (e *servedEnv) seedCommentAt(ctx context.Context, issueID, author, text string, at time.Time) error {
_, err := e.reference.ImportIssueComment(ctx, issueID, author, text, at)
return err
}
func (e *servedEnv) setConfig(ctx context.Context, key, value string) error {
return e.reference.SetConfig(ctx, key, value)
}
// listEvents answers ONE issue's whole event journal, which is how the update
// cases end the clause a row read cannot: RowVersion says the row did not move,
// and nothing on the row says an event was not appended beside it.
//
// The limit is 0 — GetEvents reads that as "no limit" — because every case takes
// a DELTA around the operation under test, and a truncated journal would make
// "the refusal wrote nothing" unfalsifiable.
//
// It reads the REFERENCE store like every other out-of-band hook here, and the
// reason is now the FIRST of the two this comment used to give rather than the
// second. The v0 journal is keyed on `since` and `limit` rather than on an
// issue, so asking the subject would mean paging a whole feed and projecting one
// id out of it — which is a different question from the one these cases ask.
// The second reason is gone: client wave ga-jpywb wired journalops.Journal
// (journal.go), so the client CAN read a journal, and served_journal_test.go is
// where that is proved.
func (e *servedEnv) listEvents(ctx context.Context, issueID string) ([]*types.Event, error) {
return e.reference.GetEvents(ctx, issueID, 0)
}
// listDependencies answers one issue's outgoing edges as records, for the
// reparent cases: the clause under test is that a set ParentID "atomically
// replaces ALL parents with exactly that target", which needs the whole SET
// rather than a lookup of the new parent.
//
// It reads through the reference store's dependency-with-metadata surface,
// which resolves each target to the issue behind it, so an edge onto an id no
// plane holds is dropped. The cases assert a parent set whose every member is a
// row they seeded, so that resolution is invisible to them.
func (e *servedEnv) listDependencies(ctx context.Context, issueID string) ([]*types.Dependency, error) {
records, err := e.reference.GetDependenciesWithMetadata(ctx, issueID)
if err != nil {
return nil, err
}
edges := make([]*types.Dependency, 0, len(records))
for _, record := range records {
if record == nil {
continue
}
edges = append(edges, &types.Dependency{
IssueID: issueID,
DependsOnID: record.ID,
Type: record.DependencyType,
})
}
return edges, nil
}
func (e *servedEnv) getIssue(ctx context.Context, id string) (*types.Issue, error) {
return e.reference.GetIssue(ctx, id)
}
// servedJournalMutations is the one-hook-per-op kit both the paged Journal and
// the pushed Watcher contracts drive, in ONE place so the two cannot disagree
// about how a mutation is made.
//
// Every hook drives the REFERENCE store, which is the harness rule and not a
// shortcut around a refusing client: two of the seven have no client-side
// spelling at all (a raw delete and a raw dependency remove are on the
// unsupported allowlist), and the question both contracts ask is whether the
// client can READ — page or stream — the journal a server wrote.
func servedJournalMutations(reference *embeddeddolt.EmbeddedDoltStore) conformance.JournalMutations {
return conformance.JournalMutations{
Create: func(ctx context.Context, id string) error {
return reference.CreateIssue(ctx, &types.Issue{
ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen,
}, "actor")
},
Update: func(ctx context.Context, id string) error {
return reference.UpdateIssue(ctx, id, map[string]any{"title": "renamed " + id}, "actor")
},
Close: func(ctx context.Context, id string) error {
return reference.CloseIssue(ctx, id, "done", "actor", "")
},
Delete: func(ctx context.Context, id string) error {
return reference.DeleteIssue(ctx, id)
},
AddDependency: func(ctx context.Context, from, to string) error {
return reference.AddDependency(ctx, &types.Dependency{
IssueID: from, DependsOnID: to, Type: types.DepBlocks,
}, "actor")
},
RemoveDependency: func(ctx context.Context, from, to string) error {
return reference.RemoveDependency(ctx, from, to, "actor")
},
Comment: func(ctx context.Context, id, text string) error {
return reference.AddComment(ctx, id, "actor", text)
},
}
}
// wispExists probes the EPHEMERAL plane alone, which is the one question a
// both-plane read cannot answer: getIssue resolves the durable row first, so a
// stray wisp written under an occupied durable id is invisible to it.
//
// The create contracts need it and nothing else does yet. It is a RAW read of
// the reference store's own table, like every other out-of-band hook here — the
// client publishes no ephemeral-plane listing at all (ListWisps is on the
// unsupported allowlist), so asking through the subject would be asking the
// thing under test.
func (e *servedEnv) wispExists(ctx context.Context, id string) (bool, error) {
var rows int
if err := e.queryScalar(ctx, "SELECT COUNT(*) FROM wisps WHERE id = ?", []any{id}, &rows); err != nil {
return false, err
}
return rows > 0, nil
}
// queryScalar is the contracts' raw-row hook. It opens its own SQL handle per
// call, the way the embedded backend's own frozen fixture kit does, because a
// held handle and a live server on the same database is a lock nobody needs.
//
// "Nobody needs" is measured, not assumed. An earlier revision of the graph-role
// wiring held one handle open for the life of the environment: the first seeding
// write after it opened never returned, the run died on Go's default ten-minute
// test timeout at 600.080s, and the panic's goroutine dump put the test inside
// embeddeddolt.(*EmbeddedDoltStore).CreateIssue blocked in the store's own
// connection acquisition, with the server goroutine parked beside it for four
// minutes. It HANGS rather than fails, which is the worst shape a gate can take
// — so the per-call open is load-bearing, and a future refactor that hoists it
// out for tidiness would reintroduce a deadlock, not a slowdown.
func (e *servedEnv) queryScalar(ctx context.Context, query string, args []any, dest ...any) error {
db, cleanup, err := embeddeddolt.OpenSQL(ctx, e.dataDir, e.database, "main")
if err != nil {
return err
}
defer func() { _ = cleanup() }()
return db.QueryRowContext(ctx, query, args...).Scan(dest...)
}
// countHistoryMatching counts the reference branch's history entries whose
// message matches pattern, where "" means every entry and anything else is a
// SQL LIKE pattern (backend/conformance/history_matching.go states the
// convention). The wisp-naming case needs it: "no entry NAMES this wisp" is a
// claim about what an entry READS, which a bare count cannot express, and a nil
// hook leaves that clause unpinned on this tier rather than checked.
func (e *servedEnv) countHistoryMatching(ctx context.Context, pattern string) (int, error) {
query := "SELECT COUNT(*) FROM dolt_log"
var args []any
if pattern != "" {
query += " WHERE message LIKE ?"
args = append(args, pattern)
}
var entries int
err := e.queryScalar(ctx, query, args, &entries)
return entries, err
}
// countHistory is DEFINED as the empty-pattern count, the same way the embedded
// backend's own fixture kit defines it, so the two hooks cannot disagree about
// the length of one log.
func (e *servedEnv) countHistory(ctx context.Context) (int, error) {
return e.countHistoryMatching(ctx, "")
}
// commitPending settles everything seeded so far into the version history, so a
// later countHistory delta measures the call under test and not the seeds that
// led up to it.
//
// It runs against the REFERENCE store rather than the subject, like every other
// out-of-band hook here: the subject is an http client, which publishes no
// commit at all (CommitPending is on its unsupported allowlist), and the history
// these cases measure belongs to the store the server is serving from.
func (e *servedEnv) commitPending(ctx context.Context) error {
return e.commitMessage(ctx, "conformance: settle seeds before a history delta")
}
// commitMessage is the same act under the caller's own message, which the
// staging fixture's Commit hook takes: those cases read `AS OF 'HEAD'` and the
// entry they settle the seeds into is named after what it settled.
func (e *servedEnv) commitMessage(ctx context.Context, message string) error {
return e.reference.Commit(ctx, message)
}
// execRaw is the single-statement spelling of exec, which is the shape the
// staging fixture's own Exec hook takes. It is a spelling rather than a second
// implementation so both go through the per-call handle the comment on
// queryScalar explains.
func (e *servedEnv) execRaw(ctx context.Context, query string, args ...any) error {
return e.exec(ctx, []conformance.SQLStatement{{Query: query, Args: args}})
}
// exec runs a seeding script as ONE session, for the close/reopen cases that
// need a state no supported verb can produce.
func (e *servedEnv) exec(ctx context.Context, statements []conformance.SQLStatement) error {
db, cleanup, err := embeddeddolt.OpenSQL(ctx, e.dataDir, e.database, "main")
if err != nil {
return err
}
defer func() { _ = cleanup() }()
conn, err := db.Conn(ctx)
if err != nil {
return err
}
defer func() { _ = conn.Close() }()
for _, statement := range statements {
if _, err := conn.ExecContext(ctx, statement.Query, statement.Args...); err != nil {
return err
}
}
return nil
}

View file

@ -0,0 +1,254 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_hooks_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/hooks"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// Client-side hook parity, design D9 L11.
//
// THE POSTURE. `bd serve` runs no hooks — it says so, and its own registered-
// backend test asserts an HTTP claim does NOT run the served workspace's
// on_update. That is the SERVER's side. This file is the client's: the seam sits
// below HookFiringStore in the client process (cmd/bd's wireStorageDecorators
// composes caller → HookFiringStore → telemetry → the opened store, and a
// registered backend's store goes through that call exactly as an embedded one
// does), so a workspace connected to a server still runs its own on_update when
// its own `bd` writes.
//
// WHY IT NEEDS A TEST AT ALL. HookFiringStore decorates six role accessors, and
// each one recurses into the inner store's accessor rather than delegating
// blindly — a blind delegation would hand back the inner claimer unchanged and
// silently drop the hook every landed claim owes. Nothing forces that for a
// backend that arrived through the registry, and nothing in the tree asserted
// it: the hook-firing tests are embedded-Dolt or proxied-Dolt, and the
// registered-backend test only pins the negative. A store whose Changed flag
// came out of an HTTP response rather than a SQL row is exactly where the
// no-op suppression could quietly invert.
//
// The residue L11 records stands: the hook fires AFTER the server's commit with
// no shared transaction, so a hook that re-reads sees the server's state.
// TestHooksFireOnHTTPWritesThroughTheDecoratorChain is the parity proof: a claim,
// an update and a close, all over the wire, each running this workspace's hook.
func TestHooksFireOnHTTPWritesThroughTheDecoratorChain(t *testing.T) {
env := newServedEnv(t, "hhk")
ctx := t.Context()
hooksDir := t.TempDir()
updateMarker := plantHook(t, hooksDir, "on_update")
closeMarker := plantHook(t, hooksDir, "on_close")
// The chain cmd/bd builds, with the http store where the opened store goes.
// Taking the roles off the DECORATED store rather than off the client is the
// whole subject: a command holds this interface, and the accessor is where
// each decorator adds its layer.
var decorated storage.DoltStorage = storage.NewHookFiringStore(env.subject, hooks.NewRunner(hooksDir))
const id = "hhk-hooked"
seed := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := env.createIssue(ctx, seed, "seed"); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
claimer, err := decorated.IssueClaimer()
if err != nil {
t.Fatalf("IssueClaimer() off the decorated store: %v", err)
}
if !storage.RoleFiresHooks(claimer) {
t.Fatal("the decorated store handed back a claimer that fires no hooks; the decorator delegated instead of recursing")
}
if _, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: "worker", IssueID: id}); err != nil {
t.Fatalf("claim over http: %v", err)
}
waitForHook(t, updateMarker, "an HTTP claim")
lifecycle, err := decorated.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle() off the decorated store: %v", err)
}
if !storage.RoleFiresHooks(lifecycle) {
t.Fatal("the decorated store handed back a lifecycle that fires no hooks")
}
if err := os.Remove(updateMarker); err != nil {
t.Fatalf("clear the update marker: %v", err)
}
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "worker", IssueID: id,
Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: "edited over http"}},
}); err != nil {
t.Fatalf("update over http: %v", err)
}
waitForHook(t, updateMarker, "an HTTP update")
if _, err := lifecycle.Close(ctx, issueops.CloseRequest{Actor: "worker", IssueID: id, Reason: "done"}); err != nil {
t.Fatalf("close over http: %v", err)
}
waitForHook(t, closeMarker, "an HTTP close")
// The writes are the server's, read back from the store the server serves —
// never from the client, which is the thing under test.
after, err := env.getIssue(ctx, id)
if err != nil {
t.Fatalf("read %s back from the reference store: %v", id, err)
}
if after.Title != "edited over http" {
t.Errorf("title after the update = %q, want the edit to have landed server-side", after.Title)
}
if after.Status != types.StatusClosed {
t.Errorf("status after the close = %q, want closed", after.Status)
}
}
// TestTheIdempotentReclaimFiresNoHook is the suppression half, and it is the
// half an HTTP-sourced Changed flag could invert: already_claimed on a 200 means
// the SAME actor re-claimed, and reading it as a change would run the user's
// hook script once per poll for a write that never happened.
//
// PROVING AN ABSENCE. hooks.Runner.Run is fire-and-forget, so "the marker is not
// there yet" is not the same as "no hook ran", and a fixed sleep only decides
// how long the test is wrong for. The barrier here is a POSITIVE CONTROL on a
// SECOND issue: the log records one line per invocation with the issue id it
// fired for, the re-claim is followed by a genuinely-changed write on another
// row, and the assertion waits for THAT row's line. The re-claim's hook, had it
// fired, would have been launched strictly earlier — before the second write was
// even issued — so a log that reaches the barrier without it is evidence rather
// than a guess. The count is asserted as well as the contents, which is what
// catches a hook that fired for the right row the wrong number of times.
func TestTheIdempotentReclaimFiresNoHook(t *testing.T) {
env := newServedEnv(t, "hhq")
ctx := t.Context()
hooksDir := t.TempDir()
log := plantLoggingHook(t, hooksDir, "on_update")
decorated := storage.NewHookFiringStore(env.subject, hooks.NewRunner(hooksDir))
const claimed = "hhq-reclaim"
const barrier = "hhq-barrier"
for _, id := range []string{claimed, barrier} {
seed := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}
if err := env.createIssue(ctx, seed, "seed"); err != nil {
t.Fatalf("seed %s: %v", id, err)
}
}
claimer, err := decorated.IssueClaimer()
if err != nil {
t.Fatalf("IssueClaimer(): %v", err)
}
if _, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: "worker", IssueID: claimed}); err != nil {
t.Fatalf("first claim: %v", err)
}
waitForHookLine(t, log, claimed, "the first HTTP claim")
res, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: "worker", IssueID: claimed})
if err != nil {
t.Fatalf("re-claim: %v", err)
}
if res.Changed {
t.Fatal("the re-claim reported Changed; already_claimed on a 200 is the idempotent re-claim")
}
// The barrier: a write that genuinely changes a DIFFERENT row, whose hook is
// launched after the re-claim's would have been.
lifecycle, err := decorated.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "worker", IssueID: barrier,
Patch: issueops.IssuePatch{Title: issueops.Field[string]{Set: true, Value: "barrier edit"}},
}); err != nil {
t.Fatalf("barrier update: %v", err)
}
waitForHookLine(t, log, barrier, "the barrier update")
if got := countHookLines(t, log, claimed); got != 1 {
t.Errorf("on_update fired %d times for %s, want 1: the idempotent re-claim ran the user's script for a write that never happened, "+
"and a polling agent would run it once per poll", got, claimed)
}
}
// plantHook writes an executable hook that touches a marker, and returns the
// marker path.
func plantHook(t *testing.T, hooksDir, name string) string {
t.Helper()
marker := filepath.Join(t.TempDir(), name+".fired")
script := "#!/bin/sh\ntouch " + marker + "\n"
if err := os.WriteFile(filepath.Join(hooksDir, name), []byte(script), 0o755); err != nil { //nolint:gosec // G306: a hook must be executable to run at all
t.Fatalf("plant the %s hook: %v", name, err)
}
return marker
}
// plantLoggingHook writes a hook that APPENDS the issue id it fired for, so the
// test can count invocations rather than observe a latch. `$1` is the issue id
// the runner passes as the hook's first argument.
func plantLoggingHook(t *testing.T, hooksDir, name string) string {
t.Helper()
log := filepath.Join(t.TempDir(), name+".log")
script := "#!/bin/sh\necho \"$1\" >> " + log + "\n"
if err := os.WriteFile(filepath.Join(hooksDir, name), []byte(script), 0o755); err != nil { //nolint:gosec // G306: a hook must be executable to run at all
t.Fatalf("plant the %s hook: %v", name, err)
}
return log
}
// waitForHookLine polls until the log records an invocation for id.
func waitForHookLine(t *testing.T, log, id, what string) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if countHookLines(t, log, id) > 0 {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("%s ran no hook: %s recorded no line for %s", what, log, id)
}
func countHookLines(t *testing.T, log, id string) int {
t.Helper()
data, err := os.ReadFile(log) // #nosec G304 - the path is this test's own temp file
if err != nil {
if os.IsNotExist(err) {
return 0
}
t.Fatalf("read the hook log: %v", err)
}
n := 0
for _, line := range strings.Split(string(data), "\n") {
if strings.TrimSpace(line) == id {
n++
}
}
return n
}
// waitForHook polls for the marker. hooks.Runner.Run is fire-and-forget by
// design — a slow hook must not block the write that triggered it — so the only
// honest assertion is a bounded wait.
func waitForHook(t *testing.T, marker, what string) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if _, err := os.Stat(marker); err == nil {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("%s ran no hook: %s was never created", what, marker)
}

View file

@ -0,0 +1,261 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_issue_operations_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// The Lifecycle PERSISTENCE-SEAM contracts, run through client → in-process bd
// serve → reference store.
//
// This is the half of the Lifecycle role that the three accessor-reachable
// contract files next door deliberately do not hold: every case here ends on a
// COLUMN rather than on a returned row — the persisted `is_blocked` projection,
// `metadata IS NULL`, a committed `AS OF 'HEAD'` read, the plane a create
// routed to — and no read on any role hydrates those. The contract expresses
// that as a raw-SQL seam on its fixture, and this leg answers it the way it
// answers every other out-of-band probe: through the REFERENCE store the server
// is serving from, never through the client.
//
// WHAT THAT MAKES THE TIER WORTH HERE. The subject is one HTTP request. The
// client sends it, recomputes nothing, and every postcondition below is read
// out of the database afterwards — so a settlement the server did not make
// inside its own transaction, a plane it routed the wrong way, or a metadata
// document it wrote as SQL NULL shows up as a raw-row fact with no role read in
// between to launder it.
//
// UpdateRaw is bound to the REFERENCE store's own untyped funnel
// (env.reference.UpdateIssue), never to the client: storage.UpdateIssue is on
// the 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 there is
// no client funnel to bind. That is fine for every case actually registered in
// this file, because none of them takes the funnel AS ITS SUBJECT — they use it
// only to SEED a precondition an httpLifecycle.Create or the configured-status
// vocabulary cannot reach directly (an already-deferred row, a custom
// "name:category" status create does not parse). The three cases whose SUBJECT
// is the funnel itself (RunIssueOperationsUpdateRawMetadataTakesTheFunnelsValueShapes
// and its siblings) are never called here — asserting the reference store's
// funnel would be the mirror image of seeding through the client, and just as
// empty — so binding this hook carries no risk of laundering a client
// assertion through the store it happens to share a process with.
//
// ONE ENVIRONMENT PER CASE, which the contract requires rather than prefers:
// RunIssueOperationsCreateRoutesInfraTypesToWisps installs BARE workspace-global
// type vocabulary and leaves it installed, and the child-id cases mint against a
// counter a neighbouring case's seeds would move.
func newServedIssueOperationsFixture(t *testing.T, prefix string) conformance.IssueOperationsStagingFixture {
t.Helper()
env := newServedEnv(t, prefix)
lifecycle, err := env.subject.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
return conformance.IssueOperationsStagingFixture{
IssuePrefix: env.prefix,
// The only hook bound to the CLIENT. The contract calls this field both
// the seed route and the subject, and where a case seeds through it the
// seed is itself a served create — every precondition those cases assert
// afterwards is read back raw.
Operations: lifecycle,
CreateIssue: env.createIssue,
AddDependency: env.addDependency,
GetReadyWork: env.reference.GetReadyWork,
SetConfig: env.setConfig,
Commit: env.commitMessage,
Exec: env.execRaw,
QueryScalar: env.queryScalar,
UpdateRaw: env.reference.UpdateIssue,
}
}
// ── The create half ─────────────────────────────────────────────────────────
// TestServedIssueOperationsCreateRoutesInfraTypesToWisps is the routing case,
// and the plane it asserts is one the client cannot ask for: createIssue
// publishes `ephemeral`, but this case sends a bare infra TYPE and leaves the
// plane to the workspace's own `types.infra` vocabulary. So what runs here is
// the server reading its configured set and routing on it, with the answer read
// out of both tables.
func TestServedIssueOperationsCreateRoutesInfraTypesToWisps(t *testing.T) {
conformance.RunIssueOperationsCreateRoutesInfraTypesToWisps(t, t.Context(), newServedIssueOperationsFixture(t, "hio1"))
}
// TestServedIssueOperationsCreateUnderAParentMintsTheNextChildID is the id
// allocator, which is emphatically the SERVER's here: GetNextChildID is on the
// unsupported allowlist, so the client names no id at all and reads the minted
// one off the answer. The case's last arm — a parent whose differently-cased
// twin already has a child — is the one that would catch a counter keyed on a
// case-folded parent.
func TestServedIssueOperationsCreateUnderAParentMintsTheNextChildID(t *testing.T) {
conformance.RunIssueOperationsCreateUnderAParentMintsTheNextChildID(t, t.Context(), newServedIssueOperationsFixture(t, "hio2"))
}
// TestServedIssueOperationsCreateClosedDerivesTheClosedStamp is PARKED, and
// it is the one park in this file whose refusal is not a gap but the point.
//
// The derivation it pins reads the CREATION STAMP the caller supplied — that is
// what "one second past the later of created_at and updated_at" is a function of
// — and created_at is exactly the member createIssue withholds, because a
// caller-supplied creation time makes the row disagree with the journal entry
// that records it. So the case's subject is the import path, and importing is
// the act this surface says belongs to `bd import` rather than to a create.
// The park will outlive every other one here.
func TestServedIssueOperationsCreateClosedDerivesTheClosedStamp(t *testing.T) {
skipKnownDivergence(t, "W-CreateRequest.Issue", createParkBead,
"every arm supplies Issue.CreatedAt and Issue.UpdatedAt, which are the two stamps the derivation is a "+
"function of and the two createIssue deliberately does not publish; the client refuses them per "+
"member (asserted by TestCreateRefusesEveryMemberTheWireExcludes) rather than deriving a closed_at "+
"from stamps the server chose")
conformance.RunIssueOperationsCreateClosedDerivesTheClosedStamp(t, t.Context(), newServedIssueOperationsFixture(t, "hio3"))
}
func TestServedIssueOperationsCreateWithDependenciesSettlesInTheCreatingTransaction(t *testing.T) {
conformance.RunIssueOperationsCreateWithDependenciesSettlesInTheCreatingTransaction(t, t.Context(), newServedIssueOperationsFixture(t, "hio4"))
}
// The two STAGING cases, which are the only ones in this package that read
// `AS OF 'HEAD'`. They dirty an unrelated durable row in the working set, then
// create, then ask what the create's own commit swept in — and over this wire
// the commit is entirely the server's, made in a process that never saw the
// dirty row. The unit-of-work leg waives both because it has no caller-held
// working set; this leg has one, because the reference store the server serves
// is a real embedded engine and the fixture holds it.
func TestServedIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t *testing.T) {
conformance.RunIssueOperationsCreateReverseNonBlockingStagesConcreteTables(t, t.Context(), newServedIssueOperationsFixture(t, "hio5"))
}
func TestServedIssueOperationsCreateParentChildRecomputesWaitsForClosure(t *testing.T) {
conformance.RunIssueOperationsCreateParentChildRecomputesWaitsForClosure(t, t.Context(), newServedIssueOperationsFixture(t, "hio6"))
}
// ── The update half ─────────────────────────────────────────────────────────
func TestServedIssueOperationsUpdateLabelPatchOrdering(t *testing.T) {
conformance.RunIssueOperationsUpdateLabelPatchOrdering(t, t.Context(), newServedIssueOperationsFixture(t, "hio7"))
}
// TestServedIssueOperationsUpdateLabelPatchValueRules is PARKED on
// L-update-fieldlen, which this wave FOUND: its first arm asserts
// ErrFieldTooLong for a 256-character label, and the operation refuses that at
// the edge with the same `invalid_argument`/`invalid_value` pair every other
// bad value on the member earns.
//
// Everything else the case is about — the duplicate add applied once, the
// absent remove that is a no-op, the empty string dropped rather than stored —
// is unaffected, and the incremental algebra beside them is exercised over this
// wire by TestServedUpdateAppliesTheOrderedLabelEditServerSide.
func TestServedIssueOperationsUpdateLabelPatchValueRules(t *testing.T) {
skipKnownDivergence(t, "L-update-fieldlen", fieldLenParkBead,
"the case's first arm binds types.ErrFieldTooLong for an over-long label, and the operation applies "+
"that bound at the edge with the invalid_value reason a malformed member also earns (asserted, "+
"ceiling and both legs included, by TestServedUpdateFieldLengthBoundsAreTheServersAndNotThisClients)")
conformance.RunIssueOperationsUpdateLabelPatchValueRules(t, t.Context(), newServedIssueOperationsFixture(t, "hio8"))
}
// TestServedIssueOperationsUpdateMetadataReplaceClearsAndValidates ends on
// `SELECT metadata IS NULL`, which is the whole reason it lives on this fixture:
// a hydrated issue reads a NULL column and the empty document back as the same
// nil bytes, so the clause — metadata is NEVER SQL NULL — is invisible to every
// read this surface publishes.
func TestServedIssueOperationsUpdateMetadataReplaceClearsAndValidates(t *testing.T) {
conformance.RunIssueOperationsUpdateMetadataReplaceClearsAndValidates(t, t.Context(), newServedIssueOperationsFixture(t, "hio9"))
}
func TestServedIssueOperationsUpdateFoldsMetadataIntoOneEvent(t *testing.T) {
conformance.RunIssueOperationsUpdateFoldsMetadataIntoOneEvent(t, t.Context(), newServedIssueOperationsFixture(t, "hioa"))
}
func TestServedIssueOperationsUpdateRefusesATypeOutsideTheWorkspaceVocabulary(t *testing.T) {
conformance.RunIssueOperationsUpdateRefusesATypeOutsideTheWorkspaceVocabulary(t, t.Context(), newServedIssueOperationsFixture(t, "hiob"))
}
// The two STATUS-CROSSING settlement cases. They are the update's half of what
// the close cases assert next door, and they are the pair the blocked-state kit
// calls two genuine votes: issueops update.go and domain/db issue.go each decide
// independently when a status move counts as a crossing.
func TestServedIssueOperationsUpdateStatusCrossingSettlesDependers(t *testing.T) {
conformance.RunIssueOperationsUpdateStatusCrossingSettlesDependers(t, t.Context(), newServedIssueOperationsFixture(t, "hioc"))
}
func TestServedIssueOperationsUpdateStatusCrossingSettlesAConditionalBlocksDepender(t *testing.T) {
conformance.RunIssueOperationsUpdateStatusCrossingSettlesAConditionalBlocksDepender(t, t.Context(), newServedIssueOperationsFixture(t, "hiod"))
}
// TestServedIssueOperationsRequestValuesAreNotMutated is the aliasing tripwire,
// and the one case here whose answer this leg gets for free in a way worth
// saying out loud: the request is SERIALIZED on the way out and the result is
// DESERIALIZED on the way back, so there is no pointer for the role to write
// through even if it wanted to. It runs anyway, because that argument is about
// today's transport and the promise is the role's.
func TestServedIssueOperationsRequestValuesAreNotMutated(t *testing.T) {
conformance.RunIssueOperationsRequestValuesAreNotMutated(t, t.Context(), newServedIssueOperationsFixture(t, "hioe"))
}
// ── The parks ───────────────────────────────────────────────────────────────
//
// Two, and both are a member updateIssue publishes nothing for. The refusals
// themselves are asserted by TestUpdateRefusesEveryMemberTheWireExcludes,
// which RUNS.
//
// The THREE CLAIM cases below are not parks: a claim rides updateIssue's own
// body (upstream #6890) — alone, or beside a patch, a guard or a force
// override, claimed and written in one transaction — so all three run for real
// against an in-process bd serve over embedded Dolt.
//
// The conflict case was the last to leave. Its final section drives Claim with
// a stale ExpectedVersion, the one claim/guard composition the local role
// allows, and while claimIssue (whose request is the actor alone) was the only
// claim this client sent, that combination refused on W-UpdateRequest.Claim —
// RETIRED by the #7247 review port, which sends the guard beside the claim.
func TestServedIssueOperationsUpdateClaimConflictCarriesTheLosingState(t *testing.T) {
conformance.RunIssueOperationsUpdateClaimConflictCarriesTheLosingState(t, t.Context(), newServedIssueOperationsFixture(t, "hiof"))
}
func TestServedIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t *testing.T) {
conformance.RunIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t, t.Context(), newServedIssueOperationsFixture(t, "hiog"))
}
func TestServedIssueOperationsClaimLeavesBlockedStateAlone(t *testing.T) {
conformance.RunIssueOperationsClaimLeavesBlockedStateAlone(t, t.Context(), newServedIssueOperationsFixture(t, "hioh"))
}
// fieldLenParkBead is the bead the length-bound park cites, and it is separate
// from parkBead because it retires on a different event: the write-side parks
// wait on the wire growing a MEMBER, and this one waits on it growing a REASON.
// The behaviour is already served; only its classification is coarse.
const fieldLenParkBead = "ga-2ltro.19"
// TestServedIssueOperationsUpdateIssuePlaneOnlyRefusesWisps is the staging
// twin of the accessor-reachable plane case next door, and it parks for the
// same reason: dropping the restriction would EDIT the wisp the caller asked to
// be told did not exist.
func TestServedIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t *testing.T) {
skipKnownDivergence(t, "W-UpdateRequest.IssuePlaneOnly", parkBead,
"updateIssue publishes no plane restriction and the server's role auto-resolves both planes, so the "+
"client refuses the flag rather than silently editing the wisp the case asked it to refuse")
conformance.RunIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t, t.Context(), newServedIssueOperationsFixture(t, "hioi"))
}
// TestServedIssueOperationsUpdateWritesEveryScalarPatchField parks on FOUR
// members at once — spec_id, await_id, owner and closed_by_session — and the
// citation names spec_id because it is the first the encoder reaches. `owner` is
// the odd one: ApplyPatchBody publishes it and IssuePatchBody does not, which
// the document itself calls an accident of order rather than a decision, so this
// park is the one here most likely to narrow rather than retire.
func TestServedIssueOperationsUpdateWritesEveryScalarPatchField(t *testing.T) {
skipKnownDivergence(t, "W-IssuePatch.SpecID", parkBead,
"the case writes every scalar the patch carries, and four of them — spec_id, await_id, owner and "+
"closed_by_session — are members IssuePatchBody does not publish; the client refuses each by name "+
"rather than reporting a landed edit that dropped them")
conformance.RunIssueOperationsUpdateWritesEveryScalarPatchField(t, t.Context(), newServedIssueOperationsFixture(t, "hioj"))
}

View file

@ -0,0 +1,95 @@
//go:build cgo
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/served_journal_test.go@49d1df2f6)
// to OSS beads under the MIT license.
package httpclient
import (
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/storage"
)
// The Journal contract against the served surface.
//
// It is the FOURTH leg of a role that has three in-tree bodies and one shared
// one: both Dolt stores and the unit-of-work provider bottom out in
// issueops.ReadEventsPageInTx, so those three are one reading plus an engine
// check. This leg is genuinely independent — a JSON envelope over HTTP, a typed
// error rebuilt from a problem document, and a page bound that is the handler's
// rather than the role's — which is why the contract's own header calls the
// truncation case the one that matters more than it looks: the alias identity it
// checks at runtime is checked here across a WIRE.
//
// THE SPLIT BETWEEN THE FIXTURE'S HOOKS IS THE HARNESS RULE, and on this role it
// is also the role's own doctrine. Journal is bound to the CLIENT; activation
// and retention are bound to the REFERENCE store, because they are operator
// surface that journalops deliberately keeps off the role — a publishing surface
// must not be one line away from a delete — and this client implements neither.
// So the fixture's shape is not a testing convenience here, it is the same split
// the production types make.
//
// ORDER AND SEQUENTIALITY ARE LOAD-BEARING, exactly as they are on the three
// legs upstream: two cases PRUNE, one of them to nothing, every case rebaselines
// off the live head, and EveryMutationKindLandsARow runs last on purpose.
func TestServedJournalContract(t *testing.T) {
env := newServedEnv(t, "hjrn")
ctx := t.Context()
fixture := newServedJournalFixture(t, env)
t.Cleanup(func() {
// Journaling is INSTANCE-scoped, and the reference store outlives this
// fixture inside one test binary. Leaving it on would journal every
// mutation a later case in this package makes.
env.reference.SetEventsJournalEnabled(false)
})
t.Run("PagesAreSeqAscendingAndSinceExclusive", func(t *testing.T) {
conformance.RunJournalPagesAreSeqAscendingAndSinceExclusive(t, ctx, fixture)
})
t.Run("HeadArrivesWithItsRowsAndDetectsCaughtUp", func(t *testing.T) {
conformance.RunJournalHeadArrivesWithItsRowsAndDetectsCaughtUp(t, ctx, fixture)
})
t.Run("LimitCapsRowsNotHead", func(t *testing.T) {
conformance.RunJournalLimitCapsRowsNotHead(t, ctx, fixture)
})
t.Run("TruncationIsTypedAndNamesTheWindow", func(t *testing.T) {
conformance.RunJournalTruncationIsTypedAndNamesTheWindow(t, ctx, fixture)
})
t.Run("HeadSurvivesAFullPrune", func(t *testing.T) {
conformance.RunJournalHeadSurvivesAFullPrune(t, ctx, fixture)
})
t.Run("EveryMutationKindLandsARow", func(t *testing.T) {
conformance.RunJournalEveryMutationKindLandsARow(t, ctx, fixture)
})
}
// newServedJournalFixture binds the role to the client through the TYPE
// ASSERTION `bd serve` makes, never through the concrete method set.
//
// The journal is not on storage.DoltStorage — journalops states why a role with
// no accessor is the right shape for it — so publishing it IS implementing this
// interface, and a client that stopped would fail here rather than keep
// compiling against a struct.
func newServedJournalFixture(t *testing.T, env *servedEnv) conformance.JournalFixture {
t.Helper()
cursor, ok := any(env.subject).(storage.EventsJournalCursor)
if !ok {
t.Fatalf("%T does not implement storage.EventsJournalCursor", env.subject)
}
reference := env.reference
return conformance.JournalFixture{
IssuePrefix: env.prefix,
Journal: cursor,
SetJournalEnabled: reference.SetEventsJournalEnabled,
Prune: reference.PruneEventsJournal,
// EVERY MUTATION DRIVES THE REFERENCE STORE, which is the harness rule
// and not a shortcut around a refusing client. Two of the seven have no
// client-side spelling at all — a raw delete and a raw dependency remove
// are on the unsupported allowlist — and the other five would prove the
// client agrees with itself: the question this contract asks is whether
// the client can READ the journal a server wrote.
Mutations: servedJournalMutations(reference),
}
}

Some files were not shown because too many files have changed in this diff Show more