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>
This commit is contained in:
Julian Knutsen 2026-08-10 05:23:30 -07:00 • committed by GitHub
commit 2a4b75b810
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 1329 additions and 9 deletions

View file

@ -308,6 +308,7 @@ func runServe() error {
CycleDetector: roles.cycles,
EdgeReader: roles.edges,
GraphCounter: roles.edgeCounter,
Relations: roles.relations,
BlockingAnnotator: roles.blocking,
TreeWalker: roles.tree,
ReadyCounter: roles.readyCounter,
@ -648,6 +649,7 @@ type serveRoleSource interface {
CycleDetector() (issueops.CycleDetector, error)
EdgeReader() (issueops.EdgeReader, error)
GraphCounter() (issueops.GraphCounter, error)
IssueRelations() (issueops.Relations, error)
BlockingAnnotator() (issueops.BlockingAnnotator, error)
TreeWalker() (issueops.TreeWalker, error)
ReadyCounter() (issueops.ReadyCounter, error)
@ -712,6 +714,7 @@ func serveIssueRoles(src serveRoleSource, journalEnabled bool) (serveRoles, erro
{"cycle detector", func() (err error) { roles.cycles, err = src.CycleDetector(); return }},
{"edge reader", func() (err error) { roles.edges, err = src.EdgeReader(); return }},
{"graph counter", func() (err error) { roles.edgeCounter, err = src.GraphCounter(); return }},
{"issue relations", func() (err error) { roles.relations, err = src.IssueRelations(); return }},
{"blocking annotator", func() (err error) { roles.blocking, err = src.BlockingAnnotator(); return }},
{"tree walker", func() (err error) { roles.tree, err = src.TreeWalker(); return }},
{"ready counter", func() (err error) { roles.readyCounter, err = src.ReadyCounter(); return }},
@ -798,6 +801,7 @@ type serveRoles struct {
cycles issueops.CycleDetector
edges issueops.EdgeReader
edgeCounter issueops.GraphCounter
relations issueops.Relations
blocking issueops.BlockingAnnotator
tree issueops.TreeWalker
readyCounter issueops.ReadyCounter

View file

@ -0,0 +1,290 @@
//go:build cgo
package main
import (
"encoding/json"
"io"
"net/http"
"slices"
"testing"
)
// End-to-end for the neighbor read, against real Dolt through a real
// `bd serve` subprocess.
//
// The pure tests in internal/httpapi cover the wire edge on a fake role — the
// parameter projection, the envelope, the path bound and the two refusals. What
// only this level can prove is what the ROWS are, and on this operation that is
// most of the contract:
//
// - the two directions really are the INVERSE graph of each other, which is
// the whole reason `direction` is required rather than defaulted;
// - the read really SPANS BOTH PLANES, in both halves — the neighbors are
// collected from `dependencies` AND `wisp_dependencies`, and they are
// hydrated from the `issues` AND `wisps` tables. A read that touched one of
// each would answer a shorter list that looks entirely plausible, and no
// fake can be asked about two tables;
// - a wisp is a legal ANCHOR, not just a legal neighbor;
// - an edge whose far end this database holds no row for is not a neighbor,
// while the same edge IS a row on `GET /v0/beads/dependencies` — the one
// observation that separates the two operations;
// - an id that names nothing is a 404 here, where the batched reads report it
// in the body.
//
// Every case scopes itself to issues this test creates, so the lists are exact
// whatever else the workspace holds.
// relatedNeighbors asks the server for one anchor's neighbors and returns the
// status and the decoded elements.
func (sp *serveProcess) relatedNeighbors(t *testing.T, id, query string) (int, []map[string]any) {
t.Helper()
resp, err := sp.client.Get(sp.url("/v0/beads/issues/" + id + "/related" + query))
if err != nil {
t.Fatalf("GET issues/%s/related%s: %v\nstderr:\n%s", id, query, err, sp.stderr.String())
}
defer func() { _ = resp.Body.Close() }()
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read related body: %v", err)
}
if resp.StatusCode != http.StatusOK {
return resp.StatusCode, nil
}
var body struct {
Items []map[string]any `json:"items"`
}
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("decode related body %q: %v", raw, err)
}
if body.Items == nil {
t.Errorf("GET issues/%s/related%s returned a null `items`; the document promises an array", id, query)
}
return resp.StatusCode, body.Items
}
// relatedIDs is the neighbor ids in the order the server answered, which is the
// order the role pins.
func (sp *serveProcess) relatedIDs(t *testing.T, id, query string) []string {
t.Helper()
status, items := sp.relatedNeighbors(t, id, query)
if status != http.StatusOK {
t.Fatalf("related %s%s: status = %d, want 200", id, query, status)
}
out := make([]string, 0, len(items))
for i, item := range items {
got, ok := item["id"].(string)
if !ok {
t.Fatalf("related %s: item %d has no id: %#v", id, i, item)
}
out = append(out, got)
}
return out
}
func equalIDs(got, want []string) bool {
if len(got) != len(want) {
return false
}
for i := range got {
if got[i] != want[i] {
return false
}
}
return true
}
func TestProxiedServerServeRelatedIssues(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := newSharedProxiedProject(t, bd, "srvrelated")
sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir))
// THE TWO DIRECTIONS ARE THE INVERSE GRAPH, and this is the shape that shows
// it: a hub that depends on two issues and is depended on by three, so out
// and in are disjoint sets of different sizes and no handler that answered
// the wrong one could pass by coincidence. A symmetric fixture would have
// made the required `direction` parameter unfalsifiable.
t.Run("out and in answer disjoint neighbor sets", func(t *testing.T) {
hub := bdProxiedCreate(t, bd, p.dir, "the hub", "-p", "2")
var dependsOn, dependents []string
for range 2 {
dependsOn = append(dependsOn, bdProxiedCreate(t, bd, p.dir, "a dependency", "-p", "2").ID)
}
for range 3 {
dependents = append(dependents, bdProxiedCreate(t, bd, p.dir, "a dependent", "-p", "2").ID)
}
// THE EDGES ARE SEEDED IN DESCENDING NEIGHBOR ID, which is what makes
// the order assertion below falsifiable. bd mints ids from a hash rather
// than a counter, so creation order and id order are unrelated — an
// implementation answering in insertion order would coincide with the
// pinned one about half the time on a two-element fixture. Sorting the
// expectation and inserting against it removes the coin flip.
slices.Sort(dependsOn)
slices.Sort(dependents)
for _, target := range slices.Backward(dependsOn) {
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", hub.ID, target); err != nil {
t.Fatalf("dep add %s -> %s: %v\n%s", hub.ID, target, err, out)
}
}
for _, source := range slices.Backward(dependents) {
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", source, hub.ID); err != nil {
t.Fatalf("dep add %s -> %s: %v\n%s", source, hub.ID, err, out)
}
}
// ASCENDING BY NEIGHBOR ID, which is the order the role pins and the
// reverse of the order these edges were written in.
if got := sp.relatedIDs(t, hub.ID, "?direction=out"); !equalIDs(got, dependsOn) {
t.Errorf("out = %v, want %v — the issues the anchor DEPENDS ON, ascending by id", got, dependsOn)
}
if got := sp.relatedIDs(t, hub.ID, "?direction=in"); !equalIDs(got, dependents) {
t.Errorf("in = %v, want %v — the issues that DEPEND ON the anchor, ascending by id", got, dependents)
}
// EACH ROW CARRIES ITS EDGE TYPE, which is the one member this element
// adds to a plain issue and the reason the role is not a filtered
// listing.
_, items := sp.relatedNeighbors(t, hub.ID, "?direction=out")
for i, item := range items {
if item["dependency_type"] != "blocks" {
t.Errorf("out item %d dependency_type = %#v, want the stored edge type", i, item["dependency_type"])
}
}
// The type filter narrows EDGES and never the anchor: the hub's edges
// are all `blocks`, so a filter for a type it has none of leaves the
// anchor found with an empty list rather than answering 404.
status, filtered := sp.relatedNeighbors(t, hub.ID, "?direction=out&type=discovered-from")
if status != http.StatusOK {
t.Fatalf("a type filter matching nothing: status = %d, want 200 — the filter narrows edges, not anchors", status)
}
if len(filtered) != 0 {
t.Errorf("a type filter matching nothing returned %d neighbors, want none", len(filtered))
}
})
// THE TWO PLANES, in BOTH halves, and this is the case a one-plane
// implementation fails. An edge is routed to `dependencies` or
// `wisp_dependencies` by the plane its SOURCE sits on, so a durable issue
// depended on by a wisp has that inbound edge in the OTHER table — and the
// neighbor itself lives in the OTHER issue table, so answering it also
// requires hydrating from `wisps`.
//
// The `ephemeral` member is what proves the second half over the wire. A read
// that collected both edge tables but hydrated only `issues` would answer the
// durable dependent and silently drop the wisp, which is a shorter list with
// nothing wrong-looking in it.
t.Run("the neighbors span both planes", func(t *testing.T) {
durable := bdProxiedCreate(t, bd, p.dir, "a durable anchor", "-p", "2")
durableDependent := bdProxiedCreate(t, bd, p.dir, "a durable dependent", "-p", "2")
wisp := bdProxiedCreate(t, bd, p.dir, "an ephemeral dependent", "-p", "2",
"--ephemeral", "--wisp-type", "heartbeat")
for _, source := range []string{durableDependent.ID, wisp.ID} {
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", source, durable.ID); err != nil {
t.Fatalf("dep add %s -> %s: %v\n%s", source, durable.ID, err, out)
}
}
status, items := sp.relatedNeighbors(t, durable.ID, "?direction=in")
if status != http.StatusOK {
t.Fatalf("status = %d, want 200", status)
}
if len(items) != 2 {
t.Fatalf("%d inbound neighbors, want 2 — one from `dependencies` and one from `wisp_dependencies`: %v", len(items), items)
}
seen := map[string]bool{}
for _, item := range items {
id, _ := item["id"].(string)
seen[id] = true
if id == wisp.ID {
// Hydrated from the WISPS table, which is the half that would
// still be missing if only the edge read spanned both planes.
if ephemeral, _ := item["ephemeral"].(bool); !ephemeral {
t.Errorf("the wisp neighbor came back without `ephemeral`; it was not hydrated from the ephemeral plane: %#v", item)
}
}
}
if !seen[durableDependent.ID] || !seen[wisp.ID] {
t.Errorf("inbound neighbors = %v, want both %s (durable) and %s (wisp)", items, durableDependent.ID, wisp.ID)
}
// A WISP IS A LEGAL ANCHOR TOO. The anchor probe reads both planes, so an
// ephemeral id resolves rather than 404ing, and its own outbound edge
// reaches the durable issue it depends on.
if got := sp.relatedIDs(t, wisp.ID, "?direction=out"); !equalIDs(got, []string{durable.ID}) {
t.Errorf("the wisp anchor's out = %v, want %v — an ephemeral id is an anchor, not a miss", got, []string{durable.ID})
}
})
// AN EDGE WITH NO FAR END IS NOT A NEIGHBOR, and it IS a row next door.
// This is the single observation that separates this operation from
// `GET /v0/beads/dependencies`, and it is why the length of `items` is a
// neighbor count rather than an edge count.
t.Run("an external target is a row next door and no neighbor here", func(t *testing.T) {
anchor := bdProxiedCreate(t, bd, p.dir, "an anchor with a dangling edge", "-p", "2")
resolvable := bdProxiedCreate(t, bd, p.dir, "a real dependency", "-p", "2")
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", anchor.ID, resolvable.ID); err != nil {
t.Fatalf("dep add: %v\n%s", err, out)
}
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", anchor.ID, "external:jira:JIRA-4141"); err != nil {
t.Fatalf("dep add external: %v\n%s", err, out)
}
if got := sp.relatedIDs(t, anchor.ID, "?direction=out"); !equalIDs(got, []string{resolvable.ID}) {
t.Errorf("out = %v, want only %s — an edge with no far end in this database is not a neighbor", got, resolvable.ID)
}
// The same graph, read as rows: both edges are there, so the difference
// is this operation's and not the fixture's.
if rows := len(sp.storedEdges(t, anchor.ID)); rows != 2 {
t.Errorf("GET /v0/beads/dependencies returned %d rows, want 2 — the dangling edge is stored", rows)
}
})
// AN ABSENT ANCHOR IS A 404, which is where this operation parts company with
// every batched read on this surface: there is one anchor, so there is no
// other answer to preserve by reporting the miss in the body — and an empty
// neighbor list is the common case, so a typo answered with one would never
// surface.
t.Run("an absent anchor is refused and an empty one is not", func(t *testing.T) {
lonely := bdProxiedCreate(t, bd, p.dir, "an issue with no neighbors", "-p", "2")
status, items := sp.relatedNeighbors(t, lonely.ID, "?direction=in")
if status != http.StatusOK {
t.Fatalf("an issue with no neighbors: status = %d, want 200", status)
}
if len(items) != 0 {
t.Errorf("an issue with no neighbors returned %d, want an empty list", len(items))
}
if status, _ := sp.relatedNeighbors(t, "bd-nosuchbead", "?direction=in"); status != http.StatusNotFound {
t.Errorf("an id that names nothing: status = %d, want 404", status)
}
})
// THE ROLE'S REFUSAL, over the wire, with the parameter named. `direction`
// has no default and the role refuses its zero value, so an omitted one is a
// 400 rather than a walk in some direction the caller did not choose.
t.Run("a missing direction is refused by name", func(t *testing.T) {
anchor := bdProxiedCreate(t, bd, p.dir, "an anchor", "-p", "2")
resp, err := sp.client.Get(sp.url("/v0/beads/issues/" + anchor.ID + "/related"))
if err != nil {
t.Fatalf("GET: %v", err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("no direction: status = %d, want 400: %s", resp.StatusCode, raw)
}
var problem map[string]any
if err := json.Unmarshal(raw, &problem); err != nil {
t.Fatalf("decode problem %q: %v", raw, err)
}
if problem["code"] != "invalid_argument" || problem["param"] != "direction" {
t.Errorf("problem = %v, want invalid_argument on param direction", problem)
}
})
}

View file

@ -105,6 +105,7 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) {
metadataCAS: &serveStubMetadataCAS{},
counter: &serveStubCounter{},
edgeCounter: &serveStubGraphCounter{},
relations: &serveStubRelations{},
inner: inner,
}}
}
@ -354,6 +355,7 @@ type serveRolesStore struct {
metadataCAS *serveStubMetadataCAS
counter *serveStubCounter
edgeCounter *serveStubGraphCounter
relations *serveStubRelations
inner storage.DoltStorage
}
@ -455,6 +457,31 @@ func (s *serveRolesStore) Counter() (issueops.Counter, error) { return s.counter
// moment the binding landed.
func (s *serveRolesStore) GraphCounter() (issueops.GraphCounter, error) { return s.edgeCounter, nil }
// IssueRelations is the FIRST role added to serveIssueRoles since this type
// stopped embedding a nil store, and it is worth recording what that changed —
// because the two comments above it describe the old regime and are now history
// rather than instruction.
//
// Counter and GraphCounter had to be FOUND. Neither is wrapped by the hook
// decorator (both are reads, so their decorators recurse), so neither was
// noticed until `bd serve` began binding it — GraphCounter on a full-package CI
// shard, because no -run pattern anyone reaches for names this test.
//
// This one could not be missed. serveRoleSource names the accessor, the
// assertion above requires it, and omitting it is `*serveRolesStore does not
// implement serveRoleSource (missing method IssueRelations)` at build time, in
// this file, naming the method. Which is the whole return on #5539 landing
// first, measured on the next role rather than asserted about it.
func (s *serveRolesStore) IssueRelations() (issueops.Relations, error) { return s.relations, nil }
// serveStubRelations is the neighbor role's stand-in, ErrUnsupported like every
// stub here.
type serveStubRelations struct{}
func (*serveStubRelations) Related(context.Context, issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
return nil, errors.ErrUnsupported
}
// serveStubGraphCounter is the edge-count role's stand-in, ErrUnsupported like
// every stub here.
type serveStubGraphCounter struct{}

View file

@ -229,6 +229,21 @@ func (*serveIdentityStore) EdgeReader() (issueops.EdgeReader, error) { return se
func (*serveIdentityStore) GraphCounter() (issueops.GraphCounter, error) {
return serveIdentityRole{}, nil
}
// IssueRelations is the first role added to serveIssueRoles since this stub
// stopped embedding a nil store, so the comment above it is now a record of the
// old regime rather than a warning about this one: GraphCounter had to be found
// by a CI shard, and this had to be declared before the package would build,
// with `missing method IssueRelations` naming it.
//
// It is declared HERE, at depth 1, and that placement is the load-bearing half.
// serveIdentityDoltStore embeds this type shallower than serveStubRest's nil
// store, so a role declared here shadows the promotion; one declared on the
// wrapper instead would satisfy the compiler and leave the assertion below
// unable to see it.
func (*serveIdentityStore) IssueRelations() (issueops.Relations, error) {
return serveIdentityRole{}, nil
}
func (*serveIdentityStore) BlockingAnnotator() (issueops.BlockingAnnotator, error) {
return serveIdentityRole{}, nil
}
@ -271,6 +286,7 @@ type serveIdentityRole struct {
issueops.CycleDetector
issueops.EdgeReader
issueops.GraphCounter
issueops.Relations
issueops.BlockingAnnotator
issueops.TreeWalker
issueops.ReadyCounter

View file

@ -120,16 +120,34 @@ func (e GetDependencyTreeParamsDirection) Valid() bool {
// Defines values for CountDependencyEdgesParamsDirection.
const (
In CountDependencyEdgesParamsDirection = "in"
Out CountDependencyEdgesParamsDirection = "out"
CountDependencyEdgesParamsDirectionIn CountDependencyEdgesParamsDirection = "in"
CountDependencyEdgesParamsDirectionOut CountDependencyEdgesParamsDirection = "out"
)
// Valid indicates whether the value is a known member of the CountDependencyEdgesParamsDirection enum.
func (e CountDependencyEdgesParamsDirection) Valid() bool {
switch e {
case In:
case CountDependencyEdgesParamsDirectionIn:
return true
case Out:
case CountDependencyEdgesParamsDirectionOut:
return true
default:
return false
}
}
// Defines values for ListRelatedIssuesParamsDirection.
const (
ListRelatedIssuesParamsDirectionIn ListRelatedIssuesParamsDirection = "in"
ListRelatedIssuesParamsDirectionOut ListRelatedIssuesParamsDirection = "out"
)
// Valid indicates whether the value is a known member of the ListRelatedIssuesParamsDirection enum.
func (e ListRelatedIssuesParamsDirection) Valid() bool {
switch e {
case ListRelatedIssuesParamsDirectionIn:
return true
case ListRelatedIssuesParamsDirectionOut:
return true
default:
return false
@ -935,7 +953,7 @@ type ContextResponse struct {
// BeadsDir Absolute path of the served workspace's `.beads` directory. A host path, kept because it is the single-workspace server's only workspace-identity handshake; disclosing it to network peers is part of what an operator accepts when binding beyond loopback.
BeadsDir string `json:"beads_dir"`
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.create`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the one behavior token is `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the one behavior token is `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
//
// THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive.
Capabilities []string `json:"capabilities"`
@ -1546,6 +1564,20 @@ type Ref struct {
Key *string `json:"key,omitempty"`
}
// RelatedIssues One issue's neighbors — the body of `GET /v0/beads/issues/{id}/related`. It is NOT a page: this operation has no limit and no cursor, and it names ONE anchor, so there is nothing for a `has_more` to be about.
//
// There is no `missing` beside `items`, unlike `DependencyEdges`. That member exists because a batch cannot report an absent anchor any other way without discarding the anchors it did find; here the single absent anchor is a 404.
//
// It is NOT `x-go-type`-pinned, for `EdgeCounts`' reason: there is no canonical Go struct whose JSON encoding is this envelope. The role answers with a bare slice of `issueops.RelatedIssue`, and THAT element is pinned — see `IssueWithDependencyMetadata`.
type RelatedIssues struct {
// Items The neighbors, ascending by id with the edge type breaking a tie. Empty array (never null) when this issue has none in the requested direction, or when the `type` filter rejected every edge.
//
// Each element is a full issue plus `dependency_type`, the type of the edge that led to it — the same element `GET /v0/beads/issues/{id}` carries under `dependencies` and `dependents`, so the two surfaces are one compatibility domain.
//
// AN EDGE WITH NO FAR END IN THIS DATABASE CONTRIBUTES NOTHING here: an `external:` reference, an id in another repository's namespace and an id whose issue was deleted out from under its edges are all silently absent, with no placeholder row and no error. The length of this array is a NEIGHBOR count, never an edge count.
Items []IssueWithDependencyMetadata `json:"items"`
}
// ReleaseIssueRequest defines model for ReleaseIssueRequest.
type ReleaseIssueRequest struct {
// Actor Who is releasing the claim. `ClaimRequest.actor`'s rules exactly: the server trims it, then refuses an empty result, anything longer than 256 BYTES (the `maxLength` above counts characters — the byte limit is the binding one), and any control character including newline. The value reaches the event the release records and the storage commit message, so an unvalidated newline would forge audit-trail lines.
@ -2072,6 +2104,26 @@ type GetIssueParams struct {
IncludeDependents *bool `form:"include_dependents,omitempty" json:"include_dependents,omitempty"`
}
// ListRelatedIssuesParams defines parameters for ListRelatedIssues.
type ListRelatedIssuesParams struct {
// Direction Which way this issue's edges are walked. `out` answers the issues it DEPENDS ON — the `dependencies` member of `GET /v0/beads/issues/{id}`. `in` answers the issues that depend on it — that read's `dependents` member.
//
// IT IS REQUIRED AND HAS NO DEFAULT, on `GET /v0/beads/dependencies:count`'s terms and for the reason `issueops.RelationDirection` gives: the two answers have the same shape and the same member names, so a caller handed the inverse graph has nothing to notice. An absent or unrecognized value is a 400 `invalid_argument` with `param: "direction"`, never a walk in some default direction.
//
// The vocabulary is CLOSED — unlike `type` below — because it is a property of the edge's shape rather than of a workspace's configuration.
Direction ListRelatedIssuesParamsDirection `form:"direction" json:"direction"`
// Type Edge types to include. Repeat the parameter. Empty means every type.
//
// `GET /v0/beads/dependencies`'s `type` exactly: the vocabulary is OPEN, so an unrecognized value is not an error and simply matches no edge, while a value no edge could ever carry — empty, or longer than the column — is a 400 `invalid_argument` with `param: "type"`.
//
// The filter narrows EDGES, never the anchor. An issue whose every edge it rejects is answered with an empty `items` and not with a 404, which is a different fact from an id that names nothing.
Type *[]string `form:"type,omitempty" json:"type,omitempty"`
}
// ListRelatedIssuesParamsDirection defines parameters for ListRelatedIssues.
type ListRelatedIssuesParamsDirection string
// ClaimNextIssueParams defines parameters for ClaimNextIssue.
type ClaimNextIssueParams struct {
// Assignee Only issues assigned to this actor.

View file

@ -319,6 +319,8 @@ var (
_ uow.StatsReporterSource = timedProvider{}
_ uow.CycleDetectorSource = timedProvider{}
_ uow.EdgeReaderSource = timedProvider{}
_ uow.GraphCounterSource = timedProvider{}
_ uow.RelationsSource = timedProvider{}
_ uow.BlockingAnnotatorSource = timedProvider{}
_ uow.TreeWalkerSource = timedProvider{}
_ uow.ReadyCounterSource = timedProvider{}
@ -435,6 +437,14 @@ func (p timedProvider) GraphCounter() (issueops.GraphCounter, error) {
return uow.NewGraphCounter(p)
}
// IssueRelations builds the single-anchor neighbor role OVER THIS WRAPPER, for
// the same reason and with the same hazard as IssueReader. It is the one
// accessor here whose name is not the role's: the seam spells it IssueRelations
// on both the store and the provider, and this type implements the seam.
func (p timedProvider) IssueRelations() (issueops.Relations, error) {
return uow.NewIssueRelations(p)
}
// BlockingAnnotator builds the blocking-decoration role OVER THIS WRAPPER, for
// the same reason and with the same hazard as IssueReader.
func (p timedProvider) BlockingAnnotator() (issueops.BlockingAnnotator, error) {

View file

@ -411,6 +411,23 @@ const (
// answers about a set of ISSUES described by a predicate, and this one about
// EDGES anchored on ids, per anchor.
OpCountDependencyEdges = "countDependencyEdges"
// OpListRelatedIssues reads ONE issue's neighbors in a named direction,
// behind issueops.Relations. It is NOT listDependencies narrowed to one
// anchor: that operation answers the stored edge ROWS with their targets
// spelled as stored, and this one answers the ISSUES on the far end — so an
// edge whose target this database holds no row for is a row there and no
// neighbor here, and the two answer different arities of question.
//
// It is a SUB-RESOURCE OF THE ISSUE rather than a member of the dependency
// collection, and the argument is ELEMENT IDENTITY rather than a claim about
// what that collection answers with — getDependencyTree answers hydrated
// TreeNodes, so "everything under /dependencies is about edges" would be
// false. What decides it is narrower and checkable: the rows here are the
// SAME pinned struct getIssue 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.
OpListRelatedIssues = "listRelatedIssues"
// OpListBlockingAnnotations reads the DERIVED blocking decoration for
// several issues at once — open blockers, issues blocked, and the parent.
// It is separate from listDependencies because it answers a summary over
@ -612,6 +629,20 @@ var operationCodes = map[string][]Code{
// for a stronger version of the same reason: this operation probes no id's
// existence at all, so there is nothing it could 404 on.
OpListBlockingAnnotations: {CodeInvalidArgument, CodeUnauthenticated, CodeBusy, CodeDBUnavailable, CodeInternal},
// getDependencyTree's row exactly, and for its reasons: ONE anchor, so a
// miss is the 404 it is rather than a per-anchor flag — there is no other
// answer to preserve by reporting it in the body, and an empty neighbor
// list is the common case, so a typo answered with one would never surface.
//
// Its 400 is BOTH the transport's and the ROLE's. The transport owns the
// unknown key and the repeated single-valued parameter; ValidateRelatedRequest
// owns the two that are about this request's MEANING — a missing or
// unrecognized direction, and a dependency type no edge could carry — and each
// reaches the client as the 400 it is, on the sentinel, with the parameter
// named. The validator's third refusal, an empty anchor id, is unreachable
// here: the id is a PATH segment this handler bounds before the role is
// asked, and an id that fails that bound is the 404 a real miss gets.
OpListRelatedIssues: {CodeInvalidArgument, CodeUnauthenticated, CodeNotFound, CodeBusy, CodeDBUnavailable, CodeInternal},
// The 404 is the difference from the row above: this operation has ONE
// anchor, so there is no other answer to preserve by reporting the miss in
// the body. Its 400 is its own — an empty root, a direction outside the

129
internal/httpapi/related.go Normal file
View file

@ -0,0 +1,129 @@
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
}

View file

@ -0,0 +1,482 @@
package httpapi
import (
"encoding/json"
"errors"
"io"
"net/http"
"reflect"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The wire edge of GET /v0/beads/issues/{id}/related, on a fake role.
//
// The handler is a decoder, a path bound and a projection — which planes the
// anchor is resolved against, which dependency tables the neighbors come from,
// the pinned order, and the dropping of an edge whose far end this database
// holds no row for are all issueops.Relations', held to on three legs by its own
// contract and shown against real Dolt in cmd/bd. What only these cases can show
// is that the request a caller SENDS becomes the request the role RECEIVES, that
// the role's answer reaches the wire in the shape the document promises, that
// the single-anchor miss is a 404 rather than an empty page, and that each of
// the role's reachable refusals arrives naming the right parameter.
func newRelatedServer(t *testing.T, items []*issueops.RelatedIssue) (*testServer, *roleRelations) {
t.Helper()
rel := &roleRelations{items: items}
return newTestServer(t, rolesConfig(Config{Relations: rel})), rel
}
// relatedNeighbor is the smallest element the role can answer with: an issue
// and the type of the edge that led to it.
func relatedNeighbor(id string, depType types.DependencyType) *issueops.RelatedIssue {
return &issueops.RelatedIssue{
Issue: types.Issue{ID: id, Title: "neighbor " + id},
DependencyType: depType,
}
}
// TestListRelatedIssuesProjectsTheWholeRequest drives every part of the request
// — the path anchor, both directions, and the repeatable type filter — alone and
// together, because they are independent members of one request and a handler
// that decoded one into another's field would answer the all-together case
// correctly and every narrower case wrong.
//
// `direction` gets BOTH of its values. The vocabulary is closed and the two
// answers are the inverse graph of each other with identical shapes, so a
// handler that passed a constant would look right on whichever value a fixture
// happened to use — which is the exact failure issueops.RelationDirection
// refuses a default to prevent.
func TestListRelatedIssuesProjectsTheWholeRequest(t *testing.T) {
for _, tc := range []struct {
name string
path string
query string
want issueops.RelatedRequest
}{
{
name: "the outgoing direction",
path: "bd-1",
query: "?direction=out",
want: issueops.RelatedRequest{ID: "bd-1", Direction: issueops.RelationOut},
},
{
name: "the incoming direction",
path: "bd-1",
query: "?direction=in",
want: issueops.RelatedRequest{ID: "bd-1", Direction: issueops.RelationIn},
},
{
name: "types narrow the edges",
path: "bd-1",
query: "?direction=out&type=blocks&type=parent-child",
want: issueops.RelatedRequest{
ID: "bd-1",
Direction: issueops.RelationOut,
Types: []types.DependencyType{types.DepBlocks, types.DepParentChild},
},
},
{
// The anchor is the PATH segment, percent-decoded once. An id
// carrying a character the URL grammar reserves reaches the role
// spelled as the caller meant it, not as the wire carried it.
name: "a percent-escaped anchor is decoded once",
path: "bd%2Fslash",
query: "?direction=in",
want: issueops.RelatedRequest{ID: "bd/slash", Direction: issueops.RelationIn},
},
} {
t.Run(tc.name, func(t *testing.T) {
ts, rel := newRelatedServer(t, nil)
resp := ts.get(t, "/v0/beads/issues/"+tc.path+"/related"+tc.query)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := rel.relatedRequests()
if len(reqs) != 1 {
t.Fatalf("%d neighbor reads ran, want 1", len(reqs))
}
if !reflect.DeepEqual(reqs[0], tc.want) {
t.Errorf("RelatedRequest = %+v, want %+v", reqs[0], tc.want)
}
})
}
}
// TestListRelatedIssuesAnswersTheRolesRowsInOrder is the response half: the
// role's answer reaches the wire as `items`, in the role's own order, with each
// element carrying its edge type beside the issue's own fields.
//
// The ORDER assertion is what makes this more than a shape check. The order is
// the ROLE's promise and the handler is a projection that may not sort or
// reshape it, so the fixture is handed to the fake in the order the role would
// answer and compared position by position.
func TestListRelatedIssuesAnswersTheRolesRowsInOrder(t *testing.T) {
ts, _ := newRelatedServer(t, []*issueops.RelatedIssue{
relatedNeighbor("bd-a", types.DepBlocks),
relatedNeighbor("bd-b", types.DepParentChild),
relatedNeighbor("bd-c", types.DepRelated),
})
resp := ts.get(t, "/v0/beads/issues/bd-anchor/related?direction=in")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
var body struct {
Items []struct {
ID *string `json:"id"`
Title *string `json:"title"`
DependencyType *string `json:"dependency_type"`
// Not a member of this element, and asserted as an ABSENCE below:
// see TestListRelatedIssuesCarriesNoRevision.
Revision *int64 `json:"revision"`
} `json:"items"`
}
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("decode %q: %v", raw, err)
}
if len(body.Items) != 3 {
t.Fatalf("%d items, want 3: %s", len(body.Items), raw)
}
for i, want := range []struct {
id string
depType string
}{
{"bd-a", string(types.DepBlocks)},
{"bd-b", string(types.DepParentChild)},
{"bd-c", string(types.DepRelated)},
} {
got := body.Items[i]
if got.ID == nil || got.DependencyType == nil || got.Title == nil {
t.Fatalf("item %d is missing a member: %s", i, raw)
}
// The ROW, not just the sequence: an answer in the right order whose
// elements carry the wrong edge type is still wrong, and the edge type
// is the one member this element adds to a plain issue.
if *got.ID != want.id || *got.DependencyType != want.depType {
t.Errorf("item %d = {%q %q}, want {%q %q}", i, *got.ID, *got.DependencyType, want.id, want.depType)
}
}
}
// TestListRelatedIssuesCarriesNoRevision pins the element-shape rule this
// operation inherits: the optimistic-concurrency token lives on the detail read
// and nowhere else, and the elements here are the pinned Go struct
// GET /v0/beads/issues/{id} already carries under `dependencies` and
// `dependents`.
//
// It is asserted on the BYTES rather than through a decode, because the failure
// it guards is a member ARRIVING — a decode into a struct without the field
// cannot see one, and a decode into a struct with it reads an absent member as
// the zero that would look correct.
//
// WHAT IT ADDS OVER TestWireTagBijection, measured rather than assumed. Giving
// types.Issue.RowVersion a json tag reddens both this and that one, so on the
// mutation most likely to happen this case is redundant. What it covers alone is
// the other direction: a handler that stopped projecting onto the pinned alias
// and built an envelope element of its own could publish a token with the
// bijection intact, because that gate compares the canonical struct against the
// schema and never looks at a body. This is the wire-side half.
func TestListRelatedIssuesCarriesNoRevision(t *testing.T) {
neighbor := relatedNeighbor("bd-a", types.DepBlocks)
// A non-zero token on the row the role answers with, so an element that
// published it would be visible rather than indistinguishable from a zero.
neighbor.RowVersion = 918273645
ts, _ := newRelatedServer(t, []*issueops.RelatedIssue{neighbor})
resp := ts.get(t, "/v0/beads/issues/bd-anchor/related?direction=out")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if strings.Contains(string(raw), "revision") || strings.Contains(string(raw), "918273645") {
t.Errorf("body carries a revision member: %s", raw)
}
}
// TestListRelatedIssuesAnswersAnEmptyArrayNotNull pins the one thing a Go nil
// slice gets wrong on the way out. `items` is required, so a client is entitled
// to range over it without a nil check — and an issue with no neighbors in the
// requested direction is the COMMON case here, not an edge one.
func TestListRelatedIssuesAnswersAnEmptyArrayNotNull(t *testing.T) {
ts, _ := newRelatedServer(t, nil)
resp := ts.get(t, "/v0/beads/issues/bd-anchor/related?direction=out")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if !strings.Contains(string(raw), `"items":[]`) {
t.Errorf("body = %s, want an empty `items` array rather than null", raw)
}
}
// TestListRelatedIssuesAnswersAnAbsentAnchorWithNotFound is the difference from
// every other graph read on this surface, and the reason this operation carries
// a 404 at all: those are batched and report a miss per anchor because failing
// would throw away the answers that were found, and here there is one anchor and
// nothing to preserve.
//
// It matters because the two answers are otherwise identical. An issue with no
// neighbors and an id that names nothing would both be an empty `items`, and
// the empty list is the common case — so a typo would never surface.
func TestListRelatedIssuesAnswersAnAbsentAnchorWithNotFound(t *testing.T) {
rel := &roleRelations{err: storage.ErrNotFound}
ts := newTestServer(t, rolesConfig(Config{Relations: rel}))
resp := ts.get(t, "/v0/beads/issues/bd-gone/related?direction=out")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["code"] != string(CodeNotFound) {
t.Errorf("code = %v, want not_found", body["code"])
}
// The role WAS asked. A 404 decided at the edge would mean the anchor was
// never probed, which is a different operation.
if n := len(rel.relatedRequests()); n != 1 {
t.Errorf("%d neighbor reads ran, want 1 — the miss is the role's answer, not the handler's guess", n)
}
}
// TestListRelatedIssuesNamesTheRefusedParameter is where the handler earns its
// keep: the role publishes ONE sentinel for the mistakes a request can make, and
// which parameter the client is told to fix comes from re-asking the request
// ValidateRelatedRequest's own questions.
//
// Both of the validator's wire-reachable refusals are here. Its third — an empty
// anchor id — is deliberately absent, because the path bound turns that into the
// 404 the case above covers; a picker that named `id` for a bad direction would
// send the caller to change a path segment that was fine.
func TestListRelatedIssuesNamesTheRefusedParameter(t *testing.T) {
for _, tc := range []struct {
name string
query string
param string
}{
{"no direction at all", "", "direction"},
{"a direction outside the closed set", "?direction=both", "direction"},
{"a direction that is nearly right", "?direction=OUT", "direction"},
{"an unusable edge type", "?direction=out&type=", "type"},
{
// The direction is checked FIRST, which is
// ValidateRelatedRequest's own order: a request wrong about both
// is a refusal about the direction, because naming the type would
// send the caller to fix a parameter the validator never reached.
name: "a bad direction beside an unusable type",
query: "?direction=sideways&type=",
param: "direction",
},
} {
t.Run(tc.name, func(t *testing.T) {
// The refusals under test are the ROLE's, so the fake has to raise
// them rather than the handler pre-empting them — which is the
// arrangement the handler's doc comment describes.
rel := &roleRelations{err: issueops.ErrValidation}
ts := newTestServer(t, rolesConfig(Config{Relations: rel}))
resp := ts.get(t, "/v0/beads/issues/bd-1/related"+tc.query)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want invalid_argument", body["code"])
}
if body["param"] != tc.param {
t.Errorf("param = %v, want %q", body["param"], tc.param)
}
if body["reason"] != string(ReasonInvalidValue) {
t.Errorf("reason = %v, want invalid_value", body["reason"])
}
})
}
}
// TestListRelatedIssuesRefusesAnImpossibleAnchorFromTheEdge: 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
// gives the SAME 404 a real miss gets, so a caller cannot map this server's
// notion of a well-formed id.
//
// It is also what makes ValidateRelatedRequest's empty-id refusal unreachable,
// which the parameter picker above relies on.
func TestListRelatedIssuesRefusesAnImpossibleAnchorFromTheEdge(t *testing.T) {
long := strings.Repeat("x", types.MaxFieldLen+1)
for _, id := range []string{long, "bd-%01"} {
ts, rel := newRelatedServer(t, nil)
resp := ts.get(t, "/v0/beads/issues/"+id+"/related?direction=out")
if resp.StatusCode != http.StatusNotFound {
t.Errorf("anchor %q: status = %d, want 404", id, resp.StatusCode)
continue
}
if body := decodeBody(t, resp); body["code"] != string(CodeNotFound) {
t.Errorf("anchor %q: code = %v, want not_found", id, body["code"])
}
if n := len(rel.relatedRequests()); n != 0 {
t.Errorf("anchor %q reached the role; a refusal from the edge must not buy a database round trip", id)
}
}
}
// TestListRelatedIssuesAnswersAQueryRefusalBeforeTheAnchorBound pins the order
// handleGetIssue already has, 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
// and lose the refusal.
func TestListRelatedIssuesAnswersAQueryRefusalBeforeTheAnchorBound(t *testing.T) {
ts, rel := newRelatedServer(t, nil)
resp := ts.get(t, "/v0/beads/issues/bd-%01/related?direction=out&bogus=1")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["param"] != "bogus" || body["reason"] != string(ReasonUnknownParameter) {
t.Errorf("body = %v, want param=bogus reason=unknown_parameter", body)
}
if n := len(rel.relatedRequests()); n != 0 {
t.Errorf("%d neighbor reads ran for a refused request", n)
}
}
// TestListRelatedIssuesStaysStrictAboutParameters is the transport's own 400s,
// the ones no role refusal is behind: a key this server does not know, and a
// single-valued parameter sent twice.
//
// The repeated-`direction` case matters more here than on most operations. The
// parameter is required and its vocabulary is closed, so silently resolving a
// repeat to one of its values would walk the INVERSE graph from the one the
// caller asked for, with the same shape and no way to notice.
func TestListRelatedIssuesStaysStrictAboutParameters(t *testing.T) {
for _, tc := range []struct {
name string
query string
param string
reason Reason
}{
{"an unknown key", "?direction=out&bogus=1", "bogus", ReasonUnknownParameter},
{"a near miss on a real parameter", "?directions=out", "directions", ReasonUnknownParameter},
{"direction sent twice", "?direction=out&direction=in", "direction", ReasonInvalidValue},
{
// The anchor is the PATH, so a query parameter naming it is a key
// this operation does not know — and not a second spelling of the
// batched reads' `issue_id`.
name: "the batched reads' anchor parameter",
query: "?direction=out&issue_id=bd-2",
param: "issue_id",
reason: ReasonUnknownParameter,
},
} {
t.Run(tc.name, func(t *testing.T) {
ts, rel := newRelatedServer(t, nil)
resp := ts.get(t, "/v0/beads/issues/bd-1/related"+tc.query)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["param"] != tc.param || body["reason"] != string(tc.reason) {
t.Errorf("body = %v, want param %q with reason %s", body, tc.param, tc.reason)
}
if n := len(rel.relatedRequests()); n != 0 {
t.Errorf("%d neighbor reads ran for a refused request", n)
}
})
}
}
// TestListRelatedIssuesReachesItsOwnRole is the wiring pin, and it is not
// ceremony: Relations, EdgeReader and Reader all answer about this issue's
// edges through adjacent accessors, so a handler wired to any of the others
// would answer this operation's requests from the wrong surface and still
// produce a plausible body. Their fakes record what they were asked, and they
// must be asked nothing.
//
// The sub-resource path is the other half of the same question: it sits one
// segment past GET /v0/beads/issues/{id}, so a route that matched too widely
// would answer this request from the detail read.
func TestListRelatedIssuesReachesItsOwnRole(t *testing.T) {
rel := &roleRelations{}
edges := &roleEdgeReader{}
rd := &roleReader{}
ts := newTestServer(t, rolesConfig(Config{Relations: rel, EdgeReader: edges, Reader: rd}))
resp := ts.get(t, "/v0/beads/issues/bd-1/related?direction=out")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if n := len(rel.relatedRequests()); n != 1 {
t.Errorf("%d neighbor reads ran, want 1", n)
}
if n := len(edges.edgeRequests()); n != 0 {
t.Errorf("%d stored-edge reads ran; the neighbor read must not reach EdgeReader", n)
}
if n := len(rd.getRequests()); n != 0 {
t.Errorf("%d detail reads ran; the sub-resource path must not fall through to getIssue", n)
}
}
// TestListRelatedIssuesKeepsANonValidationFailureAtFiveHundred is the other half
// of classifying on the sentinel: an error that is neither the role's
// request-validation refusal nor its miss must not be reported as the caller's
// fault.
func TestListRelatedIssuesKeepsANonValidationFailureAtFiveHundred(t *testing.T) {
rel := &roleRelations{err: errors.New("backend is unreachable")}
ts := newTestServer(t, rolesConfig(Config{Relations: rel}))
resp := ts.get(t, "/v0/beads/issues/bd-1/related?direction=out")
if resp.StatusCode != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["code"] != string(CodeInternal) {
t.Errorf("code = %v, want internal", body["code"])
}
}
// TestListRelatedIssuesSurvivesANilNeighbor pins the reason this role goes out
// UNWRAPPED where checkedReader exists: the role answers with a slice of
// POINTERS, and a caller-supplied one that put a nil in it would be a panic on a
// live server if the projection dereferenced blindly. It drops the element
// instead, exactly as wireItems and wireEdges already do.
func TestListRelatedIssuesSurvivesANilNeighbor(t *testing.T) {
ts, _ := newRelatedServer(t, []*issueops.RelatedIssue{
relatedNeighbor("bd-a", types.DepBlocks),
nil,
relatedNeighbor("bd-c", types.DepRelated),
})
resp := ts.get(t, "/v0/beads/issues/bd-anchor/related?direction=out")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
var body struct {
Items []json.RawMessage `json:"items"`
}
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("decode %q: %v", raw, err)
}
if len(body.Items) != 2 {
t.Errorf("%d items, want the two real neighbors: %s", len(body.Items), raw)
}
assertNoPanic(t, ts)
}

View file

@ -41,6 +41,13 @@ import (
//
// issueops.EdgeReader has no wrapper here for the same reason: it answers with
// a value, and wireEdges drops a nil edge.
//
// issueops.Relations has none either, and it is the case worth stating because
// it is the first role that answers with a SLICE OF POINTERS and still needs no
// wrapper. What decides it is not the pointer, it is whether a handler
// dereferences one it was handed: wireRelated skips a nil element exactly as
// wireEdges and wireItems do, so the only thing a wrapper could add is the
// appearance of a guarantee.
type checkedReader struct{ inner issueops.Reader }
// Ready passes the request through unchanged.

View file

@ -134,6 +134,35 @@ func (c *roleGraphCounter) countRequests() []issueops.EdgeCountRequest {
return append([]issueops.EdgeCountRequest(nil), c.counts...)
}
// roleRelations is the single-anchor NEIGHBOR role of the store-shaped source,
// its own fake beside roleEdgeReader for roleGraphCounter's reason: the two sit
// on adjacent accessors and answer about the same edges, so one fake serving
// both would let a test pass on a server that had wired the neighbor handler to
// the stored-edge reader.
type roleRelations struct {
items []*issueops.RelatedIssue
err error
mu sync.Mutex
reqs []issueops.RelatedRequest
}
func (r *roleRelations) Related(_ context.Context, req issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
r.mu.Lock()
r.reqs = append(r.reqs, req)
r.mu.Unlock()
if r.err != nil {
return nil, r.err
}
return r.items, nil
}
func (r *roleRelations) relatedRequests() []issueops.RelatedRequest {
r.mu.Lock()
defer r.mu.Unlock()
return append([]issueops.RelatedRequest(nil), r.reqs...)
}
// roleBlockingAnnotator is the derived-decoration role of the store-shaped
// source. It is its own fake beside roleEdgeReader because the two are separate
// interfaces for separate questions, and a double answering both would be the
@ -833,6 +862,9 @@ func rolesConfig(cfg Config) Config {
if cfg.GraphCounter == nil {
cfg.GraphCounter = &roleGraphCounter{}
}
if cfg.Relations == nil {
cfg.Relations = &roleRelations{}
}
if cfg.BlockingAnnotator == nil {
cfg.BlockingAnnotator = &roleBlockingAnnotator{}
}

View file

@ -297,6 +297,23 @@ var routeTable = []route{
implemented: true,
handler: (*Server).handleUpdate,
},
{
op: OpListRelatedIssues,
method: http.MethodGet,
// A SUB-RESOURCE of the issue-detail path, and the surface's first. The
// segment is a LITERAL after a single-segment wildcard, so pattern and
// specPath agree and the router registers the documented path itself —
// no declaration is needed 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's `/v0/beads/issues/{idop}` is registered under POST and is
// one segment shorter besides.
pattern: "/v0/beads/issues/{id}/related",
capability: "issues.related",
implemented: true,
handler: (*Server).handleListRelatedIssues,
},
{
op: OpListSettings,
method: http.MethodGet,

View file

@ -220,7 +220,15 @@ type Config struct {
// with the edge ROWS in one direction, this one with a number in either,
// and neither can answer the other's question. Required on the same terms
// as every field here.
GraphCounter issueops.GraphCounter
GraphCounter issueops.GraphCounter
// Relations is the single-anchor neighbor read behind
// GET /v0/beads/issues/{id}/related. It is a SEPARATE field from EdgeReader
// for the reason issueops.EdgeReader's own doc gives at length: that role
// answers with the edge ROWS for many anchors and reports a miss per anchor,
// this one answers with the hydrated ISSUES on the far end for ONE anchor and
// answers ErrNotFound. Different answer shape, different miss policy,
// different arity. Required on the same terms as every field here.
Relations issueops.Relations
BlockingAnnotator issueops.BlockingAnnotator
TreeWalker issueops.TreeWalker
ReadyCounter issueops.ReadyCounter
@ -337,6 +345,7 @@ type Server struct {
issueCycles issueops.CycleDetector
issueEdges issueops.EdgeReader
issueEdgeCounter issueops.GraphCounter
issueRelations issueops.Relations
issueBlocking issueops.BlockingAnnotator
issueTree issueops.TreeWalker
issueReadyCounter issueops.ReadyCounter
@ -487,6 +496,7 @@ func Listen(cfg Config) (*Server, error) {
issueCycles: cfg.CycleDetector,
issueEdges: cfg.EdgeReader,
issueEdgeCounter: cfg.GraphCounter,
issueRelations: cfg.Relations,
issueBlocking: cfg.BlockingAnnotator,
issueTree: cfg.TreeWalker,
issueReadyCounter: cfg.ReadyCounter,
@ -604,12 +614,12 @@ func Listen(cfg Config) (*Server, error) {
// "all or nothing" would turn an honest condition into a special case inside
// three functions. It is checked once, on its own, below.
func sourceRoles(cfg Config) []any {
return []any{cfg.Reader, cfg.Claimer, cfg.ReadyClaimer, cfg.Releaser, cfg.Lifecycle, cfg.BatchCloser, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.GraphCounter, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Counter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS}
return []any{cfg.Reader, cfg.Claimer, cfg.ReadyClaimer, cfg.Releaser, cfg.Lifecycle, cfg.BatchCloser, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.GraphCounter, cfg.Relations, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Counter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS}
}
// roleSourceNames spells sourceRoles for the refusal message, in the same
// order, so a caller reading the error learns the whole set it must pass.
const roleSourceNames = "Reader, Claimer, ReadyClaimer, Releaser, Lifecycle, BatchCloser, Settings, Stats, CycleDetector, EdgeReader, GraphCounter, BlockingAnnotator, TreeWalker, ReadyCounter, Counter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS"
const roleSourceNames = "Reader, Claimer, ReadyClaimer, Releaser, Lifecycle, BatchCloser, Settings, Stats, CycleDetector, EdgeReader, GraphCounter, Relations, BlockingAnnotator, TreeWalker, ReadyCounter, Counter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS"
func anyRoleSet(cfg Config) bool {
return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil })
@ -925,6 +935,23 @@ func (s *Server) graphCounter(r *http.Request) (issueops.GraphCounter, error) {
return src.GraphCounter()
}
// relations returns the single-anchor neighbor surface for one request, built
// the same two ways as edgeReader above and held by INTERFACE so
// uow.RelationsSource is load-bearing rather than decorative.
//
// It goes out UNWRAPPED even though the role answers with a slice of POINTERS,
// which is the one place this differs from checkedReader's argument. That
// wrapper exists because handleGetIssue DEREFERENCES the pointer a role handed
// back; here wireRelated drops a nil element the way wireItems and wireEdges
// already do, so there is nothing for a checked wrapper to make safe.
func (s *Server) relations(r *http.Request) (issueops.Relations, error) {
if s.provider == nil {
return s.issueRelations, nil
}
var src uow.RelationsSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())}
return src.IssueRelations()
}
// blockingAnnotator returns the derived blocking-decoration surface for one
// request, on the same terms as every role above and held by INTERFACE so
// uow.BlockingAnnotatorSource is load-bearing rather than decorative. It goes

View file

@ -2169,6 +2169,159 @@ paths:
'503':
$ref: '#/components/responses/Unavailable'
/v0/beads/issues/{id}/related:
get:
operationId: listRelatedIssues
summary: List one issue's neighbors in a named direction
description: >-
THE ISSUES ON THE FAR END of this issue's edges, in the direction the
request names, each carrying the type of the edge that led to it. It is
the read behind `bd dep list`'s neighbor view, and its elements are the
same `IssueWithDependencyMetadata` the `dependencies` and `dependents`
members of `GET /v0/beads/issues/{id}` already carry.
IT IS A SUB-RESOURCE OF THE ISSUE, not a member of the dependency
collection, and the two answer different things about the same edges.
`GET /v0/beads/dependencies` returns the stored edge ROWS — targets
spelled exactly as stored, nothing looked up — for many anchors at once;
this one is anchored on ONE issue and answers with HYDRATED ISSUES, so
an edge whose far end this database holds no row for is not a neighbor
at all. `issueops.Relations` and `issueops.EdgeReader` state that split
once; nothing is restated here.
THE CONSEQUENCE IS WORTH READING BEFORE COUNTING ANYTHING. A dependency
target may be an `external:` reference or an id belonging to another
repository, and this database holds no issue for either. Such an edge is
left out with no placeholder row and no error, so the length of `items`
is this issue's NEIGHBOR count and not its EDGE count, and the two
differ by however many of its edges point outside this database. A
caller that needs the edges themselves reads
`GET /v0/beads/dependencies`; a caller that needs the number reads
`GET /v0/beads/dependencies:count`, which counts edges and not
neighbors.
AN ID THAT NAMES NEITHER AN ISSUE NOR A WISP IS A 404, and that is the
difference from every other graph read on this surface. Those are
batched and report a miss per anchor, because failing the call would
throw away the answers for the ids that were found; here there is one
anchor and no other answer to preserve. It matters because an empty
`items` is the COMMON case — most issues have neighbors in only one
direction — so a typo answered with an empty list would never surface.
BOTH PLANES ARE READ, on the anchor and on its neighbors. The anchor is
resolved against the durable and ephemeral planes together, so a wisp id
is a legal anchor; and the neighbors are collected from BOTH dependency
tables and hydrated from both issue tables, so a durable issue's `in`
neighbors include the wisps that depend on it and a `direction=out`
answer includes the wisp targets it depends on. Those are the ROLE's
rules, stated at `issueops.Relations`, and this document cites them
rather than restating them.
THE ORDER IS PINNED: ascending by the neighbor's id, with the edge type
breaking a tie. It is pinned rather than left to the query because the
rows come from two dependency tables read in sequence, so their natural
order is an artifact of which plane a neighbor happens to live on —
stable enough to look deliberate and not stable enough to rely on.
THE ROWS CARRY NO `revision`, on `GET /v0/beads/issues`'s terms. The
element here is the pinned Go struct `GET /v0/beads/issues/{id}` carries
under `dependencies` and `dependents`, so it publishes an issue's own
serialized fields and nothing this operation invents; the
optimistic-concurrency token stays on the detail read, which is where a
guarded write composes its `expected_version` from. A client holding a
neighbor list and wanting a guard reads the rows it actually intends to
write, one detail read each.
THERE IS NO `limit` AND NO CURSOR. One issue's neighbors are unbounded
here exactly as the `dependencies` member of
`GET /v0/beads/issues/{id}` already is, and this operation names ONE
anchor, so there is no question to bound instead — which is what the
dependency-collection reads bound at 100 `issue_id` values apiece. A
limit with no cursor behind it would truncate with no way to fetch the
rest.
THERE IS NO `both` DIRECTION, for the reason
`GET /v0/beads/dependencies:count` has none: a caller that wants the
pair asks twice, and one call answering both would have to say which
direction each row came from — which is a second member on an element
this document deliberately shares with the detail read.
parameters:
- $ref: '#/components/parameters/IssueID'
- name: direction
in: query
required: true
description: >-
Which way this issue's edges are walked. `out` answers the issues it
DEPENDS ON — the `dependencies` member of
`GET /v0/beads/issues/{id}`. `in` answers the issues that depend on
it — that read's `dependents` member.
IT IS REQUIRED AND HAS NO DEFAULT, on
`GET /v0/beads/dependencies:count`'s terms and for the reason
`issueops.RelationDirection` gives: the two answers have the same
shape and the same member names, so a caller handed the inverse graph
has nothing to notice. An absent or unrecognized value is a 400
`invalid_argument` with `param: "direction"`, never a walk in some
default direction.
The vocabulary is CLOSED — unlike `type` below — because it is a
property of the edge's shape rather than of a workspace's
configuration.
schema:
type: string
enum: [out, in]
- name: type
in: query
description: >-
Edge types to include. Repeat the parameter. Empty means every
type.
`GET /v0/beads/dependencies`'s `type` exactly: the vocabulary is
OPEN, so an unrecognized value is not an error and simply matches no
edge, while a value no edge could ever carry — empty, or longer than
the column — is a 400 `invalid_argument` with `param: "type"`.
The filter narrows EDGES, never the anchor. An issue whose every
edge it rejects is answered with an empty `items` and not with a
404, which is a different fact from an id that names nothing.
style: form
explode: true
schema:
type: array
items:
type: string
security:
- bearerToken: []
responses:
'200':
description: This issue's neighbors, in ascending neighbor id.
content:
application/json:
schema:
$ref: '#/components/schemas/RelatedIssues'
'400':
$ref: '#/components/responses/InvalidArgument'
'401':
$ref: '#/components/responses/Unauthenticated'
'404':
$ref: '#/components/responses/NotFound'
'500':
$ref: '#/components/responses/InternalError'
'503':
$ref: '#/components/responses/Unavailable'
/v0/beads/issues/{id}:claim:
post:
operationId: claimIssue
@ -6476,7 +6629,7 @@ components:
derived from its route table, and the server-wide BEHAVIORS it
enforces. v0's operation vocabulary is `ready.list`, `ready.count`,
`issues.list`, `issues.query`, `issues.count`, `issues.get`,
`issues.create`,
`issues.related`, `issues.create`,
`issues.batchClose`,
`issues.claim`, `issues.claimNext`, `issues.release`,
`issues.close`, `issues.reopen`, `issues.update`,
@ -7544,6 +7697,49 @@ components:
items:
$ref: '#/components/schemas/IssueBlocking'
RelatedIssues:
type: object
description: >-
One issue's neighbors — the body of
`GET /v0/beads/issues/{id}/related`. It is NOT a page: this operation
has no limit and no cursor, and it names ONE anchor, so there is nothing
for a `has_more` to be about.
There is no `missing` beside `items`, unlike `DependencyEdges`. That
member exists because a batch cannot report an absent anchor any other
way without discarding the anchors it did find; here the single absent
anchor is a 404.
It is NOT `x-go-type`-pinned, for `EdgeCounts`' reason: there is no
canonical Go struct whose JSON encoding is this envelope. The role
answers with a bare slice of `issueops.RelatedIssue`, and THAT element
is pinned — see `IssueWithDependencyMetadata`.
required: [items]
properties:
items:
type: array
description: >-
The neighbors, ascending by id with the edge type breaking a tie.
Empty array (never null) when this issue has none in the requested
direction, or when the `type` filter rejected every edge.
Each element is a full issue plus `dependency_type`, the type of the
edge that led to it — the same element
`GET /v0/beads/issues/{id}` carries under `dependencies` and
`dependents`, so the two surfaces are one compatibility domain.
AN EDGE WITH NO FAR END IN THIS DATABASE CONTRIBUTES NOTHING here:
an `external:` reference, an id in another repository's namespace
and an id whose issue was deleted out from under its edges are all
silently absent, with no placeholder row and no error. The length of
this array is a NEIGHBOR count, never an edge count.
items:
$ref: '#/components/schemas/IssueWithDependencyMetadata'
BatchCreateRequest:
type: object
additionalProperties: false