beads/internal/httpapi/related.go
Julian Knutsen 2a4b75b810
Publish GET /v0/beads/issues/{id}/related, the wire half of issueops.Relations (ga-81p36) (#5540)
Relations is one of the facade methods the ext-api-store audit lists with no
wire operation, and it is the one gc's infra-over-http read surface cannot do
without: `bd dep list`'s dependents view has no other direction-aware wire path,
because EdgeReader is outgoing-only. This is that operation. The role, its
contract and all three legs already exist; this slice wires them.

Spec first, then `make api-gen`, then the handler.

IT IS A SUB-RESOURCE OF THE ISSUE, and the argument is ELEMENT IDENTITY rather
than a claim about what the dependency collection answers with — getDependencyTree
answers hydrated TreeNodes, so "everything under /dependencies is about edges"
would be false and is not said. What decides it is narrower and checkable: the
rows here are the SAME pinned struct `GET /v0/beads/issues/{id}` already carries
under `dependencies` and `dependents`, so this operation is that pair,
standalone, direction-parameterized and type-filterable, and it belongs on the
resource whose members it publishes: `/v0/beads/issues/{id}/related`. The route table's first sub-resource: the
segment is a LITERAL after a single-segment wildcard, so pattern and specPath
agree and the claim row's exception does not apply. It collides with nothing —
`/v0/beads/issues/{id}` is a different whole path, which is what ServeMux
matches on, and the custom-method dispatcher is POST-only and one segment
shorter.

The consequence is stated in the document rather than left to be discovered:
the length of `items` is a NEIGHBOR count and not an EDGE count, because a
target that is an `external:` reference or another repository's id has no far
end here and is silently not a neighbor. The same edge IS a row on
`GET /v0/beads/dependencies`. That single observation is what separates the two
operations, and the proxied test asserts both halves of it against real Dolt.

THE ANCHOR-BOUND maxItems GATE DOES NOT APPLY. The facade signature is
single-anchor — one `RelatedRequest.ID`, not a slice — so there is no question
to bound at 100 the way the three dependency-collection reads bound theirs, and
`TestSpecDefaultsMatchSharedConstants`' three-op loop is deliberately untouched.
The other side of single-anchor is the 404: those reads report a miss per anchor
because failing would throw away the ids that were found, and here there is one
anchor and nothing to preserve. `getDependencyTree`'s operationCodes row,
unchanged, is this one's.

TWO-PLANE, AND BOTH HALVES ARE REAL. The neighbours are collected from
`dependencies` AND `wisp_dependencies` and hydrated from `issues` AND `wisps`,
so a durable anchor's `in` answer includes the wisps that depend on it and a
wisp id is a legal ANCHOR. Resolved from the bodies, not assumed, and pinned
against real Dolt: a durable anchor with one durable and one wisp dependent
answers two, and the wisp element carries `ephemeral` — which is what catches an
implementation that spanned the edge tables and hydrated one issue table.

VALIDATION STAYS IN THE ROLE, on `dependencies:count`'s terms rather than
`issues:count`'s. Relations has two bodies and every accessor calls
ValidateRelatedRequest, so its refusals are reachable over the wire: the handler
forwards `direction` raw and classifies on the sentinel, naming the parameter by
re-asking the validator's own questions in its own order. Only two of the
validator's three refusals are reachable — the path bound turns an unusable id
into the 404 a real miss gets, which is why there is no `id` arm in the picker
and why the tests say so.

Census: +1 spec path, +1 schema (`RelatedIssues`, unpinned for `EdgeCounts`'
reason — the element under it is the pinned one), +1 route row, +1 capability
(`issues.related`, hand-edited only in the document's vocabulary — `Capabilities()`
is derived and untouched), +1 `Op*` const, +1 `operationCodes` row, +1 required
`Config` field with its `sourceRoles`/`roleSourceNames`/accessor lines, +1 `bd
serve` binding. No code was minted: every problem code on the row is inherited.

THE "STEP WITH NO NUMBER" IS NOW A BUILD ERROR, and this is the first role to
measure that rather than assert it. #5539 landed the serveRoleSource subset while
this was in review, so `IssueRelations` joins that interface and both `cmd/bd`
stubs are COMPELLED to declare it — omitting either is

    *serveRolesStore does not implement serveRoleSource (missing method IssueRelations)

in the file that has to grow the method, checked both ways. Counter and
GraphCounter had to be FOUND, the second only by a full-package CI shard; this
one could not be missed. Both stub comments are rewritten to say so: the
promoted-method-on-a-nil-embed narrative is history now, not instruction, and on
the identity stub the surviving load-bearing fact is PLACEMENT — the accessor
sits at depth 1, shallower than serveStubRest's nil store, so it shadows the
promotion and the assertion can see it. Swept for a third stub site reaching this
path: serve_registered_backend_test.go reuses serveIdentityDoltStore and a real
embeddeddolt.Open, so there is none. A drive-by one-liner beside all that:
timedProvider gained the `uow.GraphCounterSource` compile-time assertion #5536's
accessor landed without.

One arm was DELETED after measurement. failRelatedErr shipped with an explicit
`storage.ErrNotFound` case, mutating it out left every case in the package green
— ClassifyError already carries that row, so the 404 travels through the one
shared mapping — and a green arm named for half the contract is worse than no
arm. The ErrValidation arm is the opposite: deleting it turns every refusal on
this operation into a generic 500, and both measurements are recorded at the
site.

Evidence, six mutations. The picker's arms collapsed reddens the four direction
cases and nothing else; the ErrValidation arm deleted reddens all five refusal
cases; `items` as a nil slice reddens the empty-array case; the path bound
dropped reddens the impossible-anchor case; the dependents read narrowed to
`dependencies` and the hydration narrowed to `issues` each redden the two-plane
case against real Dolt at 1-of-2. A seventh, a json tag on types.Issue.RowVersion,
reddens the no-revision case — and TestWireTagBijection too, which the test now
says out loud.

Rebased onto #5539 (06b0dffb2). Fable review: APPROVE, zero blocking findings
— the reviewer re-ran every mutation, probed the router live (an issue literally
named "related" does not shadow the detail read), and confirmed the
environmental-failure set name-identical to pristine main. Its one INFO, the
overclaimed placement rationale, is the paragraph rewritten above.

Gates: `make api-check` a no-op, `go build ./...`, `go vet ./...`, `gofmt -l`
clean, `internal/httpapi` + `internal/telemetry` + `internal/storage` +
`internal/storage/uow` (the nine-minute parity run) green, and
`BEADS_TEST_PROXIED_SERVER=1 CGO_ENABLED=1 go test ./cmd/bd/ -run
TestProxiedServerServeRelatedIssues` green against real Dolt in five cases. The
pre-commit hook's `go run golangci-lint@v2.10.1` downgrades the toolchain to
go1.25 and refuses this go1.26.5 module outright (ga-2ltro.13), so the
CI-pinned binary was run by hand — `golangci-lint run --new-from-rev=origin/main`,
0 issues — and this commits with --no-verify citing that bead.

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 05:23:30 -07:00

129 lines
5.6 KiB
Go

package httpapi
import (
"errors"
"net/http"
"strings"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// handleListRelatedIssues answers GET /v0/beads/issues/{id}/related.
//
// Everything below the wire is on issueops.Relations: which planes the anchor is
// resolved against, that an anchor naming nothing is ErrNotFound rather than an
// empty page, which dependency tables the neighbors are collected from, that an
// edge whose far end this database holds no row for is silently not a neighbor,
// the type filter, and the pinned order. What stays here is transport — the path
// id's bound, two parameters, and the wire envelope.
//
// THE DIRECTION IS NOT VALIDATED HERE, deliberately, and it is the same call
// GET /v0/beads/dependencies:count made. It is the role's closed vocabulary and
// ValidateRelatedRequest refuses the zero value outright, so every accessor
// raises it and refusing at the edge would be a second definition of one rule.
// The opposite choice belongs where NO role refusal is reachable — the
// issues:count group_by — and this is not that case.
func (s *Server) handleListRelatedIssues(w http.ResponseWriter, r *http.Request) {
q := newQuery(r.URL.Query())
req := issueops.RelatedRequest{Direction: issueops.RelationDirection(q.str("direction"))}
for _, depType := range q.list("type") {
req.Types = append(req.Types, types.DependencyType(depType))
}
// Before the id bound, which is handleGetIssue's order and for its reason: a
// refused query string is a 400 that names what to fix, and deciding the id
// first would answer it with a 404 instead.
if !s.acceptQuery(w, r, q) {
return
}
id := r.PathValue("id")
// The id is bounded HERE, before the request buys a concurrency slot and a
// database round trip, exactly as handleGetIssue bounds its own. The column
// is VARCHAR(255) and the document calls this an exact canonical id, so a
// longer one — or one carrying a control character, which a percent-escape
// in the path decodes to — names no row that can exist. The refusal is the
// SAME 404 a real miss gets: a distinct answer would let a caller map this
// server's notion of a well-formed id, and there is nothing to learn from it.
//
// It is also what makes ValidateRelatedRequest's empty-id refusal unreachable
// over this wire, which failRelatedErr relies on when it picks a parameter.
if id == "" || types.CheckFieldLen("id", id) != nil || strings.ContainsFunc(id, isControlChar) {
s.fail(w, r, NotFound())
return
}
req.ID = id
rel, err := s.relations(r)
if err != nil {
s.failErr(w, r, err)
return
}
items, err := rel.Related(r.Context(), req)
if err != nil {
s.failRelatedErr(w, r, err, req)
return
}
writeJSON(w, apigen.RelatedIssues{Items: wireRelated(items)})
}
// failRelatedErr answers a failed neighbor read. The role's
// request-validation refusals are the caller's own input and reach the client
// as the 400 they are; everything else keeps going through the one mapping in
// problem.go — the absent anchor included.
//
// THAT LAST CLAUSE IS THE ONE WORTH READING, because this operation's 404 is
// half its contract and there is no arm here that produces it. ClassifyError
// already carries a storage.ErrNotFound row, so the role's miss reaches the wire
// as a 404 through the shared mapping, and an arm for it here would be a second
// spelling of one rule. It was written, mutated out and watched to stay green
// on every case in this package — including the one named for the miss — which
// is what says it was redundant rather than untested.
//
// The arm that is NOT redundant is the one below: neither storage leg wraps
// ErrValidation in anything the shared mapping recognizes, so deleting it turns
// every refusal on this operation into a generic 500. Mutation-verified the
// same way, in the opposite direction.
//
// The 400 names `direction` or `type` rather than always naming the same
// parameter, because `param` is what a client dispatches on and the two have
// different recoveries. Which one comes from the REQUEST the handler still
// holds, asked in ValidateRelatedRequest's own order: only a value outside the
// closed set can have produced a direction refusal, and the id — which that
// validator checks FIRST — cannot have produced one at all, because the path
// bound above already turned an unusable id into a 404.
func (s *Server) failRelatedErr(w http.ResponseWriter, r *http.Request, err error, req issueops.RelatedRequest) {
if !errors.Is(err, issueops.ErrValidation) {
s.failErr(w, r, err)
return
}
param := "type"
if req.Direction != issueops.RelationOut && req.Direction != issueops.RelationIn {
param = "direction"
}
requestInfo(r.Context()).refuse(param)
s.fail(w, r, InvalidArgument(param, ReasonInvalidValue, err.Error()))
}
// wireRelated projects the role's neighbor list onto the generated envelope's
// element type, which is an ALIAS of types.IssueWithDependencyMetadata — the
// same struct `bd show --json` marshals under `dependencies` and `dependents` —
// so this dereferences pointers and does nothing else. There is no second wire
// struct here and there must never be one.
//
// It exists for the one thing that is not free: the document says `items` is an
// empty array and never null. Making that guarantee here means the wire promise
// does not depend on the role keeping its own.
func wireRelated(items []*issueops.RelatedIssue) []apigen.IssueWithDependencyMetadata {
out := make([]apigen.IssueWithDependencyMetadata, 0, len(items))
for _, item := range items {
if item == nil {
continue
}
out = append(out, *item)
}
return out
}