diff --git a/cmd/bd/serve.go b/cmd/bd/serve.go index 106bf5680..d15db43b6 100644 --- a/cmd/bd/serve.go +++ b/cmd/bd/serve.go @@ -307,6 +307,7 @@ func runServe() error { Stats: roles.stats, CycleDetector: roles.cycles, EdgeReader: roles.edges, + GraphCounter: roles.edgeCounter, BlockingAnnotator: roles.blocking, TreeWalker: roles.tree, ReadyCounter: roles.readyCounter, @@ -664,6 +665,7 @@ func serveIssueRoles(src storage.DoltStorage, journalEnabled bool) (serveRoles, {"stats reporter", func() (err error) { roles.stats, err = src.StatsReporter(); return }}, {"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 }}, {"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 }}, @@ -736,6 +738,7 @@ type serveRoles struct { stats issueops.StatsReporter cycles issueops.CycleDetector edges issueops.EdgeReader + edgeCounter issueops.GraphCounter blocking issueops.BlockingAnnotator tree issueops.TreeWalker readyCounter issueops.ReadyCounter diff --git a/cmd/bd/serve_edge_counts_proxied_integration_test.go b/cmd/bd/serve_edge_counts_proxied_integration_test.go new file mode 100644 index 000000000..c0890b829 --- /dev/null +++ b/cmd/bd/serve_edge_counts_proxied_integration_test.go @@ -0,0 +1,305 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "io" + "net/http" + "testing" +) + +// End-to-end for the edge count, 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 per-anchor envelope, the four refusals and the +// anchor bound. What only this level can prove is what the NUMBERS mean, and on +// this operation that is most of the contract: +// +// - the two directions really are DIFFERENT edge sets, which is the whole +// reason the parameter is required rather than defaulted; +// - the count really SPANS BOTH DEPENDENCY PLANES — an edge lives in +// `dependencies` or in `wisp_dependencies` by which plane its SOURCE sits +// on, and a durable issue's dependent count includes the wisps that depend +// on it. That is a fact about two tables and a fake cannot be asked it; +// - a missing anchor really is a per-anchor `missing: true` beside answers +// that were found, rather than a 404 that throws them away; +// - the numbers AGREE with the rows the stored-edge read returns, which is +// the property that makes this operation a count of that graph rather than +// of some other one. +// +// Every case scopes itself to issues this test creates, so the numbers are +// exact whatever else the workspace holds. + +// anchorCount is one decoded entry of the response. Every member is a POINTER: +// an omitted `count` or `missing` is the failure mode worth catching, and a +// value decode would read it as the zero that is correct most of the time. +type anchorCount struct { + ID *string `json:"id"` + Count *int64 `json:"count"` + Missing *bool `json:"missing"` +} + +// countEdges asks the server for the edge counts and returns the status and the +// decoded anchors. +// +// The count decodes through an int64 rather than through `any`, because the +// member is `format: int64` and reading a cardinality through a float64 answers +// a number NEAR the count — which on a number is worse than an error, since +// nothing downstream can tell. +func (sp *serveProcess) countEdges(t *testing.T, query string) (int, []anchorCount) { + t.Helper() + resp, err := sp.client.Get(sp.url("/v0/beads/dependencies:count" + query)) + if err != nil { + t.Fatalf("GET dependencies:count%s: %v\nstderr:\n%s", query, err, sp.stderr.String()) + } + defer func() { _ = resp.Body.Close() }() + raw, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read count body: %v", err) + } + if resp.StatusCode != http.StatusOK { + return resp.StatusCode, nil + } + var body struct { + Anchors []anchorCount `json:"anchors"` + } + if err := json.Unmarshal(raw, &body); err != nil { + t.Fatalf("decode count body %q: %v", raw, err) + } + if body.Anchors == nil { + t.Errorf("GET dependencies:count%s returned a null `anchors`; the document promises an array", query) + } + return resp.StatusCode, body.Anchors +} + +// one asks about a single anchor and returns its entry. +func (sp *serveProcess) countEdgesOf(t *testing.T, id, query string) anchorCount { + t.Helper() + status, anchors := sp.countEdges(t, "?issue_id="+id+query) + if status != http.StatusOK { + t.Fatalf("count edges of %s%s: status = %d", id, query, status) + } + if len(anchors) != 1 { + t.Fatalf("count edges of %s: %d anchors, want 1", id, len(anchors)) + } + a := anchors[0] + if a.ID == nil || a.Count == nil || a.Missing == nil { + t.Fatalf("count edges of %s: an anchor member is missing: %+v", id, a) + } + if *a.ID != id { + t.Fatalf("count edges of %s answered about %q; the id is echoed as spelled", id, *a.ID) + } + return a +} + +func TestProxiedServerServeEdgeCounts(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "srvedgecnt") + sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir)) + + // THE TWO DIRECTIONS ARE DIFFERENT EDGE SETS, 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 2 and 3 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 count different edges", func(t *testing.T) { + hub := bdProxiedCreate(t, bd, p.dir, "the hub", "-p", "2") + var dependsOn, dependents []string + for i := 0; i < 2; i++ { + dependsOn = append(dependsOn, bdProxiedCreate(t, bd, p.dir, "a dependency", "-p", "2").ID) + } + for i := 0; i < 3; i++ { + dependents = append(dependents, bdProxiedCreate(t, bd, p.dir, "a dependent", "-p", "2").ID) + } + for _, target := range 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 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) + } + } + + if got := *sp.countEdgesOf(t, hub.ID, "&direction=out").Count; got != 2 { + t.Errorf("out = %d, want 2 — the edges whose SOURCE is the anchor", got) + } + if got := *sp.countEdgesOf(t, hub.ID, "&direction=in").Count; got != 3 { + t.Errorf("in = %d, want 3 — the edges whose TARGET is the anchor", got) + } + + // THE COUNT AGREES WITH THE ROWS. The stored-edge read beside it is + // outbound-only and returns the rows themselves; if the two disagreed, + // one of them would be counting a different graph. + if rows := len(sp.storedEdges(t, hub.ID)); int64(rows) != *sp.countEdgesOf(t, hub.ID, "&direction=out").Count { + t.Errorf("the outbound count and GET /v0/beads/dependencies disagree: %d rows", rows) + } + + // The type filter narrows EDGES and never anchors: the hub's outbound + // edges are all `blocks`, so a filter for a type it has none of leaves + // it PRESENT at 0 rather than missing. + filtered := sp.countEdgesOf(t, hub.ID, "&direction=out&type=discovered-from") + if *filtered.Count != 0 || *filtered.Missing { + t.Errorf("a type filter matching nothing = {count %d missing %v}, want a present anchor at 0", + *filtered.Count, *filtered.Missing) + } + }) + + // THE WISP PLANE, which is the fact this operation's contract states most + // loudly and the one no fake can be asked. 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 an inbound edge in the OTHER + // table — and the count is the sum across both. + t.Run("the count spans both dependency 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) + } + } + + // One edge in `dependencies`, one in `wisp_dependencies`, and the + // answer is 2. A count that read one table would answer 1 — and would + // look perfectly plausible. + if got := *sp.countEdgesOf(t, durable.ID, "&direction=in").Count; got != 2 { + t.Errorf("in = %d, want 2 — the sum across `dependencies` and `wisp_dependencies`", got) + } + + // And from the wisp's own side: an ephemeral anchor's outbound count + // reaches the durable issue it depends on. + if got := *sp.countEdgesOf(t, wisp.ID, "&direction=out").Count; got != 1 { + t.Errorf("the wisp's out = %d, want 1 — an ephemeral anchor counts its own edges", got) + } + }) + + // A MISSING ANCHOR IS REPORTED, NOT REFUSED, and it is reported BESIDE the + // answers that were found. This is the case the `missing` member exists + // for: both entries here carry a count of 0, and only the flag tells the + // typo from the issue that genuinely has no inbound edges. + t.Run("a missing anchor rides beside the answers that were found", func(t *testing.T) { + found := bdProxiedCreate(t, bd, p.dir, "found, with no dependents", "-p", "2") + withEdges := bdProxiedCreate(t, bd, p.dir, "found, with a dependent", "-p", "2") + dependent := bdProxiedCreate(t, bd, p.dir, "the dependent", "-p", "2") + if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", dependent.ID, withEdges.ID); err != nil { + t.Fatalf("dep add: %v\n%s", err, out) + } + + status, anchors := sp.countEdges(t, + "?issue_id="+withEdges.ID+"&issue_id=bd-nosuchbead&issue_id="+found.ID+"&direction=in") + if status != http.StatusOK { + t.Fatalf("status = %d, want 200 — an absent id is not a 404 on this operation", status) + } + if len(anchors) != 3 { + t.Fatalf("%d anchors, want 3 in the order the request named them", len(anchors)) + } + for i, want := range []struct { + id string + count int64 + missing bool + }{ + {withEdges.ID, 1, false}, + {"bd-nosuchbead", 0, true}, + {found.ID, 0, false}, + } { + got := anchors[i] + if got.ID == nil || got.Count == nil || got.Missing == nil { + t.Fatalf("anchor %d is missing a member: %+v", i, got) + } + if *got.ID != want.id || *got.Count != want.count || *got.Missing != want.missing { + t.Errorf("anchor %d = {%q %d %v}, want {%q %d %v}", + i, *got.ID, *got.Count, *got.Missing, want.id, want.count, want.missing) + } + } + }) + + // THE STATUS FILTER AND ITS ASYMMETRY, both halves against real rows. The + // filter narrows by the DEPENDENT's stored status, read from the + // dependent's own plane; and it is refused beside `direction=out`, because + // an outbound edge's far end may be a row this database does not hold. + t.Run("status narrows inbound edges and is refused outbound", func(t *testing.T) { + anchor := bdProxiedCreate(t, bd, p.dir, "status-filtered anchor", "-p", "2") + open1 := bdProxiedCreate(t, bd, p.dir, "an open dependent", "-p", "2") + open2 := bdProxiedCreate(t, bd, p.dir, "another open dependent", "-p", "2") + closed := bdProxiedCreate(t, bd, p.dir, "a dependent to close", "-p", "2") + for _, source := range []string{open1.ID, open2.ID, closed.ID} { + if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", source, anchor.ID); err != nil { + t.Fatalf("dep add: %v\n%s", err, out) + } + } + // --force because the dependent is BLOCKED by the very anchor it + // depends on, and close policy refuses that. This case is about the + // count's status filter, not about the close gate: what it needs is a + // dependent in a different stored status, and forcing is the shortest + // honest way to get one without giving the edge a second meaning. + if out, err := bdProxiedRun(t, bd, p.dir, "close", closed.ID, "--reason", "done", "--force"); err != nil { + t.Fatalf("close: %v\n%s", err, out) + } + + if got := *sp.countEdgesOf(t, anchor.ID, "&direction=in").Count; got != 3 { + t.Errorf("unnarrowed in = %d, want 3", got) + } + if got := *sp.countEdgesOf(t, anchor.ID, "&direction=in&status=open").Count; got != 2 { + t.Errorf("status=open in = %d, want 2 — the closed dependent's edge is narrowed out", got) + } + if got := *sp.countEdgesOf(t, anchor.ID, "&direction=in&status=closed").Count; got != 1 { + t.Errorf("status=closed in = %d, want 1", got) + } + // An unrecognized status is not a refusal: it matches nothing and + // counts 0, so a scripted caller counting a status its workspace has + // since dropped keeps reading 0. + if got := *sp.countEdgesOf(t, anchor.ID, "&direction=in&status=nosuchstatus").Count; got != 0 { + t.Errorf("an unrecognized status counted %d, want 0 rather than a refusal", got) + } + + // The asymmetry, over the wire: the ROLE raises it and the handler + // names the member the caller has to move. + resp, err := sp.client.Get(sp.url("/v0/beads/dependencies:count?issue_id=" + anchor.ID + "&direction=out&status=open")) + 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("status beside direction=out: 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"] != "status" { + t.Errorf("problem = %v, want invalid_argument on param status", problem) + } + }) + + // A REPEATED ANCHOR COLLAPSES, against a real read rather than a fake's + // bookkeeping. The role promises the collapse and the handler deliberately + // does not do it, so this is the case that shows the promise is kept by + // something. + t.Run("a repeated anchor is answered once", func(t *testing.T) { + anchor := bdProxiedCreate(t, bd, p.dir, "named twice", "-p", "2") + dependent := bdProxiedCreate(t, bd, p.dir, "its dependent", "-p", "2") + if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", dependent.ID, anchor.ID); err != nil { + t.Fatalf("dep add: %v\n%s", err, out) + } + + status, anchors := sp.countEdges(t, "?issue_id="+anchor.ID+"&issue_id="+anchor.ID+"&direction=in") + if status != http.StatusOK { + t.Fatalf("status = %d, want 200", status) + } + if len(anchors) != 1 { + t.Fatalf("%d anchors for one id named twice, want 1", len(anchors)) + } + if *anchors[0].Count != 1 { + t.Errorf("count = %d, want 1 — a repeat must not count the same edges twice", *anchors[0].Count) + } + }) +} diff --git a/cmd/bd/serve_source_test.go b/cmd/bd/serve_source_test.go index aed13b7c4..f7bcba400 100644 --- a/cmd/bd/serve_source_test.go +++ b/cmd/bd/serve_source_test.go @@ -104,6 +104,7 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) { batchApplier: &serveStubBatchApplier{}, metadataCAS: &serveStubMetadataCAS{}, counter: &serveStubCounter{}, + edgeCounter: &serveStubGraphCounter{}, inner: inner, } } @@ -348,6 +349,7 @@ type serveRolesStore struct { batchApplier *serveStubBatchApplier metadataCAS *serveStubMetadataCAS counter *serveStubCounter + edgeCounter *serveStubGraphCounter inner storage.DoltStorage } @@ -419,6 +421,22 @@ func (s *serveRolesStore) MetadataCAS() (issueops.MetadataCAS, error) { return s // hook peeling. func (s *serveRolesStore) Counter() (issueops.Counter, error) { return s.counter, nil } +// GraphCounter is declared for Counter's reason, and it is the SECOND role to +// need this file edited for a promotion rather than for a hook: the edge count +// is a read, so hook_graph_counter.go recurses and the recursion lands here. +// The count role's own comment above says this went unnoticed until `bd serve` +// began binding it; this one was found the same way, by this test panicking the +// moment the binding landed. +func (s *serveRolesStore) GraphCounter() (issueops.GraphCounter, error) { return s.edgeCounter, nil } + +// serveStubGraphCounter is the edge-count role's stand-in, ErrUnsupported like +// every stub here. +type serveStubGraphCounter struct{} + +func (*serveStubGraphCounter) CountEdges(context.Context, issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { + return issueops.EdgeCountResult{}, errors.ErrUnsupported +} + // serveStubCounter is the count role's stand-in. It answers ErrUnsupported like // every stub here: this file's subject is which LAYER a role comes from, never // what the role answers. diff --git a/cmd/bd/serve_store_identity_test.go b/cmd/bd/serve_store_identity_test.go index 95c44575a..bdb7a7bbd 100644 --- a/cmd/bd/serve_store_identity_test.go +++ b/cmd/bd/serve_store_identity_test.go @@ -202,6 +202,17 @@ func (*serveIdentityStore) CycleDetector() (issueops.CycleDetector, error) { return serveIdentityRole{}, nil } func (*serveIdentityStore) EdgeReader() (issueops.EdgeReader, error) { return serveIdentityRole{}, nil } + +// GraphCounter is declared for the reason every accessor here is, and it is the +// one this stub was CAUGHT missing rather than written with: the edge-count +// role is a read, so its hook decorator recurses, and the recursion lands on a +// type whose embedded storage.DoltStorage is nil. That is a promoted method on +// a nil interface — a segfault inside `bd serve`'s role extraction, not a +// compile error — and it surfaced only on the full-suite macOS shard, because +// no test name here matches the ones a role slice thinks to run. +func (*serveIdentityStore) GraphCounter() (issueops.GraphCounter, error) { + return serveIdentityRole{}, nil +} func (*serveIdentityStore) BlockingAnnotator() (issueops.BlockingAnnotator, error) { return serveIdentityRole{}, nil } @@ -243,6 +254,7 @@ type serveIdentityRole struct { issueops.StatsReporter issueops.CycleDetector issueops.EdgeReader + issueops.GraphCounter issueops.BlockingAnnotator issueops.TreeWalker issueops.ReadyCounter diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index 543585635..8d6996891 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -118,6 +118,24 @@ func (e GetDependencyTreeParamsDirection) Valid() bool { } } +// Defines values for CountDependencyEdgesParamsDirection. +const ( + In CountDependencyEdgesParamsDirection = "in" + Out CountDependencyEdgesParamsDirection = "out" +) + +// Valid indicates whether the value is a known member of the CountDependencyEdgesParamsDirection enum. +func (e CountDependencyEdgesParamsDirection) Valid() bool { + switch e { + case In: + return true + case Out: + return true + default: + return false + } +} + // Defines values for ClaimNextIssueParamsSort. const ( ClaimNextIssueParamsSortHybrid ClaimNextIssueParamsSort = "hybrid" @@ -247,6 +265,30 @@ type AddDependenciesResponse struct { Added []DependencyEdge `json:"added"` } +// AnchorEdgeCount One anchor's edge cardinality, or the report that it is not there. +type AnchorEdgeCount struct { + // Count How many stored edges match, in the requested direction, after the type and status filters. Never negative. + // + // It SPANS BOTH DEPENDENCY PLANES and is a SUM over them rather than a distinct count of edge rows — a durable issue's dependent count includes the wisps that depend on it, and a wisp's dependency count includes the durable issues it depends on. `issueops.AnchorEdgeCount.Count` states the rule, the one state that can make the sum differ from a distinct count, and why this role answers with the sum. Nothing is restated here. + // + // ALWAYS PRESENT, including as 0, and 0 is the COMMON answer: most issues have no edges in at least one direction. It is 0 for a missing anchor too, which is exactly why `missing` is beside it. + // + // DECODE IT AS A 64-BIT INTEGER. The member is `format: int64` and a workspace's graph is not bounded by 2^53; a lossy parser would answer a number NEAR the count, which on a cardinality is worse than an error because nothing downstream can tell. + Count int64 `json:"count"` + + // Id The anchor, spelled exactly as the request spelled it. It is not re-canonicalized: there is no fuzzy, prefix or substring resolution on this surface, so what comes back is what went out. + Id string `json:"id"` + + // Missing True when no issue and no wisp carries this id. + // + // ALWAYS PRESENT, including as `false`. It is the member that keeps this from being a question a caller cannot tell it got wrong: a count of 0 is otherwise indistinguishable from a typo, and an absent boolean would be ambiguous between "present" and "this producer does not report misses". + // + // A missing anchor counts 0 whatever rows are still keyed to it — a dependency row whose source has been deleted is orphaned data, and counting it would contradict this flag. + // + // DANGLING EDGES ARE NOT MISSING ANCHORS. This is about the ANCHOR. An edge whose OTHER end names nothing is counted like any other edge, and nothing here reports on it. + Missing bool `json:"missing"` +} + // ApplyBatchRequest defines model for ApplyBatchRequest. type ApplyBatchRequest struct { // Actor Who is applying the plan, under `ClaimRequest.actor`'s rules and for the same reasons: the server trims it, 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. @@ -893,7 +935,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.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.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"` @@ -1155,6 +1197,16 @@ type DependencyTreePage struct { Items []TreeNode `json:"items"` } +// EdgeCounts Each anchor's edge cardinality — the body of `GET /v0/beads/dependencies:count`. It is NOT a page and carries no total: the answer is per anchor, and a sum across anchors would double-count every edge whose two ends were both named. +// +// It is NOT `x-go-type`-pinned, for `IssueCount`'s reason: there is no canonical Go struct whose JSON encoding is this contract. The role answers with `issueops.EdgeCountResult`, whose members carry no JSON tags at all because nothing marshals it. +type EdgeCounts struct { + // Anchors One entry per DISTINCT requested `issue_id`, in the order the request first named it. Empty array (never null) when the request named no anchors this server accepted — which it cannot, since `issue_id` is required and bounded below at one. + // + // A repeated id appears ONCE. The collapse happens before anything is counted, so a caller that summed the entries would not count the same edges twice. + Anchors []AnchorEdgeCount `json:"anchors"` +} + // EventRecord One record of the durable events journal: a single committed issue mutation, as a replaying consumer receives it. // // THIS IS THE CLI'S RECORD. It is pinned to the same Go struct `bd events tail` and `bd events export` marshal one per line, so the JSONL a consumer reads from stdout and the elements of an `EventsPage.records` array are the same bytes for the same row. A committed golden fixture pins that encoding field by field. @@ -1872,6 +1924,40 @@ type GetDependencyTreeParams struct { // GetDependencyTreeParamsDirection defines parameters for GetDependencyTree. type GetDependencyTreeParamsDirection string +// CountDependencyEdgesParams defines parameters for CountDependencyEdges. +type CountDependencyEdgesParams struct { + // IssueId The anchors to count around. Repeat the parameter; at least one is required and at most 100 are accepted, and either bound is a 400 `invalid_argument` with `param: "issue_id"`, `reason: "invalid_value"`. + // + // Each value must be an EXACT canonical issue id, for the reason `GET /v0/beads/dependencies` gives. A value that matches nothing is reported on its own anchor rather than refused. An EMPTY value is a 400: the empty string names nothing a caller can have meant, and reporting it as a missing anchor would put a nameless row in an answer keyed by name. + // + // Repeats collapse onto the first mention — a second entry carries no second fact and would only invite a caller summing the result to count the same edges twice. + IssueId []string `form:"issue_id" json:"issue_id"` + + // Direction Which end of the edge the anchors sit on. `out` counts what each anchor DEPENDS ON — the direction `bd dep list` reads and the number `bd show` prints as the dependency count. `in` counts what depends on it. + // + // IT IS REQUIRED, and that is the one deliberate unfriendliness on this request. The two answers are about DIFFERENT EDGE SETS, and a workspace where most issues have edges in only one direction returns the same number for both often enough that a caller who meant the other one would not notice for a long time. An absent or unrecognized value is a 400 `invalid_argument` with `param: "direction"`, never a count 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 CountDependencyEdgesParamsDirection `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`. + // + // The filter narrows EDGES, never anchors. An anchor whose every edge it rejects comes back present with a count of 0, which is a different fact from an anchor that is not there. + Type *[]string `form:"type,omitempty" json:"type,omitempty"` + + // Status Count only edges whose DEPENDENT — the issue at the source end, the one doing the depending — is in this stored status. Empty means every status. + // + // IT IS LEGAL ONLY WITH `direction=in`. Sending it beside `direction=out` is a 400 `invalid_argument` with `param: "status"` and `reason: "invalid_value"`, rather than a filter that is quietly ignored. The asymmetry is the substrate's and `issueops.EdgeCountRequest.Status` states why: narrowing by status joins the far end of the edge to the row holding its status, and an OUTBOUND edge's far end may be an `external:` reference or an id belonging to another repository — rows this database does not hold — so the filter would silently drop every dangling edge. + // + // It is ONE status, not a comma-separated OR set, and it is NOT validated against the workspace vocabulary: an unrecognized name matches nothing and counts 0 rather than failing, exactly as `GET /v0/beads/issues:count`'s `status` does. A scripted caller counting a status its workspace has since dropped reads 0 and should keep reading 0. + Status *string `form:"status,omitempty" json:"status,omitempty"` +} + +// CountDependencyEdgesParamsDirection defines parameters for CountDependencyEdges. +type CountDependencyEdgesParamsDirection string + // ListEventsParams defines parameters for ListEvents. type ListEventsParams struct { // Since Return records with `seq` strictly greater than this value. Pass `0` to read from the beginning of the retained journal. diff --git a/internal/httpapi/claim.go b/internal/httpapi/claim.go index ac6b57654..6b3001f19 100644 --- a/internal/httpapi/claim.go +++ b/internal/httpapi/claim.go @@ -429,6 +429,12 @@ func (p timedProvider) EdgeReader() (issueops.EdgeReader, error) { return uow.NewEdgeReader(p) } +// GraphCounter builds the edge-count role OVER THIS WRAPPER, for the same +// reason and with the same hazard as IssueReader. +func (p timedProvider) GraphCounter() (issueops.GraphCounter, error) { + return uow.NewGraphCounter(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) { diff --git a/internal/httpapi/edge_counts_test.go b/internal/httpapi/edge_counts_test.go new file mode 100644 index 000000000..9f3f52501 --- /dev/null +++ b/internal/httpapi/edge_counts_test.go @@ -0,0 +1,376 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "reflect" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// The wire edge of GET /v0/beads/dependencies:count, on a fake role. +// +// The handler is a decoder, a bound and a projection — the plane span, the +// missing-anchor rule, the status asymmetry and the de-duplication are +// issueops.GraphCounter's, 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, and that +// each of the role's four refusals arrives naming the right parameter. + +func newEdgeCountServer(t *testing.T, result issueops.EdgeCountResult) (*testServer, *roleGraphCounter) { + t.Helper() + counter := &roleGraphCounter{result: result} + return newTestServer(t, rolesConfig(Config{GraphCounter: counter})), counter +} + +// TestCountDependencyEdgesProjectsTheWholeRequest drives every parameter, 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 single-parameter case wrong. +// +// `direction` gets both of its values: the vocabulary is CLOSED and the two +// answers are about different edge sets, so a handler that passed a constant +// would look right on whichever value the fixture happened to use. +func TestCountDependencyEdgesProjectsTheWholeRequest(t *testing.T) { + for _, tc := range []struct { + name string + query string + want issueops.EdgeCountRequest + }{ + { + name: "anchors and the outbound direction", + query: "?issue_id=bd-1&issue_id=bd-2&direction=out", + want: issueops.EdgeCountRequest{ + IDs: []string{"bd-1", "bd-2"}, + Direction: issueops.EdgeDirectionOut, + }, + }, + { + name: "the inbound direction", + query: "?issue_id=bd-1&direction=in", + want: issueops.EdgeCountRequest{ + IDs: []string{"bd-1"}, + Direction: issueops.EdgeDirectionIn, + }, + }, + { + name: "types narrow the edges", + query: "?issue_id=bd-1&direction=out&type=blocks&type=parent-child", + want: issueops.EdgeCountRequest{ + IDs: []string{"bd-1"}, + Direction: issueops.EdgeDirectionOut, + Types: []types.DependencyType{types.DepBlocks, types.DepParentChild}, + }, + }, + { + name: "status rides with the inbound direction", + query: "?issue_id=bd-1&direction=in&status=open", + want: issueops.EdgeCountRequest{ + IDs: []string{"bd-1"}, + Direction: issueops.EdgeDirectionIn, + Status: "open", + }, + }, + { + // A repeated id is NOT collapsed here. De-duplication is the + // ROLE's promise, made on the request it received, so a handler + // that collapsed first would be a second implementation of it — + // and one the role's own contract could never observe. + name: "a repeated id reaches the role as sent", + query: "?issue_id=bd-1&issue_id=bd-1&direction=out", + want: issueops.EdgeCountRequest{ + IDs: []string{"bd-1", "bd-1"}, + Direction: issueops.EdgeDirectionOut, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ts, counter := newEdgeCountServer(t, issueops.EdgeCountResult{}) + + resp := ts.get(t, "/v0/beads/dependencies:count"+tc.query) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + reqs := counter.countRequests() + if len(reqs) != 1 { + t.Fatalf("%d counts ran, want 1", len(reqs)) + } + if !reflect.DeepEqual(reqs[0], tc.want) { + t.Errorf("EdgeCountRequest = %+v, want %+v", reqs[0], tc.want) + } + }) + } +} + +// TestCountDependencyEdgesAnswersPerAnchor is the response half: the role's +// answer arrives per anchor, in the role's order, with both members on every +// entry. +// +// The fixture mixes a present anchor with edges, a present anchor with NONE and +// a MISSING one, because those are the three states a caller has to be able to +// tell apart and two of them share a count of 0. A response that dropped +// `missing`, or omitted a zero `count`, would make them indistinguishable while +// still carrying every anchor. +func TestCountDependencyEdgesAnswersPerAnchor(t *testing.T) { + ts, _ := newEdgeCountServer(t, issueops.EdgeCountResult{Anchors: []issueops.AnchorEdgeCount{ + {ID: "bd-1", Count: 3}, + {ID: "bd-empty", Count: 0}, + {ID: "bd-gone", Count: 0, Missing: true}, + }}) + + resp := ts.get(t, "/v0/beads/dependencies:count?issue_id=bd-1&issue_id=bd-empty&issue_id=bd-gone&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 { + Anchors []struct { + ID *string `json:"id"` + Count *int64 `json:"count"` + Missing *bool `json:"missing"` + } `json:"anchors"` + } + if err := json.Unmarshal(raw, &body); err != nil { + t.Fatalf("decode %q: %v", raw, err) + } + if len(body.Anchors) != 3 { + t.Fatalf("%d anchors, want 3: %s", len(body.Anchors), raw) + } + for i, want := range []struct { + id string + count int64 + missing bool + }{ + {"bd-1", 3, false}, + {"bd-empty", 0, false}, + {"bd-gone", 0, true}, + } { + got := body.Anchors[i] + // Pointers throughout: an OMITTED member is the failure this case + // exists for, and a value-typed decode would read it as the zero that + // happens to be correct for two of these three rows. + if got.ID == nil || got.Count == nil || got.Missing == nil { + t.Fatalf("anchor %d is missing a member: %s", i, raw) + } + if *got.ID != want.id || *got.Count != want.count || *got.Missing != want.missing { + t.Errorf("anchor %d = {%q %d %v}, want {%q %d %v}", + i, *got.ID, *got.Count, *got.Missing, want.id, want.count, want.missing) + } + } + // The index IS the order promise: the role answers in the order the request + // first named each anchor, and the handler is a projection that may not + // sort or reshape it. + if strings.Index(string(raw), `"bd-1"`) > strings.Index(string(raw), `"bd-gone"`) { + t.Errorf("the anchors were reordered: %s", raw) + } +} + +// TestCountDependencyEdgesAnswersAnEmptyArrayNotNull pins the one thing a Go +// nil slice gets wrong on the way out. `anchors` is required, so a client is +// entitled to range over it without a nil check. +func TestCountDependencyEdgesAnswersAnEmptyArrayNotNull(t *testing.T) { + ts, _ := newEdgeCountServer(t, issueops.EdgeCountResult{}) + + resp := ts.get(t, "/v0/beads/dependencies:count?issue_id=bd-1&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), `"anchors":[]`) { + t.Errorf("body = %s, want an empty `anchors` array rather than null", raw) + } +} + +// TestCountDependencyEdgesNamesTheRefusedParameter is where the handler earns +// its keep: the role publishes ONE sentinel for four different mistakes, and +// which parameter the client is told to fix comes from re-asking the request +// the validator's own questions. +// +// The last two cases are the ones a naive picker fails. A request carrying TWO +// offenders must name the one the validator reached FIRST — its order is part +// of its contract, and naming the second sends the caller to fix a parameter +// the server never evaluated. +func TestCountDependencyEdgesNamesTheRefusedParameter(t *testing.T) { + for _, tc := range []struct { + name string + query string + param string + }{ + {"no direction at all", "?issue_id=bd-1", "direction"}, + {"a direction outside the closed set", "?issue_id=bd-1&direction=both", "direction"}, + {"status beside the outbound direction", "?issue_id=bd-1&direction=out&status=open", "status"}, + {"an empty id", "?issue_id=bd-1&issue_id=&direction=out", "issue_id"}, + {"an unusable edge type", "?issue_id=bd-1&direction=out&type=", "type"}, + { + // direction is checked before status: a request that is wrong + // about both is a refusal about the direction. + name: "a bad direction beside a misplaced status", + query: "?issue_id=bd-1&direction=sideways&status=open", + param: "direction", + }, + { + // status is checked before the per-entry id scan. + name: "a misplaced status beside an empty id", + query: "?issue_id=&direction=out&status=open", + param: "status", + }, + } { + t.Run(tc.name, func(t *testing.T) { + counter := &roleGraphCounter{} + ts := newTestServer(t, rolesConfig(Config{GraphCounter: counter})) + // 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. + counter.err = issueops.ErrValidation + + resp := ts.get(t, "/v0/beads/dependencies:count"+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"]) + } + }) + } +} + +// TestCountDependencyEdgesBoundsTheQuestion pins this operation's OWN limits — +// the two the handler holds rather than the role, because they are statements +// about what one HTTP request may ask for and not about what an edge count +// means. +// +// Both assert that the role was never reached. A bound that refused after the +// read would have bounded nothing that costs anything. +func TestCountDependencyEdgesBoundsTheQuestion(t *testing.T) { + for _, tc := range []struct { + name string + query string + }{ + {"no anchors at all", "?direction=out"}, + {"one anchor past the cap", "?direction=out" + strings.Repeat("&issue_id=bd-1", maxDependencyAnchors+1)}, + } { + t.Run(tc.name, func(t *testing.T) { + ts, counter := newEdgeCountServer(t, issueops.EdgeCountResult{}) + + resp := ts.get(t, "/v0/beads/dependencies:count"+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"] != "issue_id" || body["reason"] != string(ReasonInvalidValue) { + t.Errorf("body = %v, want invalid_argument on issue_id with reason invalid_value", body) + } + if n := len(counter.countRequests()); n != 0 { + t.Errorf("%d counts ran; a refused request must not reach the database", n) + } + }) + } + + // The cap itself is reachable: a request AT the bound is served. Without + // this the two cases above would pass on an off-by-one that refused the + // hundredth anchor too. + ts, counter := newEdgeCountServer(t, issueops.EdgeCountResult{}) + resp := ts.get(t, "/v0/beads/dependencies:count?direction=out"+strings.Repeat("&issue_id=bd-1", maxDependencyAnchors)) + if resp.StatusCode != http.StatusOK { + t.Fatalf("at the cap: status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + if n := len(counter.countRequests()); n != 1 { + t.Errorf("%d counts ran at the cap, want 1", n) + } +} + +// TestCountDependencyEdgesStaysStrictAboutParameters 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 answer a DIFFERENT question from the one +// the caller asked — and the caller would have no way to notice. +func TestCountDependencyEdgesStaysStrictAboutParameters(t *testing.T) { + for _, tc := range []struct { + name string + query string + param string + reason Reason + }{ + {"an unknown key", "?issue_id=bd-1&direction=out&bogus=1", "bogus", ReasonUnknownParameter}, + {"a near miss on a real parameter", "?issue_id=bd-1&directions=out", "directions", ReasonUnknownParameter}, + {"direction sent twice", "?issue_id=bd-1&direction=out&direction=in", "direction", ReasonInvalidValue}, + {"status sent twice", "?issue_id=bd-1&direction=in&status=open&status=closed", "status", ReasonInvalidValue}, + } { + t.Run(tc.name, func(t *testing.T) { + ts, counter := newEdgeCountServer(t, issueops.EdgeCountResult{}) + + resp := ts.get(t, "/v0/beads/dependencies:count"+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(counter.countRequests()); n != 0 { + t.Errorf("%d counts ran for a refused request", n) + } + }) + } +} + +// TestCountDependencyEdgesReachesItsOwnRole is the wiring pin, and it is not +// ceremony: EdgeReader and GraphCounter are two roles on the same collection +// with adjacent accessors, so a handler wired to the reader would answer this +// operation's requests from the wrong surface. The reader's fake records what +// it was asked, and it must be asked nothing. +func TestCountDependencyEdgesReachesItsOwnRole(t *testing.T) { + counter := &roleGraphCounter{} + reader := &roleEdgeReader{} + ts := newTestServer(t, rolesConfig(Config{GraphCounter: counter, EdgeReader: reader})) + + resp := ts.get(t, "/v0/beads/dependencies:count?issue_id=bd-1&direction=out") + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + if n := len(counter.countRequests()); n != 1 { + t.Errorf("%d counts ran, want 1", n) + } + if n := len(reader.edgeRequests()); n != 0 { + t.Errorf("%d stored-edge reads ran; the count must not reach EdgeReader", n) + } +} + +// TestCountDependencyEdgesKeepsANonValidationFailureAtFiveHundred is the other +// half of classifying on the sentinel: an error that is NOT the role's +// request-validation refusal must not be reported as the caller's fault. +func TestCountDependencyEdgesKeepsANonValidationFailureAtFiveHundred(t *testing.T) { + counter := &roleGraphCounter{err: errors.New("backend is unreachable")} + ts := newTestServer(t, rolesConfig(Config{GraphCounter: counter})) + + resp := ts.get(t, "/v0/beads/dependencies:count?issue_id=bd-1&direction=out") + if resp.StatusCode != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(CodeInternal) { + t.Errorf("code = %v, want internal", body["code"]) + } +} diff --git a/internal/httpapi/edges.go b/internal/httpapi/edges.go index 8053cafa1..ad3adec85 100644 --- a/internal/httpapi/edges.go +++ b/internal/httpapi/edges.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net/http" + "slices" "github.com/steveyegge/beads/internal/httpapi/apigen" "github.com/steveyegge/beads/internal/types" @@ -66,6 +67,119 @@ func (s *Server) handleListDependencies(w http.ResponseWriter, r *http.Request) writeJSON(w, wireEdges(result)) } +// handleCountDependencyEdges answers GET /v0/beads/dependencies:count. +// +// Everything below the wire is on issueops.GraphCounter: which plane each +// anchor is probed on, that an absent anchor is a per-anchor miss rather than +// an error, that the count spans both dependency planes as a sum, the type and +// status filters, and the de-duplication of a repeated id. What stays here is +// transport — three repeatable-or-single parameters, the anchor bound, and +// projecting the role's answer onto the wire envelope. +// +// The DIRECTION is not validated here, deliberately. It is the role's closed +// vocabulary, and issueops.GraphCounter has ONE body on all three legs with +// ValidateEdgeCountRequest inside it, so refusing at the edge would be a second +// definition of the same rule — the opposite of GET /v0/beads/issues:count, +// where the handler owns its enum precisely because no role refusal is +// reachable there. Here four of them are, and failEdgeCountErr names the +// parameter for each. +func (s *Server) handleCountDependencyEdges(w http.ResponseWriter, r *http.Request) { + q := newQuery(r.URL.Query()) + + ids := q.list("issue_id") + req := issueops.EdgeCountRequest{ + IDs: ids, + Direction: issueops.EdgeDirection(q.str("direction")), + Status: q.str("status"), + } + for _, depType := range q.list("type") { + req.Types = append(req.Types, types.DependencyType(depType)) + } + + if !s.acceptQuery(w, r, q) { + return + } + // The anchor bound is this operation's own limit rather than a statement + // about what an edge count means, exactly as the stored-edge read's is — + // and it is the SAME bound, from the same constant, because the two + // operations bound the same thing on the same collection. + if len(ids) == 0 { + requestInfo(r.Context()).refuse("issue_id") + s.fail(w, r, InvalidArgument("issue_id", ReasonInvalidValue, "name at least one issue_id")) + return + } + if len(ids) > maxDependencyAnchors { + requestInfo(r.Context()).refuse("issue_id") + s.fail(w, r, InvalidArgument("issue_id", ReasonInvalidValue, + fmt.Sprintf("at most %d issue_id values per request, got %d", maxDependencyAnchors, len(ids)))) + return + } + + counter, err := s.graphCounter(r) + if err != nil { + s.failErr(w, r, err) + return + } + result, err := counter.CountEdges(r.Context(), req) + if err != nil { + s.failEdgeCountErr(w, r, err, req) + return + } + writeJSON(w, wireEdgeCounts(result)) +} + +// failEdgeCountErr answers a failed edge count. The role's four +// 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. +// +// It classifies on the SENTINEL, as failEdgeReadErr does, and picks the +// parameter to name by re-asking the request the validator's own questions IN +// THE VALIDATOR'S OWN ORDER. That order is part of ValidateEdgeCountRequest's +// contract — the direction is checked FIRST so an empty request is a refusal +// about the direction rather than an empty answer — and a picker that asked in +// a different order would name a second offender on a request carrying two, +// sending the caller to fix a parameter the server had not reached. +func (s *Server) failEdgeCountErr(w http.ResponseWriter, r *http.Request, err error, req issueops.EdgeCountRequest) { + if !errors.Is(err, issueops.ErrValidation) { + s.failErr(w, r, err) + return + } + param := "type" + switch { + case req.Direction != issueops.EdgeDirectionOut && req.Direction != issueops.EdgeDirectionIn: + param = "direction" + case req.Status != "" && req.Direction != issueops.EdgeDirectionIn: + param = "status" + case slices.Contains(req.IDs, ""): + param = "issue_id" + } + requestInfo(r.Context()).refuse(param) + s.fail(w, r, InvalidArgument(param, ReasonInvalidValue, err.Error())) +} + +// wireEdgeCounts projects the role's per-anchor answer onto the wire envelope. +// +// It does NOT flatten, which is the difference from wireEdges beside it. An +// edge row carries its own issue_id, so a flat array of rows loses nothing; a +// number does not, so the per-anchor shape is the answer and folding it would +// produce a total nobody asked for. +// +// `anchors` is non-nil so the body carries `[]` rather than `null`, and both +// `count` and `missing` are emitted on every entry — 0 is the common answer +// and `false` is a fact, so an omitted member on either would be ambiguous. +func wireEdgeCounts(result issueops.EdgeCountResult) apigen.EdgeCounts { + body := apigen.EdgeCounts{Anchors: []apigen.AnchorEdgeCount{}} + for _, anchor := range result.Anchors { + body.Anchors = append(body.Anchors, apigen.AnchorEdgeCount{ + Id: anchor.ID, + Count: anchor.Count, + Missing: anchor.Missing, + }) + } + return body +} + // failEdgeReadErr answers a failed stored-edge read. The role's two // request-validation refusals — an empty id, an unusable dependency type — are // the caller's own input and reach the client as the 400 they are; everything diff --git a/internal/httpapi/problem.go b/internal/httpapi/problem.go index d5bb2206b..64840fa79 100644 --- a/internal/httpapi/problem.go +++ b/internal/httpapi/problem.go @@ -403,6 +403,14 @@ const ( // member because it answers per named issue, reports the ids that named // nothing, and returns edges whose target this database holds no row for. OpListDependencies = "listDependencies" + // OpCountDependencyEdges sizes each anchor's edge set in ONE named + // direction, behind issueops.GraphCounter. It is NOT listDependencies + // counted: that operation is outgoing-only and takes no direction, this one + // REQUIRES one and answers about either end, so the two agree on a number + // only at direction=out. It is also not a third Counter method — that role + // answers about a set of ISSUES described by a predicate, and this one about + // EDGES anchored on ids, per anchor. + OpCountDependencyEdges = "countDependencyEdges" // 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 @@ -584,6 +592,22 @@ var operationCodes = map[string][]Code{ // the response's `missing` member, so a batch keeps the answers for the ids // that were found. A 404 would discard them. OpListDependencies: {CodeInvalidArgument, CodeUnauthenticated, CodeBusy, CodeDBUnavailable, CodeInternal}, + // The stored-edge read's vocabulary exactly, and no not_found for its + // reason: an id that names nothing is reported on its own anchor, so a + // batch keeps the answers for the ids that were found. The role has no + // ErrNotFound at all, which its doc states. + // + // Its 400 is BOTH the transport's and the ROLE's, which is what separates + // this row from GET /v0/beads/issues:count beside it. That operation + // refuses its one enum at the edge and reaches no role refusal; here + // ValidateEdgeCountRequest runs inside the single shared body — the role + // has one body on all three legs, so the check could not belong to an + // accessor — and four of its refusals are reachable over the wire: a + // missing or unrecognized direction, a status beside direction=out, an + // empty id, and a dependency type no edge could carry. Each reaches the + // client as the 400 it is, on the sentinel, with the parameter named in the + // validator's own order. + OpCountDependencyEdges: {CodeInvalidArgument, CodeUnauthenticated, CodeBusy, CodeDBUnavailable, CodeInternal}, // The same vocabulary as the stored-edge read beside it, and no not_found // 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. diff --git a/internal/httpapi/roles_test.go b/internal/httpapi/roles_test.go index 3d02a4a9a..210cb7de8 100644 --- a/internal/httpapi/roles_test.go +++ b/internal/httpapi/roles_test.go @@ -106,6 +106,34 @@ func (e *roleEdgeReader) edgeRequests() []issueops.EdgeReadRequest { return append([]issueops.EdgeReadRequest(nil), e.reads...) } +// roleGraphCounter is the edge-COUNT role of the store-shaped source, its own +// fake beside roleEdgeReader rather than a method on it: the two are separate +// roles with separate accessors, and one fake answering both would let a test +// pass on a server that had wired the count handler to the reader. +type roleGraphCounter struct { + result issueops.EdgeCountResult + err error + + mu sync.Mutex + counts []issueops.EdgeCountRequest +} + +func (c *roleGraphCounter) CountEdges(_ context.Context, req issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { + c.mu.Lock() + c.counts = append(c.counts, req) + c.mu.Unlock() + if c.err != nil { + return issueops.EdgeCountResult{}, c.err + } + return c.result, nil +} + +func (c *roleGraphCounter) countRequests() []issueops.EdgeCountRequest { + c.mu.Lock() + defer c.mu.Unlock() + return append([]issueops.EdgeCountRequest(nil), c.counts...) +} + // 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 @@ -802,6 +830,9 @@ func rolesConfig(cfg Config) Config { if cfg.EdgeReader == nil { cfg.EdgeReader = &roleEdgeReader{} } + if cfg.GraphCounter == nil { + cfg.GraphCounter = &roleGraphCounter{} + } if cfg.BlockingAnnotator == nil { cfg.BlockingAnnotator = &roleBlockingAnnotator{} } diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index 094926b4c..4bb0df8b9 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -321,6 +321,23 @@ var routeTable = []route{ implemented: true, handler: (*Server).handleListDependencies, }, + { + op: OpCountDependencyEdges, + method: http.MethodGet, + // A collection-level custom method on the dependency collection, + // spelled the way ready:count and issues:count are: both segments are + // LITERAL, so pattern and specPath agree and the router registers the + // documented path itself. + // + // It collides with nothing. The three literal paths under this + // collection — /cycles, /blocking, /tree — all carry a separating + // slash, and the plain collection GET is a different whole segment, + // which is what ServeMux matches on. + pattern: "/v0/beads/dependencies:count", + capability: "dependencies.count", + implemented: true, + handler: (*Server).handleCountDependencyEdges, + }, { op: OpListBlockingAnnotations, method: http.MethodGet, diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 07adce2fc..4e4b523d1 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -209,11 +209,18 @@ type Config struct { // hook-firing refusal below bites hardest on it: a store's own // IssueLifecycle() returns a role that fires on_create, on_update and the // close hooks for every mutation it lands. - Lifecycle issueops.Lifecycle - Settings issueops.WorkspaceConfig - Stats issueops.StatsReporter - CycleDetector issueops.CycleDetector - EdgeReader issueops.EdgeReader + Lifecycle issueops.Lifecycle + Settings issueops.WorkspaceConfig + Stats issueops.StatsReporter + CycleDetector issueops.CycleDetector + EdgeReader issueops.EdgeReader + // GraphCounter is the edge-count role behind + // GET /v0/beads/dependencies:count. It is a SEPARATE field from EdgeReader + // for the reason Counter is separate from ReadyCounter: that role answers + // 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 BlockingAnnotator issueops.BlockingAnnotator TreeWalker issueops.TreeWalker ReadyCounter issueops.ReadyCounter @@ -329,6 +336,7 @@ type Server struct { issueStats issueops.StatsReporter issueCycles issueops.CycleDetector issueEdges issueops.EdgeReader + issueEdgeCounter issueops.GraphCounter issueBlocking issueops.BlockingAnnotator issueTree issueops.TreeWalker issueReadyCounter issueops.ReadyCounter @@ -478,6 +486,7 @@ func Listen(cfg Config) (*Server, error) { issueStats: cfg.Stats, issueCycles: cfg.CycleDetector, issueEdges: cfg.EdgeReader, + issueEdgeCounter: cfg.GraphCounter, issueBlocking: cfg.BlockingAnnotator, issueTree: cfg.TreeWalker, issueReadyCounter: cfg.ReadyCounter, @@ -595,12 +604,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.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.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, 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, 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 }) @@ -897,6 +906,21 @@ func (s *Server) edgeReader(r *http.Request) (issueops.EdgeReader, error) { return src.EdgeReader() } +// graphCounter returns the edge-count surface for one request, built the same +// two ways as edgeReader above and held by INTERFACE so +// uow.GraphCounterSource is load-bearing rather than decorative. +// +// It goes out UNWRAPPED, for counter's reason: the role answers with a VALUE +// whose slice a nil-safe range walks, so no handler dereferences a pointer it +// returned and a checked wrapper would be ceremony that reads like a guarantee. +func (s *Server) graphCounter(r *http.Request) (issueops.GraphCounter, error) { + if s.provider == nil { + return s.issueEdgeCounter, nil + } + var src uow.GraphCounterSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())} + return src.GraphCounter() +} + // 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 diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index ef395326b..292cce393 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -4083,6 +4083,191 @@ paths: '503': $ref: '#/components/responses/Unavailable' + /v0/beads/dependencies:count: + get: + operationId: countDependencyEdges + summary: Count the dependency edges around several issues + description: >- + HOW MANY EDGES each named issue has in ONE named direction, after the + type and status filters — the cardinality behind + `GET /v0/beads/dependencies`, plus the direction that read does not + take. Nothing is materialized: this is the operation for a caller that + wants the numbers for issues whose edges it will never print. + + + IT IS NOT THE LISTING COUNTED, and the operationId says so rather than + pretending otherwise. The listing is OUTGOING ONLY and takes no + direction; this one REQUIRES a direction and answers about either end. + Naming it `countDependencies` would have promised that it sizes the set + `listDependencies` returns, which it does only at `direction=out`. + + + THE ANSWER IS PER ANCHOR, which is the other difference from the + listing. That one flattens every issue's edges onto one array because + the rows carry their own `issue_id`; a number does not, so folding + these together would produce a total no caller asked for and lose the + per-issue answer every caller wants. `anchors` carries one entry per + DISTINCT requested id, in the order the request first named it — an + array rather than an object, because the request's order is part of the + answer and a keyed object would have made that ordering this surface's + own invention. + + + A NAMED ISSUE THAT DOES NOT EXIST IS NOT A 404, on + `GET /v0/beads/dependencies`'s terms and one sharper: its entry reports + `missing: true` with `count: 0`, and 0 is the COMMON answer here — + most issues have no edges in at least one direction — so without that + flag a typo would be indistinguishable from a real zero and would never + surface. There is no `not_found` on this operation at all. + + + THE COUNT SPANS BOTH DEPENDENCY PLANES and is a SUM rather than a + distinct count of edge rows; a status-narrowed count reads the + dependent's status from its own plane; and `status` is legal only with + `direction=in` because an outbound edge's far end may be a row this + database does not hold. Those are the ROLE's rules, stated once at + `issueops.GraphCounter` and its `EdgeCountRequest`, and this document + cites them rather than restating them — a second telling is a second + thing to keep true. + + + THERE IS NO `limit` AND NO CURSOR, for the reason + `GET /v0/beads/dependencies` has none and `GET /v0/beads/issues:count` + gives: a cardinality has no page, and bounding the scan would answer + "how many of the first N". The QUESTION is bounded instead, at 100 + `issue_id` values per call — the same bound, the same number and the + same constant as the listing on this collection, because the two bound + the same thing and a client holding both must not have to learn two + numbers. + + + THERE IS NO `both` DIRECTION. A caller that wants the pair asks twice, + which is what every front door in the tree already does. One call + answering both would mean two numbers per anchor, and `status` — which + narrows by a row only the inbound direction has — would then govern one + of them and silently not the other. + parameters: + - name: issue_id + in: query + description: >- + The anchors to count around. Repeat the parameter; at least one is + required and at most 100 are accepted, and either bound is a 400 + `invalid_argument` with `param: "issue_id"`, `reason: + "invalid_value"`. + + + Each value must be an EXACT canonical issue id, for the reason + `GET /v0/beads/dependencies` gives. A value that matches nothing is + reported on its own anchor rather than refused. An EMPTY value is a + 400: the empty string names nothing a caller can have meant, and + reporting it as a missing anchor would put a nameless row in an + answer keyed by name. + + + Repeats collapse onto the first mention — a second entry carries no + second fact and would only invite a caller summing the result to + count the same edges twice. + style: form + explode: true + required: true + schema: + type: array + minItems: 1 + maxItems: 100 + items: + type: string + - name: direction + in: query + required: true + description: >- + Which end of the edge the anchors sit on. `out` counts what each + anchor DEPENDS ON — the direction `bd dep list` reads and the number + `bd show` prints as the dependency count. `in` counts what depends + on it. + + + IT IS REQUIRED, and that is the one deliberate unfriendliness on + this request. The two answers are about DIFFERENT EDGE SETS, and a + workspace where most issues have edges in only one direction returns + the same number for both often enough that a caller who meant the + other one would not notice for a long time. An absent or + unrecognized value is a 400 `invalid_argument` with + `param: "direction"`, never a count 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`. + + + The filter narrows EDGES, never anchors. An anchor whose every edge + it rejects comes back present with a count of 0, which is a + different fact from an anchor that is not there. + style: form + explode: true + schema: + type: array + items: + type: string + - name: status + in: query + description: >- + Count only edges whose DEPENDENT — the issue at the source end, the + one doing the depending — is in this stored status. Empty means + every status. + + + IT IS LEGAL ONLY WITH `direction=in`. Sending it beside + `direction=out` is a 400 `invalid_argument` with `param: "status"` + and `reason: "invalid_value"`, rather than a filter that is quietly + ignored. The asymmetry is the substrate's and + `issueops.EdgeCountRequest.Status` states why: narrowing by status + joins the far end of the edge to the row holding its status, and an + OUTBOUND edge's far end may be an `external:` reference or an id + belonging to another repository — rows this database does not hold + — so the filter would silently drop every dangling edge. + + + It is ONE status, not a comma-separated OR set, and it is NOT + validated against the workspace vocabulary: an unrecognized name + matches nothing and counts 0 rather than failing, exactly as + `GET /v0/beads/issues:count`'s `status` does. A scripted caller + counting a status its workspace has since dropped reads 0 and + should keep reading 0. + schema: + type: string + security: + - bearerToken: [] + responses: + '200': + description: One entry per distinct anchor, in the order first named. + content: + application/json: + schema: + $ref: '#/components/schemas/EdgeCounts' + '400': + $ref: '#/components/responses/InvalidArgument' + '401': + $ref: '#/components/responses/Unauthenticated' + '500': + $ref: '#/components/responses/InternalError' + '503': + $ref: '#/components/responses/Unavailable' + /v0/beads/dependencies/blocking: get: operationId: listBlockingAnnotations @@ -6298,7 +6483,8 @@ components: `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, - `dependencies.list`, `dependencies.blocking`, `dependencies.tree`, + `dependencies.list`, `dependencies.count`, + `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, @@ -7247,6 +7433,95 @@ components: items: type: string + EdgeCounts: + type: object + description: >- + Each anchor's edge cardinality — the body of + `GET /v0/beads/dependencies:count`. It is NOT a page and carries no + total: the answer is per anchor, and a sum across anchors would + double-count every edge whose two ends were both named. + + + It is NOT `x-go-type`-pinned, for `IssueCount`'s reason: there is no + canonical Go struct whose JSON encoding is this contract. The role + answers with `issueops.EdgeCountResult`, whose members carry no JSON + tags at all because nothing marshals it. + required: [anchors] + properties: + anchors: + type: array + description: >- + One entry per DISTINCT requested `issue_id`, in the order the + request first named it. Empty array (never null) when the request + named no anchors this server accepted — which it cannot, since + `issue_id` is required and bounded below at one. + + + A repeated id appears ONCE. The collapse happens before anything is + counted, so a caller that summed the entries would not count the + same edges twice. + items: + $ref: '#/components/schemas/AnchorEdgeCount' + + AnchorEdgeCount: + type: object + description: One anchor's edge cardinality, or the report that it is not there. + required: [id, count, missing] + properties: + id: + type: string + description: >- + The anchor, spelled exactly as the request spelled it. It is not + re-canonicalized: there is no fuzzy, prefix or substring resolution + on this surface, so what comes back is what went out. + count: + type: integer + format: int64 + description: >- + How many stored edges match, in the requested direction, after the + type and status filters. Never negative. + + + It SPANS BOTH DEPENDENCY PLANES and is a SUM over them rather than a + distinct count of edge rows — a durable issue's dependent count + includes the wisps that depend on it, and a wisp's dependency count + includes the durable issues it depends on. + `issueops.AnchorEdgeCount.Count` states the rule, the one state that + can make the sum differ from a distinct count, and why this role + answers with the sum. Nothing is restated here. + + + ALWAYS PRESENT, including as 0, and 0 is the COMMON answer: most + issues have no edges in at least one direction. It is 0 for a + missing anchor too, which is exactly why `missing` is beside it. + + + DECODE IT AS A 64-BIT INTEGER. The member is `format: int64` and a + workspace's graph is not bounded by 2^53; a lossy parser would + answer a number NEAR the count, which on a cardinality is worse + than an error because nothing downstream can tell. + missing: + type: boolean + description: >- + True when no issue and no wisp carries this id. + + + ALWAYS PRESENT, including as `false`. It is the member that keeps + this from being a question a caller cannot tell it got wrong: a + count of 0 is otherwise indistinguishable from a typo, and an + absent boolean would be ambiguous between "present" and "this + producer does not report misses". + + + A missing anchor counts 0 whatever rows are still keyed to it — a + dependency row whose source has been deleted is orphaned data, and + counting it would contradict this flag. + + + DANGLING EDGES ARE NOT MISSING ANCHORS. This is about the ANCHOR. An + edge whose OTHER end names nothing is counted like any other edge, + and nothing here reports on it. + BlockingAnnotations: type: object description: >- diff --git a/internal/httpapi/spec_parity_test.go b/internal/httpapi/spec_parity_test.go index 6e6c0b147..0e8f5cd61 100644 --- a/internal/httpapi/spec_parity_test.go +++ b/internal/httpapi/spec_parity_test.go @@ -386,6 +386,36 @@ func TestSpecDefaultsMatchSharedConstants(t *testing.T) { t.Errorf("%s: limit description does not document the non-loopback refusal of limit=0", tc.opID) } } + + // The anchor bound on ALL THREE dependency-collection reads. Each bounds + // the same thing — how many issues one call may ask about — from the same + // maxDependencyAnchors, and each says so in prose. Nothing kept the + // document's number and the constant together until this: the bound is + // enforced in the handler, so a spec that drifted to a different maxItems + // would be refused by the server it documents, at a number no reader could + // have predicted. + // + // THE THIRD ROW IS THE POINT. listBlockingAnnotations enforces the same + // constant (blocking.go) and declares the same maxItems, and it predates + // this gate — so a two-operation loop would have pinned the copies that + // happened to be in the slice that wrote it and left the oldest one free + // to drift. Every operation reading maxDependencyAnchors belongs here, and + // the next one to do so must be added. + for _, opID := range []string{OpListDependencies, OpCountDependencyEdges, OpListBlockingAnnotations} { + so, ok := ops[opID] + if !ok { + t.Fatalf("operation %q missing from the spec", opID) + } + schema := mapAt(t, specParam(t, so, "issue_id"), "schema") + if got, ok := schema["maxItems"].(int); !ok || got != maxDependencyAnchors { + t.Errorf("%s: issue_id maxItems = %v, want the shared bound %d", opID, schema["maxItems"], maxDependencyAnchors) + } + // At least one is required on both, and the schema is where a + // generated client learns it. + if got, ok := schema["minItems"].(int); !ok || got != 1 { + t.Errorf("%s: issue_id minItems = %v, want 1", opID, schema["minItems"]) + } + } } // capabilityToken matches one backticked capability token in the