* feat(httpapi): wire-shape signal — wire_revision, floor header, golden digest, param tokens
S0 of the HTTP role-parity program: give a client a single place to learn
whether this build's wire shape has moved under it, and give CI a gate that
catches an undocumented move.
- GET /v0/beads/context reports wire_revision (bumps only on a non-additive
response-shape change) and min_client_wire_revision. An optional
Bd-Wire-Revision request header lets a client declare the revision it was
built for; checkWireRevision refuses a declared revision below the floor
with 400 invalid_argument/reason=wire_revision_unsupported and a
min_wire_revision field, on every route but /healthz (wireRevisionExempt) —
including the identity handshake, where catching the mismatch is cheapest.
Absent header is today's behavior; malformed value is invalid_value, never
wire_revision_unsupported. The floor lives in Server.minClientWireRevision
(defaulting to the MinClientWireRevision constant) so a test can raise it.
- internal/httpapi/wireshape: a golden digest over every response's every
content-type schema (including application/problem+json) across the whole
spec, keyed by schema+member. TestWireShapeDigest fails closed when a
member's JSON name or type changes without wire_revision bumping to match;
regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`.
- GET /v0/beads/issues' `sort` parameter now carries the issues.listSort
capability token, the same convention `capabilities` entries use.
TestNewParameterOnExistingOperationHasABehaviorToken requires every new
parameter on an existing operation to carry one, checked against a
write-once grandfather baseline (testdata/pretoken_parameters.json) of
parameters that predate the rule; TestUntokenedParameterRuleFires proves
the checker itself against a synthetic fixture.
- Docs: engdocs/design/bd-serve-v0.md gets a "The wire-shape signal" section;
CHANGELOG.md gets an Added entry.
Live-mutated and reverted three RED demonstrations during development:
retyping api_version in the spec failed TestWireShapeDigest; short-circuiting
checkWireRevision's floor comparison failed
TestWireRevisionBelowFloorRefusesEveryEnforcedRoute; adding an untokened
query parameter to listIssues failed
TestNewParameterOnExistingOperationHasABehaviorToken. All three now pass
against the unmutated tree.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): rename issues.listSort to issues.list.sort, harden token rule
Opus review of 12c5144ca (HIGH-1, MEDIUM-5):
- Rename the capability token issues.listSort -> issues.list.sort to match
bd-enterprise's client (httpstore/wire/handshake.go:121, DESIGN.txt S4e),
and widen capabilityToken to accept an optional third segment.
- untokenedParameters() now requires the extracted token to be one
Capabilities() actually serves, not just backtick-shaped text. This
catches real false positives that existed in the spec already
(workapi.DefaultReadyLimit, status.custom) which only shape-matched the
old regex; they're added to the pretoken baseline as genuinely
pre-existing untokened parameters.
- Extend the rule to request body members (new
testdata/pretoken_request_body_members.json baseline) and exempt
brand-new operations via a frozen testdata/pretoken_operations.json
snapshot.
- Add TestPretokenBaselinesNeverGrow pinning all three baseline sizes so
a future change can't hand-add an exemption instead of a token.
- Update spec prose for the widened rule scope.
go test ./internal/httpapi/... and the reviewer's pmut.py all pass as
expected: plain/bogus modes go RED, reuse (real-but-unrelated token) stays
green, matching the review's literal ask ("a token must be one advertised
by Capabilities()").
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): close four digest-coverage gaps, add gendigest write guard
Opus review of 12c5144ca (HIGH-2, MEDIUM-4). The digest only tracked
Type/Format/Enum/Required on direct properties, missing:
- nullable: true (never read at all)
- array item shape (Issue.labels items string->integer was invisible;
only object-shaped items got recursed into)
- additionalProperties value shape (IssueCount.groups)
- request bodies entirely (Compute() only walked responses, so
DeleteIssuesRequest.expected_version string->integer, the other half
of #6053, was invisible)
Also added defensive oneOf flattening alongside the existing allOf merge
(dormant today -- grep confirms this spec uses oneOf nowhere -- but no
longer silently invisible if that changes).
Extracted the golden-vs-computed comparison into wireshape.Compare(),
shared by TestWireShapeDigest and the new wireshape.SafeToWrite(), which
gendigest now calls before writing: it refuses to overwrite golden.json
with changed/removed entries unless the candidate's wire_revision is
strictly greater than the existing golden's. Pure additions always write.
TestSafeToWrite exercises both guard directions.
golden.json is regenerated. This single regen is a one-time exception to
the new guard, done by writing the digest directly rather than through
gendigest: confirmed via a throwaway diff (not checked in) that every one
of the 57 "changed" entries differs only in the NEW fields the wider walk
now populates (ItemType/ItemFormat/Nullable/AdditionalProps*) -- every
pre-existing Type/Format/Required/Enum value is byte-identical. Nothing on
the wire changed; the measurement got more precise. Bumping
CurrentWireRevision for this would have written a false "the protocol
changed here" entry into the revision history table. Going forward, any
REAL change the guard now reports uses the normal bump-then-regenerate
path, same as before.
Verified against the reviewer's mut.py: nested_type, nullable,
nullable_issue, array_items, addlprops, request_body and format all go RED
on TestWireShapeDigest, each reverted after confirming.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): make bd_version wire_revision inference advisory
Opus review of 12c5144ca (HIGH-3). The spec told a client inferring
wire_revision from bd_version to use the release cutoff >= 1.3.0, and said
nothing about what happens when that inference is wrong -- which it
demonstrably is for real builds already in the field:
- main builds up to commit b3ef65c85 report bd_version 1.2.2 (below any
1.3.0 cutoff) while already sending the string-typed revision/
expected_version shape (#6053).
- 1.3.0-rc.N pre-release builds sort BELOW the release cutoff 1.3.0 under
plain string comparison despite already carrying the string shape.
- The bd-enterprise compatibility line at d3ab32773462 reports bd_version
1.1.0 while also sending strings.
Moved the cutoff to >= 1.3.0-rc.1 (compared as semver-with-prerelease,
which at least captures the rc builds), documented both named exceptions
inline, and made the whole inference explicitly ADVISORY: a client must
accept revision/expected_version as either a string or a number whenever
wire_revision is absent (or probe directly) rather than let the inferred
value choose a decoder, and must never refuse solely because the inferred
revision is 0. Mirrored into engdocs/design/bd-serve-v0.md.
This is spec/doc prose only -- there is no server-side inference code to
change, since this server always sends wire_revision directly; the
inference is guidance for clients reading a pre-signal server's response
(this server, past builds, or an unrelated implementation).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): LOW-7/8/9/10 review follow-ups for wire-revision signal
LOW-7: WireRevisionUnsupported now also sets Problem.wire_revision (this
server's CurrentWireRevision) and Problem.bd_version on the
wire_revision_unsupported refusal, alongside the existing
min_wire_revision, so a client logging the refusal has this server's
full self-description without a second /v0/beads/context call.
LOW-8: gazelle + make bazel-sync add the BUILD.bazel entries the prior
commits were missing: wire_revision.go/wire_revision_test.go in
internal/httpapi's srcs, new BUILD.bazel files for wireshape and
wireshape/cmd/gendigest, and a testdata glob on httpapi's go_test so
the pretoken_*.json baselines are visible under `bazel test`. Verified
with `bazel build //internal/httpapi/...` and
`bazel test //internal/httpapi/... --test_env=BEADS_TEST_SKIP=dolt`
(both green) and `python3 tools/bazel/go_srcs.py --check` (clean).
LOW-9: narrowed CHANGELOG.md and engdocs/design/bd-serve-v0.md to
describe the digest's actual final coverage (format/enum/required/
nullable, array items, additionalProperties, request bodies, $ref/
allOf/oneOf recursion, the SafeToWrite revision-bump guard) and the
token rule's actual final shape (three pinned baselines, request-body
members, Capabilities()-membership validation, new-operation
exemption) instead of the original, narrower claims.
LOW-10: Bd-Wire-Revision now parses via a strict decimal-only
parseStrictNonNegativeInt (no leading '+', no leading zero except a
bare "0") instead of strconv.Atoi alone, so two different header
bytes can no longer name the same revision. New malformed-header test
cases: "+1", "01", "007".
Regenerated apigen/types.gen.go (make api-gen) for the new Problem
fields and wireshape/testdata/golden.json (go run
.../wireshape/cmd/gendigest) for the two new additive Problem members;
the latter wrote cleanly through SafeToWrite itself, since both are
pure additions.
go test ./... and bazel test //internal/httpapi/... both green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): re-review LOW follow-ups — retirement test, gendigest -init, docs
1. TestRetiredRevisionsStayBelowTheFloor pins the PRESENCE guarantee the
wire_revision property doc relies on: CurrentWireRevision >= 2 (so 0
and 1 stay permanently retired) and MinClientWireRevision <=
CurrentWireRevision (so this build's own floor never refuses every
request against itself).
2. gendigest now refuses to create a golden.json that does not exist yet
unless run with -init. Previously a missing file (moved testdata,
wrong path, accidental delete) was indistinguishable from a real first
run and silently wrote a fresh golden with no revision history checked
against anything. writeGolden() is extracted out of main() so this is
covered directly: TestWriteGoldenRequiresInitWhenMissing,
TestWriteGoldenInitCreatesWhenMissing,
TestWriteGoldenIgnoresInitWhenGoldenExists (the existing-golden path is
still governed only by SafeToWrite, -init or not).
3. Narrowed the two remaining stale claims that still described the
digest's original, narrower coverage: the wire_revision property's
prose in openapi.v0.yaml (regenerated into apigen/types.gen.go via
make api-gen) and wireshape/doc.go now both list nullable, array item
shape, additionalProperties value shape, request bodies, and
$ref/allOf/oneOf recursion, plus the new -init guard.
go test ./internal/httpapi/... and make api-check both green;
bazel test //internal/httpapi/... (httpapi, wireshape, and the new
gendigest test target) green; python3 tools/bazel/go_srcs.py --check
clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* feat(wireshape): cover operation parameters in the wire-shape digest
The digest previously walked only response and request-body schemas, so a
type, enum, required, or removal change on one of the spec's 138 operation
parameters (123 query, 14 path, 1 header) passed the gate silently — the
open item from PR review on #7182.
Each parameter is now recorded as its own Entry, keyed by
"param:"+operationId / location+":"+name (operation-scoped, not
schema-scoped, since two operations' same-named parameter are independent
wire contracts), capturing type, array item shape, enum, required, style,
explode and default. Adding a parameter stays additive; removing,
retyping, narrowing its enum, or changing required/style/explode/default
now trips SafeToWrite exactly like a response or request-body change.
Verified against the live spec: retyping listIssues' `limit` query
parameter from integer to string now fails TestWireShapeDigest (confirmed
red, then reverted — not part of this commit). golden.json regenerated via
gendigest; the new parameter entries are a pure addition, no wire_revision
bump needed. Added TestParameterMutationsAreCaught (remove/retype/narrow-
enum against real golden entries) and updated wireshape's doc.go, the
`wire_revision` spec prose, and the CHANGELOG to describe the new
coverage.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): review fixes — stale-golden and lowered-revision arms, effective param serialization, digest boundary
Maintainer fixup from the adopt-pr review loop (iterations 1 and 2), on
top of e17ba924f.
- goldenDrift (A, I): TestWireShapeDigest's comparison moves into a
goldenDrift helper. An addition alongside a moved wire_revision no
longer passes with a stale golden: it asks for a regenerate, as a
changed or removed entry after a bump already did. Every message now
names response/request-body members AND parameters, and TestGoldenDrift
pins each arm. This takes only the test half of the stranded fixup
(adopt-pr/bd-47kdge/stranded-fixup-528cd6095); its doc half, which says
parameters are outside the digest, is false since e17ba924f and is not
replayed (J).
- Lowered wire_revision (D): a CurrentWireRevision LOWER than the
golden's is a wrong constant, not a stale golden, so goldenDrift says to
restore it instead of regenerating, and SafeToWrite (so gendigest)
refuses any write at a lower revision, whatever the entries.
- Effective style/explode (B): walkParam records style and explode with
OpenAPI 3.0's defaults filled in (form for query/cookie, simple for
path/header; explode defaults to style == form). Adding `explode: false`
to a query array that relied on form's implicit explode is now a
changed entry, while spelling out a default changes nothing.
testdata/golden.json is regenerated with -init: 111 parameter entries
change only in style/explode (96 to form/true, 15 to simple), 828
entries before and after, wire_revision stays 2. The golden is new in
this PR and unreleased, so this needs no bump.
- TestWalkParam (H): a package-internal table test
(wireshape_internal_test.go) pins every field walkParam extracts,
through a computeFrom(document, revision) seam that Compute now wraps:
per-location defaults, $ref'd parameters and items, format, nullable and
default, content parameters, and the nil returns.
TestEffectiveSerializationIsCompared pins B end to end through Compare
and SafeToWrite. BUILD.bazel embeds the library in the go_test, which is
gazelle's own output.
- Required inputs and the digest boundary (C, E, F; docs only): all five
prose surfaces (openapi.v0.yaml's wire_revision description and the
regenerated apigen/types.gen.go, wireshape/doc.go, CHANGELOG.md,
engdocs/design/bd-serve-v0.md) now say that a new REQUIRED request
input is recorded as an ordinary addition and needs its own review,
that value constraints and member-level composition are outside the
digest, and that object and content parameters are recorded only as
their container. bd-serve-v0.md also gains the parameter coverage it
was missing.
- G: a brand-new operation is permanently exempt from the
capability-token rule; its own review decides its capability story.
- Iteration 2 (nit): walkParam's comment now says that the location
default it records as a `content` parameter's style and explode is a
placeholder, since OpenAPI 3.0 applies style and explode only to a
parameter described by `schema`. All 138 operation parameters in the
spec use `schema`, so the golden does not change.
Validated: go test ./internal/httpapi/... (gms_pure_go), make api-check,
go vet for linux/windows/darwin, gofmt, git diff --check, gazelle on the
package (no drift), make bazel-sync-check, and bazel test
//internal/httpapi/wireshape/... in the local processwrapper sandbox
(2 of 2 pass). Overlay mutation probes: dropping the added-after-bump
arm, the lowered-revision arm, SafeToWrite's lowered check, or the
effective-default fill each turns the new tests red.
Iteration 2 changes only that comment; go test
./internal/httpapi/wireshape/... (gms_pure_go), go vet, gofmt and git
diff --check pass again.
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>
* feat(count): add Counter scope fields (S8) — ParentID, NoParent, ExcludeTypes, ExcludeStatus
Extends issueops.CountRequest with ParentID, NoParent, ExcludeTypes and
ExcludeStatus, closing the gap where bd count could not express the
filters bd list already has, forcing downstream consumers like gc to
fall back to listing everything just to get a count.
- issueops.Counter: four new CountRequest fields, documented against the
List equivalents they mirror (ParentID/ExcludeTypes) or newly define
(NoParent, ExcludeStatus has no List counterpart). Status "all" is
pinned as equivalent to unset, matching BuildListFilter's own "all" and
preserving count/list cardinality parity (the role's reason to exist).
- internal/workapi.BuildCountFilter: maps the four fields onto the one
types.IssueFilter builder all three storage legs (dolt, embeddeddolt,
uow) already share via internal/storage/issueops and sqlbuild, so no
per-leg storage code was needed.
- cmd/bd: --parent, --no-parent, --exclude-type, --exclude-status flags.
- HTTP: adds parent/no_parent/exclude_type/exclude_status to GET
/v0/beads/issues:count, behind the new issues.count.scope behavior
token (routes.go), wired in reads.go's countFilters, documented in
openapi.v0.yaml with per-parameter tokens and an extended capabilities
description. gendigest confirms a byte-identical golden.json: query
parameters are outside the wire-shape digest's scope, so this is a
zero-diff, no-revision-bump change as expected.
- backend/conformance: four new Counter contract cases (ParentID scoping,
NoParent's edge-only semantics vs ParentID's edge-or-dotted-id match,
ExcludeTypes composing with include_infra's own exclusions, and
ExcludeStatus), run identically against all three storage legs via a
new CounterFixture.AddDependency hook shared with ReaderFixture.
Verified: go build ./...; go test ./internal/httpapi/... ./internal/workapi/...
./issueops/... and the Counter contract on all three legs (dolt via
testcontainers, embeddeddolt, uow via local dolt binary); make api-gen
(additive-only apigen diff) and make api-check; go vet and golangci-lint
clean; gofmt clean; gazelle diff empty (no new files/imports). Mutation
testing: dropping issues.count.scope from behaviorCapabilities turns
TestCapabilitiesAdvertiseEveryImplementedOperation,
TestSpecCapabilityVocabularyMatchesTheRouteTable and
TestNewParameterOnExistingOperationHasABehaviorToken red; no-op'ing
ExcludeStatus in BuildCountFilter turns
TestBuildCountFilterExcludeStatusTakesNamesAsWritten and the
embeddeddolt ExcludeStatusNarrowsThePredicate conformance case red. Both
reverted and reconfirmed green.
Deviation: DESIGN.txt's literal text would make count --status all an
ErrValidation; shipped behind a test and a doc comment instead, since
"all" already means "every status" on both count and list and rejecting
it would break the count/list parity this role exists to guarantee.
S3/S4 note: no OSS HTTP client exists yet to enforce capability-token
skew. A doc comment on CapIssuesCountScope in routes.go specifies the
required behavior once one lands: check issues.count.scope against the
cached handshake capabilities and refuse locally with a typed
ErrUnsupported{Capability} before sending any of the four new params to
an older server.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(count): S8 review follow-ups — refusal parity, exclude-status validation, doc fixes, parity tests
Addresses the Opus review's six required changes for S8 (bd count scope
fields):
1. BuildCountFilter now refuses ParentID+NoParent together as ErrValidation,
matching bd list's CLI refusal wording; wired through the role, the CLI,
and invalid_argument classification in internal/httpapi/reads.go.
2. Status:"all" is documented in DESIGN.txt as every status, matching List's
no-filter reading (count/list cardinality parity) — a coordinator decision
recorded in beads-design/DESIGN.txt, outside this worktree.
3. ExcludeStatus names are now validated against the workspace vocabulary
(built-in statuses plus workspace-custom ones); an unknown name is
ErrValidation instead of a silent no-op, since a typo here would overcount.
4. Fixed openapi.v0.yaml and issueops/reader.go doc claims about bd list
--parent's default tree-walk vs. the one-level role answer that bd count
--parent agrees with (confirmed by tracing list_show_filter_modes.go); fixed
an Oxford-comma nit in routes.go and the spec.
5. Added storage-level count == len(List) parity tests for ParentID, NoParent
and ExcludeTypes (List has no ExcludeStatus counterpart), plus wisp-child
and closed-child contract cases, across all three backends (dolt,
embeddeddolt, uow). CounterFixture gained a List hook for this.
6. Extended the routes.go skew note: gc's ErrCountUnsupported fallback to List
is now named explicitly, with a note that S3/S4 must add a skew test that
masks the token and asserts the fallback fires.
Also fixed RunCounterExcludeStatusNarrowsThePredicate's now-stale "unrecognized
status excludes nothing" assertion to expect ErrValidation instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(count): PR #7199 review follow-ups — exclude-status config load, ParentID doc swap
Addresses bee's REQUEST-CHANGES on gastownhall/beads#7199 (S8):
1. BLOCKER: storecounter.filter and uow.countFilter only loaded the
workspace list config when IncludeInfra was set, so BuildCountFilter's
ExcludeStatus validation refused a workspace's own custom status unless
the caller also passed the unrelated IncludeInfra flag. Both legs now
load the config when IncludeInfra OR len(ExcludeStatus) > 0, with
comments corrected to say so. Added leg-level regression tests (the
conformance fixture cannot drive a workspace-configured custom status)
on embeddeddolt and uow, reproducing the reviewer's CLI repro directly,
plus an HTTP-level probe in cmd/bd's real-Dolt proxied count test.
2. issueops.ReadyRequest.ParentID's comment had been overwritten with the
one-level direct-children wording that belongs to ListRequest.ParentID;
Ready actually walks all descendants via GetDescendantIDsInTx (GH#3396).
Restored the descendants comment on ReadyRequest.ParentID and moved the
one-level explanation to ListRequest.ParentID, which had none.
Verified: make api-check; dolt-server, embeddeddolt and uow Counter
contract legs (BEADS_TEST_DOLT_SERVER=local with a pinned dolt binary for
uow; Docker for the dolt-server leg); the new proxied HTTP exclude_status
probe (BEADS_TEST_PROXIED_SERVER=1).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* chore(wireshape): add the countIssues scope parameters to the wire-shape golden
#7182 now digests operation parameters. The four new issues:count parameters
(parent, no_parent, exclude_type, exclude_status) are additive entries, so no
wire_revision bump is needed; regenerated with gendigest.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(conformance): register the S8 count-scope cases with RunRoleContracts (adopt-pr #7199)
The PR adds nine RunCounter* contract cases to counter_contract.go and wires
them into the three in-tree TestCounterContract legs, but not into the
Counter row of roleContractCases. TestRoleContractCasesCoverEveryContractCase
derives the expected set from source, so it fails on the PR head, and an
external backend running RunRoleContracts would never see the new cases.
Register them in source-declaration order (after
RunCounterAnUnknownStatusMatchesNothing), which the same guard enforces.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(count): correct the S8 scope docs the review found wrong (adopt-pr #7199)
Comment and spec-description fixes only; no behavior change. Review-loop
iterations 1 and 2 of the #7199 relaunch.
- ListRequest.ParentID (issueops/reader.go) said "DIRECT children only
... the same one-level clause". The sqlbuild clause has two arms and
neither walks: the parent-child edge arm stops at one level, but the
dotted-prefix arm (`id LIKE CONCAT(?, '.%')` for rows with no
parent-child edge) reaches every edge-less dotted id at any depth, which
RunReaderListParentReachesEveryDescendantAndOnlyItsOwn pins with an
edge-less X.1.1. State both arms, and say the CLI tree view re-runs the
clause against the store once per level (findAllDescendants calls
SearchIssues, not the role). Document ListRequest.NoParent, which had no
doc. The contributor's ReadyRequest.ParentID text is kept; only its
cross-reference to this field changes from "one-level" to "non-walking".
- CountRequest.NoParent (issueops/counter.go) and the count flag comment
(cmd/bd/count.go) said NoParent counts rows with "neither" an edge nor a
dotted prefix. Its SQL checks only the edge table, so an edge-less X.1
is counted by both --parent X and --no-parent, as bd list lists it.
- RunCounterExcludeStatusNarrowsThePredicate's header said an
unrecognized name "excludes nothing rather than failing" while its body
asserts ErrValidation. The header now matches the body.
- The OpCountIssues entry in problem.go's operationCodes said the role has
"exactly one reachable refusal". It has three: an invalid metadata key,
an unrecognized exclude_status name, and parent with no_parent (named
no_parent), all classified by invalidFilterParam. The code set is
unchanged.
- BuildCountFilter's header said cfg is "only read under IncludeInfra".
It is also read to validate ExcludeStatus against the workspace's
custom statuses, which is why both callers load it when ExcludeStatus is
non-empty.
- The countIssues `parent` description in openapi.v0.yaml carried the
same one-level claim as ListRequest.ParentID; it now states both arms.
types.gen.go is regenerated (make api-gen); make api-check passes.
Review fixes (iteration 2), still comment and spec text only:
- The iteration-1 problem.go rewrite called all three count refusals
ErrValidation. Only the exclude_status and parent-with-no_parent
refusals wrap issueops.ErrValidation (internal/workapi/count.go). The
metadata-key refusal is ValidateMetadataFilters' plain fmt.Errorf
chain, so errors.Is(err, ErrValidation) is false for it; it reaches the
wire as a 400 only because invalidFilterParam matches message prefixes.
The comment now says that, so a later move to typed errors cannot trust
it and demote the metadata-key refusal to a 500. The sentinel itself is
not added here: ValidateMetadataFilters is shared with the list and
ready builders.
- invalidFilterParam's comment on the count rows pointed at the
metadata-key rows as "above"; they come after it in the switch.
- The countIssues `parent` description said the CLI tree mode walks
"every edge-linked descendant". findAllDescendants re-runs the full
two-arm predicate per level, so it also descends through edge-less
dotted ids; it now says "every descendant reachable through either
arm". types.gen.go is regenerated; make api-check 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>
* chore(wireshape): re-record the count scope params under the base's param digest (adopt-pr #7199)
The base branch (feat/wire-revision-signal, #7182 be1f0bad72) now digests
the effective style/explode of scalar query parameters. This PR's golden
entries for countIssues query:parent and query:no_parent were written by
the old algorithm, so after the base refresh TestWireShapeDigest reported
them as "changed without a wire_revision bump".
No bump is owed: all four count-scope entries (parent, no_parent,
exclude_type, exclude_status) are additions this PR introduces and are
absent from the base golden. golden.json was reset to the base copy and
regenerated with `go run ./internal/httpapi/wireshape/cmd/gendigest`. The
result is four pure additions against the base (+35/-0); parent and
no_parent gain "style": "form" and "explode": true, and wire_revision
stays 2.
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>
* ci: place the PR's new embedded counter test in the shard manifest
TestCounterExcludeStatusAcceptsAWorkspaceCustomStatusWithoutIncludeInfra,
added to internal/storage/embeddeddolt in f23bf5ddbf, is a new top-level
embedded storage test. The 15-shard block of
.github/scripts/embedded-storage-test-shards.txt must list every
discovered test exactly once. Without the entry,
TestStorageEmbeddedShardManifestGeneratorNotStale (scripts/) fails, both
on the reviewed head 89a387de6c and on the merge. CI never ran the check
on this PR: pr.yml runs only for PRs based on main, release/** or
hotfix/**, and this PR was based on feat/wire-revision-signal until the
retarget.
Generated with
`python3 scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration --write`.
The incremental write adds this one line, in shard 4, and moves no other
test.
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 Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
465 lines
21 KiB
Go
465 lines
21 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/workapi"
|
|
)
|
|
|
|
// recordingIssues captures the filter the reader built, which is the only way
|
|
// to see what a handler actually asked storage for. Everything else about a
|
|
// read is observable from the response; the FILTER is not, and the filter is
|
|
// where the drift this design exists to prevent would live.
|
|
type recordingIssues struct {
|
|
domain.IssueUseCase
|
|
|
|
mu sync.Mutex
|
|
ready []types.WorkFilter
|
|
search []types.IssueFilter
|
|
items []*types.IssueWithCounts
|
|
}
|
|
|
|
func (f *recordingIssues) GetReadyWorkWithCounts(_ context.Context, filter types.WorkFilter) (domain.SearchCountsPage, error) {
|
|
f.mu.Lock()
|
|
f.ready = append(f.ready, filter)
|
|
f.mu.Unlock()
|
|
return domain.SearchCountsPage{Items: f.items}, nil
|
|
}
|
|
|
|
func (f *recordingIssues) SearchIssuesWithCounts(_ context.Context, _ string, filter types.IssueFilter) (domain.SearchCountsPage, error) {
|
|
f.mu.Lock()
|
|
f.search = append(f.search, filter)
|
|
f.mu.Unlock()
|
|
return domain.SearchCountsPage{Items: f.items}, nil
|
|
}
|
|
|
|
// The ready surface's defer-wake sweep reaches this before the read; nothing
|
|
// is deferred in the fixture, so it reports a no-op sweep.
|
|
func (f *recordingIssues) WakeExpiredDefers(context.Context) (issues, wisps int, err error) {
|
|
return 0, 0, nil
|
|
}
|
|
|
|
func (f *recordingIssues) readyFilters() []types.WorkFilter {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return append([]types.WorkFilter(nil), f.ready...)
|
|
}
|
|
|
|
func (f *recordingIssues) searchFilters() []types.IssueFilter {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return append([]types.IssueFilter(nil), f.search...)
|
|
}
|
|
|
|
// emptyConfig is the workspace vocabulary a bare fixture has: no custom
|
|
// statuses, no custom types, no infra overrides. The list reader loads it
|
|
// through the unit of work before it builds a filter, so a read test that
|
|
// drives the list path has to answer it.
|
|
type emptyConfig struct{ domain.ConfigUseCase }
|
|
|
|
func (emptyConfig) GetCustomStatuses(context.Context) ([]types.CustomStatus, error) { return nil, nil }
|
|
func (emptyConfig) GetCustomTypes(context.Context) ([]string, error) { return nil, nil }
|
|
func (emptyConfig) GetInfraTypes(context.Context) (map[string]bool, error) { return nil, nil }
|
|
|
|
func newReadServer(t *testing.T, cfg Config) (*testServer, *recordingIssues) {
|
|
t.Helper()
|
|
rec := &recordingIssues{}
|
|
cfg.Provider = &fakeProvider{issues: &fakeIssues{}, readIssues: rec, readConfig: emptyConfig{}}
|
|
return newTestServer(t, cfg), rec
|
|
}
|
|
|
|
// TestReadyForwardsAnExplicitSortPolicy is the guard on the one default that
|
|
// changes the item SET rather than just its order.
|
|
//
|
|
// The storage layer maps an EMPTY sort policy to hybrid. A handler that
|
|
// forwarded an absent `sort` as "" would therefore serve hybrid while the
|
|
// frozen document still read `default: priority` — and hybrid demotes older
|
|
// high-priority work, so as soon as `limit` truncates, the page contains
|
|
// DIFFERENT ISSUES from the ones `bd ready` shows. The document tests pin the
|
|
// document; only this pins the handler.
|
|
//
|
|
// The wanted value is the LITERAL, not readySortDefault. Comparing the filter
|
|
// against the same constant the handler read would pass for every value that
|
|
// constant could take, including hybrid — the assertion would say only that
|
|
// the handler forwards its own default, which is not the property at risk.
|
|
// TestDefaultsMatchCLIFlags ties that literal to `bd ready --sort`'s
|
|
// registered default and to the frozen document, so all three move together or
|
|
// one of them fails.
|
|
func TestReadyForwardsAnExplicitSortPolicy(t *testing.T) {
|
|
ts, rec := newReadServer(t, Config{})
|
|
|
|
if resp := ts.get(t, "/v0/beads/ready"); resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200", resp.StatusCode)
|
|
}
|
|
filters := rec.readyFilters()
|
|
if len(filters) != 1 {
|
|
t.Fatalf("%d ready queries, want 1", len(filters))
|
|
}
|
|
if got := filters[0].SortPolicy; got != types.SortPolicy("priority") {
|
|
t.Errorf("SortPolicy = %q, want \"priority\" — an empty policy is the storage layer's hybrid fallback, and hybrid re-SELECTS the page once the limit truncates",
|
|
got)
|
|
}
|
|
// The shared limit default reaches storage too: the document states the
|
|
// number, the CLI flag registers the same constant, and this is where the
|
|
// server proves it uses that constant rather than a literal of its own.
|
|
if got, want := filters[0].Limit, workapi.DefaultReadyLimit; got != want {
|
|
t.Errorf("Limit = %d, want the shared default %d", got, want)
|
|
}
|
|
}
|
|
|
|
// TestReadySortIsValidatedAgainstTheDocumentedEnum: an unrecognized policy is a
|
|
// 400 rather than a silent fallback, because a silent fallback would answer a
|
|
// question the client did not ask.
|
|
func TestReadySortIsValidatedAgainstTheDocumentedEnum(t *testing.T) {
|
|
ts, rec := newReadServer(t, Config{})
|
|
|
|
resp := ts.get(t, "/v0/beads/ready?sort=newest")
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400", resp.StatusCode)
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["code"] != string(CodeInvalidArgument) || body["param"] != "sort" || body["reason"] != string(ReasonInvalidValue) {
|
|
t.Errorf("body = %v, want invalid_argument on param sort with reason invalid_value", body)
|
|
}
|
|
if n := len(rec.readyFilters()); n != 0 {
|
|
t.Errorf("%d ready queries ran; a refused request must not reach storage", n)
|
|
}
|
|
}
|
|
|
|
// TestABuilderRefusalIsTheDocumentedBadRequest drives every row of
|
|
// invalidFilterParam end to end, through the real builders.
|
|
//
|
|
// The mapping is prose matching on this repository's own error strings, which
|
|
// is only safe while something fails when one of those strings is reworded.
|
|
// Nothing did: the builders' golden files record successful filters and never
|
|
// see a message, so `invalid issue type ` in particular was pinned nowhere and
|
|
// a reworded builder would have quietly demoted `?type=bogus` from 400
|
|
// invalid_value to 500 internal.
|
|
//
|
|
// metadata_field and has_metadata_key are here for a second reason: their keys
|
|
// used to be checked only in the SQL builder, whose error arrives wrapped in
|
|
// the storage method's name and therefore cannot be classified at all. The
|
|
// frozen document says an invalid key is a 400; it was a 500.
|
|
func TestABuilderRefusalIsTheDocumentedBadRequest(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name string
|
|
path string
|
|
param string
|
|
}{
|
|
{"an issue type outside the workspace vocabulary", "/v0/beads/issues?type=bogus", "type"},
|
|
{"a status that is not a status", "/v0/beads/issues?status=bogus", "status"},
|
|
{"a metadata field key the query layer cannot spell", "/v0/beads/issues?metadata_field=1bad=x", "metadata_field"},
|
|
{"a has-metadata key the query layer cannot spell", "/v0/beads/issues?has_metadata_key=1bad", "has_metadata_key"},
|
|
{"a metadata field key on the ready surface", "/v0/beads/ready?metadata_field=1bad=x", "metadata_field"},
|
|
{"a has-metadata key on the ready surface", "/v0/beads/ready?has_metadata_key=1bad", "has_metadata_key"},
|
|
{"a metadata field key on the count surface", "/v0/beads/issues:count?metadata_field=1bad=x", "metadata_field"},
|
|
{"a has-metadata key on the count surface", "/v0/beads/issues:count?has_metadata_key=1bad", "has_metadata_key"},
|
|
{"an unknown exclude-status name on the count surface", "/v0/beads/issues:count?exclude_status=bogus", "exclude_status"},
|
|
{"parent and no_parent together on the count surface", "/v0/beads/issues:count?parent=bd-1&no_parent=true", "no_parent"},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
ts, _ := newReadServer(t, Config{})
|
|
resp := ts.get(t, tc.path)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("GET %s: status = %d, want 400", tc.path, resp.StatusCode)
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["code"] != string(CodeInvalidArgument) || body["param"] != tc.param || body["reason"] != string(ReasonInvalidValue) {
|
|
t.Errorf("GET %s: body = %v, want invalid_argument on param %s with reason invalid_value", tc.path, body, tc.param)
|
|
}
|
|
// The detail reflects the caller's own input back, which is what a
|
|
// 4xx detail is for — and is the half that stops being true if the
|
|
// builder's message moves.
|
|
if detail, _ := body["detail"].(string); detail == "" {
|
|
t.Errorf("GET %s: no detail; the builder's own message is the detail", tc.path)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestAnInvalidMetadataKeyNeverReachesStorage: the refusal is worth having only
|
|
// if it happens before the query runs. A key that reached the SQL builder came
|
|
// back as a 500 with the storage method's name wrapped around it.
|
|
func TestAnInvalidMetadataKeyNeverReachesStorage(t *testing.T) {
|
|
ts, rec := newReadServer(t, Config{})
|
|
if resp := ts.get(t, "/v0/beads/issues?metadata_field=1bad=x"); resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400", resp.StatusCode)
|
|
}
|
|
if n := len(rec.searchFilters()); n != 0 {
|
|
t.Errorf("%d list queries ran; the refusal must happen before the database is touched", n)
|
|
}
|
|
if n := len(rec.readyFilters()); n != 0 {
|
|
t.Errorf("%d ready queries ran; the refusal must happen before the database is touched", n)
|
|
}
|
|
}
|
|
|
|
// TestUnknownReadParameterIsRefusedByName: silently ignoring an unrecognized
|
|
// FILTER parameter WIDENS the result set, so a client one version ahead
|
|
// receives rows it believes it filtered out.
|
|
func TestUnknownReadParameterIsRefusedByName(t *testing.T) {
|
|
for _, path := range []string{"/v0/beads/ready?bogus=1", "/v0/beads/issues?bogus=1", "/v0/beads/issues/bd-1?bogus=1"} {
|
|
ts, _ := newReadServer(t, Config{})
|
|
resp := ts.get(t, path)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Errorf("GET %s: status = %d, want 400", path, resp.StatusCode)
|
|
continue
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["param"] != "bogus" || body["reason"] != string(ReasonUnknownParameter) {
|
|
t.Errorf("GET %s: body = %v, want param=bogus reason=unknown_parameter", path, body)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestAMalformedKnownParameterIsNotReportedAsVersionSkew: the two 400 reasons
|
|
// carry opposite client recoveries — unknown_parameter says "this server is
|
|
// older than you think, degrade", invalid_value says "send something else" —
|
|
// so a bad value on a parameter the server DOES know must not be reported as
|
|
// the former just because the request also has to be checked for the latter.
|
|
func TestAMalformedKnownParameterIsNotReportedAsVersionSkew(t *testing.T) {
|
|
ts, _ := newReadServer(t, Config{})
|
|
|
|
resp := ts.get(t, "/v0/beads/ready?limit=-1&bogus=1")
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400", resp.StatusCode)
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["param"] != "limit" || body["reason"] != string(ReasonInvalidValue) {
|
|
t.Errorf("body = %v, want the malformed known parameter reported first", body)
|
|
}
|
|
}
|
|
|
|
// TestUnlimitedReadsAreLoopbackOnly pins the one mode-dependent refusal: an
|
|
// unlimited read buffers the whole active set and its JSON encoding inside one
|
|
// shared process, which must not be reachable by arbitrary network peers.
|
|
func TestUnlimitedReadsAreLoopbackOnly(t *testing.T) {
|
|
t.Run("loopback allows it", func(t *testing.T) {
|
|
ts, rec := newReadServer(t, Config{})
|
|
if resp := ts.get(t, "/v0/beads/ready?limit=0"); resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200", resp.StatusCode)
|
|
}
|
|
filters := rec.readyFilters()
|
|
if len(filters) != 1 || filters[0].Limit != 0 {
|
|
t.Errorf("filters = %v, want one query with Limit 0 (unlimited passes through untouched)", filters)
|
|
}
|
|
})
|
|
|
|
t.Run("a non-loopback bind refuses it", func(t *testing.T) {
|
|
// InsecureNoAuth is what --allow-non-loopback now requires when no
|
|
// token file is configured. It is the posture under test here — the
|
|
// refusal being pinned is about the BIND, not about the credential.
|
|
ts, rec := newReadServer(t, Config{Addr: "127.0.0.1:0", AllowNonLoopback: true, InsecureNoAuth: true})
|
|
resp := ts.get(t, "/v0/beads/ready?limit=0")
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400", resp.StatusCode)
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["param"] != "limit" || body["reason"] != string(ReasonInvalidValue) {
|
|
t.Errorf("body = %v, want invalid_argument on param limit", body)
|
|
}
|
|
if n := len(rec.readyFilters()); n != 0 {
|
|
t.Errorf("%d queries ran; the refusal must happen before the database is touched", n)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestGetIssueRefusesAnImpossibleIDFromTheEdge: an id longer than the column,
|
|
// or one carrying a control character a percent-escape decoded to, names no row
|
|
// that can exist. Answering it from the edge costs nothing and tells the caller
|
|
// exactly what a read would have — and the SAME 404 a real miss gets, so a
|
|
// caller cannot map the server's notion of a well-formed id.
|
|
func TestGetIssueRefusesAnImpossibleIDFromTheEdge(t *testing.T) {
|
|
long := ""
|
|
for range types.MaxFieldLen + 1 {
|
|
long += "x"
|
|
}
|
|
for _, id := range []string{long, "bd-%01"} {
|
|
ts, rec := newReadServer(t, Config{})
|
|
resp := ts.get(t, "/v0/beads/issues/"+id)
|
|
if resp.StatusCode != http.StatusNotFound {
|
|
t.Errorf("GET issue %q: status = %d, want 404", id, resp.StatusCode)
|
|
continue
|
|
}
|
|
if body := decodeBody(t, resp); body["code"] != string(CodeNotFound) {
|
|
t.Errorf("GET issue %q: code = %v, want not_found", id, body["code"])
|
|
}
|
|
if n := len(rec.readyFilters()); n != 0 {
|
|
t.Errorf("GET issue %q reached storage", id)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestCursorRoundTrips: the token is opaque and server-private, and the only
|
|
// thing that invalidates one is a change to the encoding.
|
|
//
|
|
// The fixture's CreatedAt has to be NON-ZERO for this test to test anything.
|
|
// decodeCursor rejects a zero instant — an empty position is one of its
|
|
// documented failure modes — so a fixture left at the zero time made the
|
|
// happy-path assertions unreachable and the test passed while asserting
|
|
// nothing, encodeCursor broken outright included.
|
|
func TestCursorRoundTrips(t *testing.T) {
|
|
created := time.Now().UTC().Truncate(time.Second)
|
|
items := []*types.IssueWithCounts{{Issue: &types.Issue{ID: "bd-7", CreatedAt: created, Priority: 2}}}
|
|
|
|
// Both served orders, because a round trip that held for one and lost a
|
|
// member of the other's position would still page — into the wrong rows.
|
|
for _, order := range []listOrder{orderCreated, orderPriority} {
|
|
token := cursorFor(items, order)
|
|
if token == "" {
|
|
t.Fatalf("%s: cursorFor returned no token for a nonempty page", order)
|
|
}
|
|
pos, ok := decodeCursor(token, order)
|
|
if !ok {
|
|
t.Fatalf("%s: a token this server minted did not decode: %q", order, token)
|
|
}
|
|
if pos.ID != "bd-7" {
|
|
t.Errorf("%s: decoded id = %q, want bd-7", order, pos.ID)
|
|
}
|
|
if !pos.CreatedAt.Equal(created) {
|
|
t.Errorf("%s: decoded created_at = %s, want %s — the position is a keyset predicate, so a lossy instant skips or repeats rows", order, pos.CreatedAt, created)
|
|
}
|
|
if order == orderPriority {
|
|
if pos.Priority == nil {
|
|
t.Errorf("%s: decoded no priority; this order's position is (priority, created_at, id)", order)
|
|
} else if *pos.Priority != 2 {
|
|
t.Errorf("%s: decoded priority = %d, want 2", order, *pos.Priority)
|
|
}
|
|
} else if pos.Priority != nil {
|
|
t.Errorf("%s: decoded a priority (%d) it has no place for", order, *pos.Priority)
|
|
}
|
|
}
|
|
|
|
for _, bad := range []string{"", "v0.abc", "v1.!!!", "v1.", "v2.!!!", "v2.", "v3.abc", "not-a-cursor"} {
|
|
if _, ok := decodeCursor(bad, orderCreated); ok {
|
|
t.Errorf("decodeCursor(%q) succeeded; every unreadable token is the same client situation", bad)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestAReadRouteTimesTheUnitsOfWorkItsReaderOpens pins the one property of
|
|
// timedProvider.IssueReader that is invisible from reading it, and it is here
|
|
// because a reviewer proposed removing it: build the reader OVER THE WRAPPER,
|
|
// so every unit of work it opens goes through the wrapper's NewUOW and lands in
|
|
// this request's uow_ms.
|
|
//
|
|
// The tempting edit is `p.inner.IssueReader()` — "add the layer by recursion,
|
|
// the way every other decorator does". Recursion is right for a decorator whose
|
|
// layer is on the RESULT: telemetry's accessor recurses because it wraps the
|
|
// reader it gets back. This decorator's layer is on NewUOW, which only a reader
|
|
// holding THIS wrapper can reach, so recursion would hand back a reader bound
|
|
// to the untimed provider. It compiles, every other test still passes, and
|
|
// every read route reports uow_ms=0.000 from then on. So this asserts the
|
|
// NUMBER on the request line, which is the only place the difference shows.
|
|
func TestAReadRouteTimesTheUnitsOfWorkItsReaderOpens(t *testing.T) {
|
|
// A provider that takes a measurable moment to hand out a unit of work, so
|
|
// the field is checkable rather than a rounded zero either way.
|
|
provider := &fakeProvider{
|
|
issues: &fakeIssues{},
|
|
readIssues: &recordingIssues{},
|
|
readConfig: emptyConfig{},
|
|
delay: 5 * time.Millisecond,
|
|
}
|
|
ts := newTestServer(t, Config{Provider: provider})
|
|
|
|
if resp := ts.get(t, "/v0/beads/ready"); resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200", resp.StatusCode)
|
|
}
|
|
// Two units of work, both through the wrapper: the ready surface's
|
|
// defer-wake sweep, then the read span. A reader bound to the untimed
|
|
// provider would report zero.
|
|
if n := len(provider.openedUOWs()); n != 2 {
|
|
t.Fatalf("opened %d units of work, want 2 (defer-wake sweep + read span)", n)
|
|
}
|
|
|
|
line := findLogLine(t, ts.stderr.String(), "op="+OpListReadyWork)
|
|
if !strings.Contains(line, "uow_ms=") {
|
|
t.Fatalf("read request line has no uow_ms field:\n%s", line)
|
|
}
|
|
if strings.Contains(line, "uow_ms=0.000") {
|
|
t.Errorf("read request line reports no unit-of-work time though the provider took 5ms; the reader is bound to the untimed provider:\n%s", line)
|
|
}
|
|
}
|
|
|
|
// TestListForwardsTheEphemeralPlaneParameter is the handler half of
|
|
// ListRequest.IncludeEphemeral. The parameter decides which TABLES the query
|
|
// reads, and nothing in the response distinguishes a merged page from a durable
|
|
// one when the fixture holds no wisps — so the recorded filter is the only place
|
|
// a dropped plumb-through is visible, which is exactly why the filter is
|
|
// recorded at all.
|
|
//
|
|
// The third case is the one that stops the parameter from being wired to the
|
|
// wrong knob: `include_infra` also admits the plane, so a handler that mapped
|
|
// `include_ephemeral` onto IncludeInfra would pass the first two and silently
|
|
// widen the answer by four issue types.
|
|
func TestListForwardsTheEphemeralPlaneParameter(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name string
|
|
path string
|
|
wantSkipWisps bool
|
|
wantInfraType bool
|
|
}{
|
|
{"absent leaves the durable listing alone", "/v0/beads/issues", true, false},
|
|
{"include_ephemeral admits the plane and takes no type exclusion off", "/v0/beads/issues?include_ephemeral=true", false, false},
|
|
{"include_infra is the wider one", "/v0/beads/issues?include_infra=true", false, true},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
ts, rec := newReadServer(t, Config{})
|
|
if resp := ts.get(t, tc.path); resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("GET %s: status = %d, want 200", tc.path, resp.StatusCode)
|
|
}
|
|
filters := rec.searchFilters()
|
|
if len(filters) != 1 {
|
|
t.Fatalf("%d list queries, want 1", len(filters))
|
|
}
|
|
if got := filters[0].SkipWisps; got != tc.wantSkipWisps {
|
|
t.Errorf("SkipWisps = %v, want %v", got, tc.wantSkipWisps)
|
|
}
|
|
infraExcluded := false
|
|
for _, excluded := range filters[0].ExcludeTypes {
|
|
if excluded == types.IssueType("message") {
|
|
infraExcluded = true
|
|
}
|
|
}
|
|
if infraExcluded == tc.wantInfraType {
|
|
t.Errorf("ExcludeTypes = %v; the infra types are a TYPE exclusion and only include_infra takes it off", filters[0].ExcludeTypes)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestTheEphemeralPlaneParameterIsTheSkewSignal pins the version-skew half.
|
|
//
|
|
// A client that sends `include_ephemeral` to a server built before this
|
|
// parameter existed gets 400 `unknown_parameter` — the designed signal that the
|
|
// server is older than the client thinks, whose recovery is to degrade rather
|
|
// than retry. That behavior is the shared decoder's, so what has to hold HERE
|
|
// is the other side of it: this build must CONSUME the parameter, because a
|
|
// handler that stopped reading it would answer the durable set and report the
|
|
// request as unknown-parameter-free, which is indistinguishable from success.
|
|
func TestTheEphemeralPlaneParameterIsTheSkewSignal(t *testing.T) {
|
|
ts, _ := newReadServer(t, Config{})
|
|
|
|
resp := ts.get(t, "/v0/beads/issues?include_ephemeral=true")
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200: a parameter this build serves must not read as skew", resp.StatusCode)
|
|
}
|
|
|
|
// The neighbouring spelling a client might guess is NOT quietly accepted:
|
|
// an unknown parameter is refused by name, which is what makes the 200
|
|
// above mean something.
|
|
resp = ts.get(t, "/v0/beads/issues?include_ephemerals=true")
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400", resp.StatusCode)
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["param"] != "include_ephemerals" || body["reason"] != string(ReasonUnknownParameter) {
|
|
t.Errorf("body = %v, want param=include_ephemerals reason=unknown_parameter", body)
|
|
}
|
|
}
|