diff --git a/backend/conformance/graph_counter_contract.go b/backend/conformance/graph_counter_contract.go new file mode 100644 index 000000000..eda7e500e --- /dev/null +++ b/backend/conformance/graph_counter_contract.go @@ -0,0 +1,578 @@ +package conformance + +import ( + "context" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of publicops.GraphCounter +// must satisfy. Each case asserts what issueops/graphcounter.go PROMISES, cited +// by symbol; a backend that disagrees is parked at its own wiring site with +// skipKnownDivergence so the case still runs on the ones that agree. +// +// THREE LEGS, ONE BODY. All three reach the same +// storage/issueops.ExecuteEdgeCount: the two stores wrap it in their own read +// transaction, and the unit-of-work provider reaches it through the domain +// repository, whose runner publishes exactly the DBTX method set that function +// takes. So a three-leg run here is ONE READING plus two engine checks and +// three wrapper checks — the same arithmetic TreeWalker's and MetadataCAS's +// contracts state — and it is still worth running, because every measured drift +// in the graph family has lived in a WRAPPER. The cases are written for that: +// they assert SENTINELS rather than message text, so a wrapper that loses a +// transaction, drops a request field or breaks errors.Is is what a per-leg +// failure would actually be. +// +// The parts of the answer that are pure — the missing-anchor rule and the +// request vocabulary — are pinned without a database beside the body +// (internal/storage/issueops/edge_counts_test.go), so what is left here is what +// only a real backend can show: which rows the two dependency planes actually +// contribute, and what a status join reaches. +// +// EVERY CASE NAMES THE EXACT IDS IT SEEDED. The three fixtures share one +// database per suite and the two store fixtures share it with every other +// role's cases, so an assertion that read "every anchor" would be an assertion +// about the whole workspace and would fail the moment a sibling suite seeded a +// row. +// +// What is deliberately NOT here: +// - the comment count and the event count, which this role excludes and says +// why at GraphCounter's doc; +// - a "both directions" request, which this role does not have (see +// EdgeCountRequest's doc) — the two directions are asserted as two calls, +// which is what a caller wanting the pair does; +// - anything about the far end's existence, which this role does not probe: +// a dangling target is counted like any other edge (AnchorEdgeCount.Missing +// says so), and RunGraphCounterCountsOutboundEdges seeds one to prove it. + +// GraphCounterFixture supplies adapter-specific storage access for the +// edge-count assertions. Every field is named and typed exactly like the +// per-backend roleFixtureKit hook it is filled from. +type GraphCounterFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + GraphCounter publicops.GraphCounter + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than an Ephemeral flag on CreateIssue because the three + // adapters reach the two planes through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge, routed to the plane the edge's source lives + // in. That routing is what makes the cross-plane cases possible at all: a + // wisp source puts its edge in wisp_dependencies and nothing else can. + AddDependency func(context.Context, *types.Dependency, string) error + // CountHistory reports how many history entries the fixture's branch has. + // A nil hook means "this backend cannot observe history", and the case that + // needs it SKIPS rather than passing quietly. + CountHistory func(context.Context) (int, error) +} + +// RunGraphCounterCountsOutboundEdges pins EdgeDirectionOut: the anchor's +// DEPENDENCIES, the edges whose source is the anchor. +// +// One of the three targets is a dangling "external:" reference, which pins +// AnchorEdgeCount.Missing's last paragraph: this role does not probe the far +// end, so an edge to a row no database holds still counts. A body that joined +// the target to an issue table to count would answer 2 here. +func RunGraphCounterCountsOutboundEdges(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-out-src" + first := fixture.IssuePrefix + "-out-a" + second := fixture.IssuePrefix + "-out-b" + dangling := "external:" + fixture.IssuePrefix + "-out-ext" + seedGraphCounterIssues(t, ctx, fixture, anchor, first, second) + seedGraphCounterEdge(t, ctx, fixture, anchor, first, types.DepBlocks) + seedGraphCounterEdge(t, ctx, fixture, anchor, second, types.DepBlocks) + seedGraphCounterEdge(t, ctx, fixture, anchor, dangling, types.DepRelated) + + result := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterCount(t, result, anchor, 3) + + // The two targets have no outbound edges of their own, so the same request + // answers 0 for them — which is what makes the number above the anchor's + // and not the workspace's. + zeroes := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{first, second}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterCount(t, zeroes, first, 0) + assertGraphCounterCount(t, zeroes, second, 0) +} + +// RunGraphCounterCountsInboundEdges pins EdgeDirectionIn: the anchor's +// DEPENDENTS, the edges whose target is the anchor. +// +// The graph is deliberately ASYMMETRIC — the anchor has two dependents and one +// dependency — so the two directions answer different numbers over the same +// rows. An implementation that ignored Direction, or that answered a constant, +// passes neither this case nor the one above. +func RunGraphCounterCountsInboundEdges(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-in-target" + dependentA := fixture.IssuePrefix + "-in-dep-a" + dependentB := fixture.IssuePrefix + "-in-dep-b" + dependency := fixture.IssuePrefix + "-in-blocker" + seedGraphCounterIssues(t, ctx, fixture, anchor, dependentA, dependentB, dependency) + seedGraphCounterEdge(t, ctx, fixture, dependentA, anchor, types.DepBlocks) + seedGraphCounterEdge(t, ctx, fixture, dependentB, anchor, types.DepBlocks) + seedGraphCounterEdge(t, ctx, fixture, anchor, dependency, types.DepBlocks) + + inbound := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionIn, + }) + assertGraphCounterCount(t, inbound, anchor, 2) + + outbound := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterCount(t, outbound, anchor, 1) +} + +// RunGraphCounterAnswersOnePerAnchorInRequestOrder pins +// EdgeCountResult.Anchors: one entry per requested id, in the order the request +// named them. The ids are seeded in the REVERSE of that order, so a body that +// answered in the storage seam's natural order (ascending by id) fails rather +// than passing by coincidence. +func RunGraphCounterAnswersOnePerAnchorInRequestOrder(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + first := fixture.IssuePrefix + "-order-c" + second := fixture.IssuePrefix + "-order-b" + third := fixture.IssuePrefix + "-order-a" + seedGraphCounterIssues(t, ctx, fixture, first, second, third) + + result := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{first, second, third}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterAnchorIDs(t, result, first, second, third) +} + +// RunGraphCounterDistinguishesNoEdgesFromNoAnchor pins AnchorEdgeCount.Missing. +// An issue with no dependencies is the COMMON case and answers 0, so a body +// that reported presence from "did any edges come back" would pass every other +// case in this file and fail only here. +// +// The ghost is named BETWEEN two real anchors deliberately: a case whose ghost +// came last could not tell a correct body from one that short-circuited on the +// first miss. +func RunGraphCounterDistinguishesNoEdgesFromNoAnchor(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + bare := fixture.IssuePrefix + "-bare-present" + ghost := fixture.IssuePrefix + "-bare-absent" + real2 := fixture.IssuePrefix + "-bare-real2" + seedGraphCounterIssues(t, ctx, fixture, bare, real2) + + result := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{bare, ghost, real2}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterAnchorIDs(t, result, bare, ghost, real2) + assertGraphCounterMissing(t, result, bare, false) + assertGraphCounterCount(t, result, bare, 0) + assertGraphCounterMissing(t, result, ghost, true) + assertGraphCounterCount(t, result, ghost, 0) + assertGraphCounterMissing(t, result, real2, false) +} + +// RunGraphCounterCollapsesRepeatedAnchors pins EdgeCountRequest.IDs's repeats +// clause: an id named twice is one anchor, at the position of its first +// mention. The repeat is placed AFTER a different anchor, so a body that +// de-duplicated by sorting rather than by first mention answers b, a instead of +// a, b and fails. +func RunGraphCounterCollapsesRepeatedAnchors(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + first := fixture.IssuePrefix + "-dup-b" + second := fixture.IssuePrefix + "-dup-a" + target := fixture.IssuePrefix + "-dup-target" + seedGraphCounterIssues(t, ctx, fixture, first, second, target) + seedGraphCounterEdge(t, ctx, fixture, first, target, types.DepBlocks) + + result := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{first, second, first, second, first}, + Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterAnchorIDs(t, result, first, second) + // One anchor, one tally: a body that accumulated per mention would answer 3. + assertGraphCounterCount(t, result, first, 1) +} + +// RunGraphCounterFiltersEdgesNotAnchors pins EdgeCountRequest.Types: the filter +// narrows edges, and an anchor whose every edge it rejects stays present with a +// count of 0. A body that dropped it would turn a filtered count into a report +// that the issue does not exist. +// +// The second half pins the OPEN vocabulary from the same field: a type no edge +// carries is accepted and matches nothing, rather than being refused. +func RunGraphCounterFiltersEdgesNotAnchors(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + kept := fixture.IssuePrefix + "-filter-kept" + dropped := fixture.IssuePrefix + "-filter-dropped" + blocker := fixture.IssuePrefix + "-filter-blocker" + related := fixture.IssuePrefix + "-filter-related" + seedGraphCounterIssues(t, ctx, fixture, kept, dropped, blocker, related) + seedGraphCounterEdge(t, ctx, fixture, kept, blocker, types.DepBlocks) + seedGraphCounterEdge(t, ctx, fixture, kept, related, types.DepRelated) + seedGraphCounterEdge(t, ctx, fixture, dropped, related, types.DepRelated) + + filtered := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{kept, dropped}, + Direction: publicops.EdgeDirectionOut, + Types: []types.DependencyType{types.DepBlocks}, + }) + assertGraphCounterAnchorIDs(t, filtered, kept, dropped) + assertGraphCounterCount(t, filtered, kept, 1) + assertGraphCounterMissing(t, filtered, dropped, false) + assertGraphCounterCount(t, filtered, dropped, 0) + + // Unfiltered, the same anchor carries both edges — so the number above is + // the filter's work and not the seed's. + all := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{kept}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterCount(t, all, kept, 2) + + invented := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{kept}, + Direction: publicops.EdgeDirectionOut, + Types: []types.DependencyType{"workspace-invented-type"}, + }) + assertGraphCounterMissing(t, invented, kept, false) + assertGraphCounterCount(t, invented, kept, 0) +} + +// RunGraphCounterNarrowsInboundByDependentStatus pins EdgeCountRequest.Status: +// the filter is on the DEPENDENT's stored status, the row at the source end of +// the inbound edge. +// +// Both dependents are seeded FIRST and the closed one is seeded closed, because +// the fixture kit's create is the only write these cases have. A body that +// joined the ANCHOR's status instead would answer 2 for open and 0 for closed, +// which is why the anchor is left open and both numbers are asserted. +func RunGraphCounterNarrowsInboundByDependentStatus(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-status-target" + openDep := fixture.IssuePrefix + "-status-open" + closedDep := fixture.IssuePrefix + "-status-closed" + seedGraphCounterIssues(t, ctx, fixture, anchor, openDep) + seedGraphCounterIssueWithStatus(t, ctx, fixture, closedDep, types.StatusClosed) + seedGraphCounterEdge(t, ctx, fixture, openDep, anchor, types.DepBlocks) + seedGraphCounterEdge(t, ctx, fixture, closedDep, anchor, types.DepBlocks) + + unnarrowed := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionIn, + }) + assertGraphCounterCount(t, unnarrowed, anchor, 2) + + for _, test := range []struct { + status string + want int64 + }{ + {string(types.StatusOpen), 1}, + {string(types.StatusClosed), 1}, + // Not validated against the workspace vocabulary: an unrecognized name + // counts 0 rather than failing. + {"never-a-status-here", 0}, + } { + narrowed := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionIn, Status: test.status, + }) + assertGraphCounterMissing(t, narrowed, anchor, false) + if got := graphCounterAnchor(t, narrowed, anchor).Count; got != test.want { + t.Errorf("inbound count of %s narrowed to status %q = %d, want %d", anchor, test.status, got, test.want) + } + } +} + +// RunGraphCounterCountsAcrossBothPlanes pins AnchorEdgeCount.Count's +// plane-spanning clause. The seed routes by SOURCE, so a wisp that depends on a +// durable issue puts its edge in wisp_dependencies and nothing else can — and a +// body that read only `dependencies` answers 1 instead of 2 for the durable +// anchor, and 0 instead of 1 for the wisp. +func RunGraphCounterCountsAcrossBothPlanes(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-plane-target" + durableDep := fixture.IssuePrefix + "-plane-durable" + wispDep := fixture.IssuePrefix + "-plane-wisp" + seedGraphCounterIssues(t, ctx, fixture, anchor, durableDep) + seedGraphCounterWisp(t, ctx, fixture, wispDep) + seedGraphCounterEdge(t, ctx, fixture, durableDep, anchor, types.DepBlocks) + seedGraphCounterEdge(t, ctx, fixture, wispDep, anchor, types.DepBlocks) + + inbound := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionIn, + }) + assertGraphCounterCount(t, inbound, anchor, 2) + + // The wisp is an anchor in its own right, on the ephemeral plane, and its + // outbound edge is the one that lives in wisp_dependencies. + outbound := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{wispDep}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterMissing(t, outbound, wispDep, false) + assertGraphCounterCount(t, outbound, wispDep, 1) +} + +// RunGraphCounterNarrowsAWispDependentByStatus pins the ephemeral half of the +// status join, which is a SEPARATE SQL branch from the durable one: the +// dependent's status is read from `wisps` for an edge in wisp_dependencies and +// from `issues` for an edge in dependencies. +// +// A body that joined `issues` for both planes answers 0 here — the wisp has no +// row there — and still passes RunGraphCounterNarrowsInboundByDependentStatus, +// which is why this case exists beside it rather than inside it. +func RunGraphCounterNarrowsAWispDependentByStatus(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-wispstatus-target" + wispDep := fixture.IssuePrefix + "-wispstatus-wisp" + seedGraphCounterIssues(t, ctx, fixture, anchor) + seedGraphCounterWisp(t, ctx, fixture, wispDep) + seedGraphCounterEdge(t, ctx, fixture, wispDep, anchor, types.DepBlocks) + + matching := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionIn, Status: string(types.StatusOpen), + }) + assertGraphCounterCount(t, matching, anchor, 1) + + missing := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionIn, Status: string(types.StatusClosed), + }) + assertGraphCounterCount(t, missing, anchor, 0) +} + +// RunGraphCounterResolvesIDsExactly pins EdgeCountRequest.IDs's exactness +// clause: a prefix of a real id, a case variant and an id carrying whitespace +// are all misses, not resolutions. They are misses rather than errors: this +// role reports them beside the anchor that did resolve. +func RunGraphCounterResolvesIDsExactly(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-exact-anchor" + target := fixture.IssuePrefix + "-exact-target" + seedGraphCounterIssues(t, ctx, fixture, anchor, target) + seedGraphCounterEdge(t, ctx, fixture, anchor, target, types.DepBlocks) + + prefix := anchor[:len(anchor)-2] + spaced := " " + anchor + " " + result := countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor, prefix, spaced}, Direction: publicops.EdgeDirectionOut, + }) + assertGraphCounterAnchorIDs(t, result, anchor, prefix, spaced) + assertGraphCounterMissing(t, result, anchor, false) + assertGraphCounterCount(t, result, anchor, 1) + assertGraphCounterMissing(t, result, prefix, true) + assertGraphCounterCount(t, result, prefix, 0) + assertGraphCounterMissing(t, result, spaced, true) + assertGraphCounterCount(t, result, spaced, 0) +} + +// RunGraphCounterAnswersAnEmptyRequest pins EdgeCountRequest.IDs's empty-slice +// clause: no anchors is not an error, it is an answer with no anchors — and the +// slice is never nil, so a front door that marshals it emits [] rather than +// null. +func RunGraphCounterAnswersAnEmptyRequest(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + result, err := fixture.GraphCounter.CountEdges(ctx, publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionIn, + }) + if err != nil { + t.Fatalf("CountEdges with no ids = %v, want an empty answer", err) + } + if len(result.Anchors) != 0 { + t.Fatalf("CountEdges with no ids returned %d anchors, want none", len(result.Anchors)) + } + if result.Anchors == nil { + t.Error("Anchors is nil; the contract promises it is never nil for a successful call") + } +} + +// RunGraphCounterRefusesAnUnusableRequest pins the request vocabulary at +// ValidateEdgeCountRequest, one refusal per clause of the leaf doc. +// +// The direction cases are asserted with NO IDS, which is the sharp half of the +// ordering promise: an empty request is a refusal about the direction rather +// than the empty answer the case above returns for a well-formed one. +func RunGraphCounterRefusesAnUnusableRequest(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-refuse-anchor" + seedGraphCounterIssues(t, ctx, fixture, anchor) + + for _, test := range []struct { + name string + req publicops.EdgeCountRequest + }{ + {"no direction at all", publicops.EdgeCountRequest{}}, + {"no direction beside real ids", publicops.EdgeCountRequest{IDs: []string{anchor}}}, + {"a direction outside the set", publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirection("sideways")}}, + {"a status on the outbound direction", publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionOut, Status: string(types.StatusOpen)}}, + {"an empty id beside a real one", publicops.EdgeCountRequest{ + IDs: []string{anchor, ""}, Direction: publicops.EdgeDirectionOut}}, + {"an unusable dependency type", publicops.EdgeCountRequest{ + IDs: []string{anchor}, Direction: publicops.EdgeDirectionOut, + Types: []types.DependencyType{""}}}, + } { + _, err := fixture.GraphCounter.CountEdges(ctx, test.req) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("CountEdges with %s = %v, want ErrValidation", test.name, err) + } + } +} + +// RunGraphCounterLeavesTheRequestAlone pins the no-mutation clause on +// GraphCounter. IDs and Types are the two members a body could write through to +// the caller, and de-duplication and filtering are exactly the steps that would. +func RunGraphCounterLeavesTheRequestAlone(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-immutable-anchor" + target := fixture.IssuePrefix + "-immutable-target" + seedGraphCounterIssues(t, ctx, fixture, anchor, target) + seedGraphCounterEdge(t, ctx, fixture, anchor, target, types.DepBlocks) + + ids := []string{anchor, anchor, target} + depTypes := []types.DependencyType{types.DepRelated, types.DepBlocks} + countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: ids, Direction: publicops.EdgeDirectionOut, Types: depTypes, + }) + + if len(ids) != 3 || ids[0] != anchor || ids[1] != anchor || ids[2] != target { + t.Errorf("the request's IDs slice is now %v; the contract says a body de-duplicates into its own copy", ids) + } + if len(depTypes) != 2 || depTypes[0] != types.DepRelated || depTypes[1] != types.DepBlocks { + t.Errorf("the request's Types slice is now %v; the contract says a body reads it without reordering it", depTypes) + } +} + +// RunGraphCounterWritesNothing pins GraphCounter's read clause: counting +// records no history entry. The delta is taken around the calls rather than as +// an absolute count, because the seeds above it are versioned writes of their +// own. +func RunGraphCounterWritesNothing(t *testing.T, ctx context.Context, fixture GraphCounterFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("this backend cannot observe history, so the writes-nothing clause cannot be checked here") + } + anchor := fixture.IssuePrefix + "-quiet-anchor" + target := fixture.IssuePrefix + "-quiet-target" + ghost := fixture.IssuePrefix + "-quiet-ghost" + seedGraphCounterIssues(t, ctx, fixture, anchor, target) + seedGraphCounterEdge(t, ctx, fixture, anchor, target, types.DepBlocks) + + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + countEdges(t, ctx, fixture, publicops.EdgeCountRequest{ + IDs: []string{anchor, ghost}, Direction: publicops.EdgeDirectionOut, + }) + // A refusal changes nothing either, so the same delta covers both. + _, _ = fixture.GraphCounter.CountEdges(ctx, publicops.EdgeCountRequest{IDs: []string{""}}) + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before { + t.Fatalf("history entries went %d -> %d across two edge counts, want no change", before, after) + } +} + +func countEdges(t *testing.T, ctx context.Context, fixture GraphCounterFixture, request publicops.EdgeCountRequest) publicops.EdgeCountResult { + t.Helper() + result, err := fixture.GraphCounter.CountEdges(ctx, request) + if err != nil { + t.Fatalf("CountEdges(%v, %s): %v", request.IDs, request.Direction, err) + } + return result +} + +func seedGraphCounterIssues(t *testing.T, ctx context.Context, fixture GraphCounterFixture, ids ...string) { + t.Helper() + for _, id := range ids { + seedGraphCounterIssueWithStatus(t, ctx, fixture, id, types.StatusOpen) + } +} + +func seedGraphCounterIssueWithStatus(t *testing.T, ctx context.Context, fixture GraphCounterFixture, id string, status types.Status) { + t.Helper() + issue := graphCounterSeed(id, false) + issue.Status = status + if err := fixture.CreateIssue(ctx, issue, "graph-counter-seed"); err != nil { + t.Fatalf("seed issue %s: %v", id, err) + } +} + +func seedGraphCounterWisp(t *testing.T, ctx context.Context, fixture GraphCounterFixture, id string) { + t.Helper() + if err := fixture.CreateWisp(ctx, graphCounterSeed(id, true), "graph-counter-seed"); err != nil { + t.Fatalf("seed wisp %s: %v", id, err) + } +} + +func seedGraphCounterEdge(t *testing.T, ctx context.Context, fixture GraphCounterFixture, from, to string, depType types.DependencyType) { + t.Helper() + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: from, DependsOnID: to, Type: depType, + }, "graph-counter-seed"); err != nil { + t.Fatalf("seed edge %s -> %s (%s): %v", from, to, depType, err) + } +} + +func graphCounterSeed(id string, ephemeral bool) *types.Issue { + return &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: ephemeral, + } +} + +func graphCounterAnchor(t *testing.T, result publicops.EdgeCountResult, id string) publicops.AnchorEdgeCount { + t.Helper() + for _, anchor := range result.Anchors { + if anchor.ID == id { + return anchor + } + } + t.Fatalf("no anchor %q in the answer; got %v", id, graphCounterAnchorIDs(result)) + return publicops.AnchorEdgeCount{} +} + +func graphCounterAnchorIDs(result publicops.EdgeCountResult) []string { + out := make([]string, 0, len(result.Anchors)) + for _, anchor := range result.Anchors { + out = append(out, anchor.ID) + } + return out +} + +func assertGraphCounterAnchorIDs(t *testing.T, result publicops.EdgeCountResult, want ...string) { + t.Helper() + got := graphCounterAnchorIDs(result) + if len(got) != len(want) { + t.Fatalf("anchors = %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("anchors = %v, want %v", got, want) + } + } +} + +func assertGraphCounterMissing(t *testing.T, result publicops.EdgeCountResult, id string, want bool) { + t.Helper() + if got := graphCounterAnchor(t, result, id).Missing; got != want { + t.Errorf("anchor %s Missing = %t, want %t", id, got, want) + } +} + +func assertGraphCounterCount(t *testing.T, result publicops.EdgeCountResult, id string, want int64) { + t.Helper() + if got := graphCounterAnchor(t, result, id).Count; got != want { + t.Errorf("anchor %s Count = %d, want %d", id, got, want) + } +} diff --git a/backend/conformance/role_bundle.go b/backend/conformance/role_bundle.go index e68222dd9..91602c47e 100644 --- a/backend/conformance/role_bundle.go +++ b/backend/conformance/role_bundle.go @@ -90,6 +90,7 @@ type RoleContractBundle struct { Deleter func(t *testing.T) *DeleterFixture DependencyEditor func(t *testing.T) *DependencyEditorFixture EdgeReader func(t *testing.T) *EdgeReaderFixture + GraphCounter func(t *testing.T) *GraphCounterFixture Importer func(t *testing.T) *ImporterFixture LifecycleCloseReopen func(t *testing.T) *LifecycleCloseReopenFixture LifecycleCreate func(t *testing.T) *LifecycleCreateFixture diff --git a/backend/conformance/role_bundle_cases.go b/backend/conformance/role_bundle_cases.go index b0a3c173e..3b5f457af 100644 --- a/backend/conformance/role_bundle_cases.go +++ b/backend/conformance/role_bundle_cases.go @@ -296,6 +296,24 @@ var roleContractCases = []roleContract{ RunEdgeReaderWritesNothing, ), + roleCases("GraphCounter", "GraphCounter()", oncePerRole, + func(b RoleContractBundle) func(t *testing.T) *GraphCounterFixture { return b.GraphCounter }, + RunGraphCounterCountsOutboundEdges, + RunGraphCounterCountsInboundEdges, + RunGraphCounterAnswersOnePerAnchorInRequestOrder, + RunGraphCounterDistinguishesNoEdgesFromNoAnchor, + RunGraphCounterCollapsesRepeatedAnchors, + RunGraphCounterFiltersEdgesNotAnchors, + RunGraphCounterNarrowsInboundByDependentStatus, + RunGraphCounterCountsAcrossBothPlanes, + RunGraphCounterNarrowsAWispDependentByStatus, + RunGraphCounterResolvesIDsExactly, + RunGraphCounterAnswersAnEmptyRequest, + RunGraphCounterRefusesAnUnusableRequest, + RunGraphCounterLeavesTheRequestAlone, + RunGraphCounterWritesNothing, + ), + // The accessor named here is NOT a storage.DoltStorage one, alone among // these rows: Importer is served only by uow.ImporterSource, so a backend // built on the store interface has nothing to fill this field with and diff --git a/engdocs/ADDING_AN_ISSUEOPS_ROLE.md b/engdocs/ADDING_AN_ISSUEOPS_ROLE.md index cbe779cda..db1c812a1 100644 --- a/engdocs/ADDING_AN_ISSUEOPS_ROLE.md +++ b/engdocs/ADDING_AN_ISSUEOPS_ROLE.md @@ -498,6 +498,27 @@ is worse than no case. Say which mechanism actually holds a promise in the contract's coverage paragraph, and name the substrate that would make it observable. +**And validation moves WITH the body when there is only one.** `ExecuteEdgeRead` +leaves `ValidateEdgeReadRequest` to each accessor, because that role has two +bodies and the check belongs to each of them. `issueops.GraphCounter` has one +body on all three legs, so its validation runs INSIDE `ExecuteEdgeCount`: there +is no second implementation for a per-leg check to belong to, and a leg that +forgot to call the validator would be a leg answering a different contract with +nothing to notice it. Ask which shape you have before copying the accessor's +first three lines from a sibling. + +**A role whose front doors land later still lands whole, and says so.** The +checklist's steps 1-11 are the role; steps 12 and 13 are the front doors. +`issueops.GraphCounter` shipped with NEITHER — no `bd` command and no HTTP +operation — because the numbers it answers are already printed through +`internal/workapi`'s detail seam, which is shared with an HTTP handler and +therefore moves in a change with its own parity argument, and because the wire +operation was separately gated. That is `BatchApplier`'s absent CLI and +`VersionReconciler`'s absent HTTP at the same time, and it is only legible as a +decision if the leaf doc says it: what a facade-only slice buys is ONE place +where the role's rules are stated and held to on three legs, before either +surface has to agree with the other. + ## When the role's answer carries a JSON value Two traps, both found in review of `issueops.MetadataCAS` and both invisible to diff --git a/internal/jira/tracker_test.go b/internal/jira/tracker_test.go index 0c56b7024..5e10ffd63 100644 --- a/internal/jira/tracker_test.go +++ b/internal/jira/tracker_test.go @@ -698,6 +698,10 @@ func (s *configStore) TreeWalker() (issueops.TreeWalker, error) { return nil, &storage.ErrUnsupported{Op: "TreeWalker", Backend: "jira-config-stub"} } +func (s *configStore) GraphCounter() (issueops.GraphCounter, error) { + return nil, &storage.ErrUnsupported{Op: "GraphCounter", Backend: "jira-config-stub"} +} + func (s *configStore) ReadyCounter() (issueops.ReadyCounter, error) { return nil, &storage.ErrUnsupported{Op: "ReadyCounter", Backend: "jira-config-stub"} } diff --git a/internal/storage/dolt/graph_counter.go b/internal/storage/dolt/graph_counter.go new file mode 100644 index 000000000..fcb1c22d3 --- /dev/null +++ b/internal/storage/dolt/graph_counter.go @@ -0,0 +1,46 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storeops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// GraphCounter returns the guarded edge-count surface for this store. +func (s *DoltStore) GraphCounter() (issueops.GraphCounter, error) { + if s == nil { + return nil, &storage.ErrUnsupported{Op: "GraphCounter", Backend: "nil"} + } + return &graphCounter{store: s}, nil +} + +// graphCounter answers an edge count from one read transaction. +// +// There is no shared constructor package for this role: the work is an +// existence probe and a tally that must see ONE snapshot, and a transaction is +// not reachable through storage.DoltStorage. The sharing happens one level down +// at issueops.ExecuteEdgeCount, which the embedded store and the unit-of-work +// provider both reach as well — so what this leg checks is the WRAPPER, and the +// conformance contract says so at the top. +type graphCounter struct{ store *DoltStore } + +var _ issueops.GraphCounter = (*graphCounter)(nil) + +// CountEdges runs the anchor probe and the tally in ONE read transaction, so an +// anchor cannot be reported missing by a probe that raced a create the tally +// then counted. +func (c *graphCounter) CountEdges(ctx context.Context, req issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { + var result issueops.EdgeCountResult + err := c.store.withReadTx(ctx, func(tx *sql.Tx) error { + var err error + result, err = storeops.ExecuteEdgeCount(ctx, tx, req) + return err + }) + if err != nil { + return issueops.EdgeCountResult{}, err + } + return result, nil +} diff --git a/internal/storage/dolt/graph_counter_contract_test.go b/internal/storage/dolt/graph_counter_contract_test.go new file mode 100644 index 000000000..9a9da7fcf --- /dev/null +++ b/internal/storage/dolt/graph_counter_contract_test.go @@ -0,0 +1,92 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestGraphCounterContract runs the GraphCounter contract against the +// server-backed store. +// +// It reaches the same tx-level body every other leg reaches +// (issueops.ExecuteEdgeCount), so this wiring is an ENGINE check and a wrapper +// check rather than an independent vote on the body — the contract file says so +// at the top and the cases are written for it. +// +// The cases are subtests of one parent so the whole role suite shares one store +// and one copy-on-write branch. setupTestStore already marks the PARENT +// parallel and no subtest here calls t.Parallel. +func TestGraphCounterContract(t *testing.T) { + fixture, ctx, cleanup := newDoltGraphCounterFixture(t, "gcn") + defer cleanup() + + t.Run("CountsOutboundEdges", func(t *testing.T) { + conformance.RunGraphCounterCountsOutboundEdges(t, ctx, fixture) + }) + t.Run("CountsInboundEdges", func(t *testing.T) { + conformance.RunGraphCounterCountsInboundEdges(t, ctx, fixture) + }) + t.Run("AnswersOnePerAnchorInRequestOrder", func(t *testing.T) { + conformance.RunGraphCounterAnswersOnePerAnchorInRequestOrder(t, ctx, fixture) + }) + t.Run("DistinguishesNoEdgesFromNoAnchor", func(t *testing.T) { + conformance.RunGraphCounterDistinguishesNoEdgesFromNoAnchor(t, ctx, fixture) + }) + t.Run("CollapsesRepeatedAnchors", func(t *testing.T) { + conformance.RunGraphCounterCollapsesRepeatedAnchors(t, ctx, fixture) + }) + t.Run("FiltersEdgesNotAnchors", func(t *testing.T) { + conformance.RunGraphCounterFiltersEdgesNotAnchors(t, ctx, fixture) + }) + t.Run("NarrowsInboundByDependentStatus", func(t *testing.T) { + conformance.RunGraphCounterNarrowsInboundByDependentStatus(t, ctx, fixture) + }) + t.Run("CountsAcrossBothPlanes", func(t *testing.T) { + conformance.RunGraphCounterCountsAcrossBothPlanes(t, ctx, fixture) + }) + t.Run("NarrowsAWispDependentByStatus", func(t *testing.T) { + conformance.RunGraphCounterNarrowsAWispDependentByStatus(t, ctx, fixture) + }) + t.Run("ResolvesIDsExactly", func(t *testing.T) { + conformance.RunGraphCounterResolvesIDsExactly(t, ctx, fixture) + }) + t.Run("AnswersAnEmptyRequest", func(t *testing.T) { + conformance.RunGraphCounterAnswersAnEmptyRequest(t, ctx, fixture) + }) + t.Run("RefusesAnUnusableRequest", func(t *testing.T) { + conformance.RunGraphCounterRefusesAnUnusableRequest(t, ctx, fixture) + }) + t.Run("LeavesTheRequestAlone", func(t *testing.T) { + conformance.RunGraphCounterLeavesTheRequestAlone(t, ctx, fixture) + }) + t.Run("WritesNothing", func(t *testing.T) { + conformance.RunGraphCounterWritesNothing(t, ctx, fixture) + }) +} + +func newDoltGraphCounterFixture(t *testing.T, prefix string) (conformance.GraphCounterFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + counter, err := store.GraphCounter() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("GraphCounter(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.GraphCounterFixture{ + IssuePrefix: kit.IssuePrefix, + GraphCounter: counter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + CountHistory: kit.CountHistory, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/domain/db/dependency.go b/internal/storage/domain/db/dependency.go index 561a457c9..c7c569cd2 100644 --- a/internal/storage/domain/db/dependency.go +++ b/internal/storage/domain/db/dependency.go @@ -907,6 +907,15 @@ func (r *dependencySQLRepositoryImpl) WalkDependencyTree(ctx context.Context, re return issueops.WalkDependencyTreeInTx(ctx, r.runner, req) } +// CountEdges runs the SHARED edge-count body, unwrapped for +// WalkDependencyTree's reason: the body publishes issueops.ErrValidation as the +// role's own vocabulary, and a `fmt.Errorf("db: ...: %w")` would keep it +// matchable while putting this repository's name into a message the direct +// route never decorates. +func (r *dependencySQLRepositoryImpl) CountEdges(ctx context.Context, req publicops.EdgeCountRequest) (publicops.EdgeCountResult, error) { + return issueops.ExecuteEdgeCount(ctx, r.runner, req) +} + func (r *dependencySQLRepositoryImpl) GetTree(ctx context.Context, rootID string, opts domain.DepTreeOpts) ([]*types.TreeNode, error) { if rootID == "" { return nil, errors.New("db: DependencySQLRepository.GetTree: rootID must not be empty") diff --git a/internal/storage/domain/dependency.go b/internal/storage/domain/dependency.go index 1202720a3..791d99745 100644 --- a/internal/storage/domain/dependency.go +++ b/internal/storage/domain/dependency.go @@ -167,6 +167,11 @@ type DependencySQLRepository interface { // directions of a `both` request inside ONE transaction. GetTree above is the // unvalidated shape. WalkDependencyTree(ctx context.Context, req issueops.WalkTreeRequest) (issueops.TreeResult, error) + // CountEdges answers the batched edge count in the shape + // issueops.GraphCounter publishes: validated, per-anchor, spanning both + // dependency planes, with the existence probe and the tally in ONE + // transaction. CountByIssueID above is the single-anchor, unprobed shape. + CountEdges(ctx context.Context, req issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) CycleThroughEdges(ctx context.Context, edges [][2]string) (string, error) GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error) GetWispDependencyRecordsForIDs(ctx context.Context, wispIDs []string) (map[string][]*types.Dependency, error) @@ -203,6 +208,9 @@ type DependencyUseCase interface { // WalkDependencyTree is the shape issueops.TreeWalker publishes; see the // repository method of the same name. WalkDependencyTree(ctx context.Context, req issueops.WalkTreeRequest) (issueops.TreeResult, error) + // CountEdges is the shape issueops.GraphCounter publishes; see the + // repository method of the same name. + CountEdges(ctx context.Context, req issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) // AddDependencies asserts a batch of edges, each landing in the plane its // own SOURCE lives in. There is deliberately no plane-pinned variant: // `bd dep add` takes whatever ids the caller names and one request may @@ -647,6 +655,13 @@ func (u *dependencyUseCaseImpl) WalkDependencyTree(ctx context.Context, req issu return u.depRepo.WalkDependencyTree(ctx, req) } +// CountEdges passes the request straight through, for WalkDependencyTree's +// reason: the request's whole vocabulary is validated inside the shared body, +// and its refusals are typed sentinels both front doors classify. +func (u *dependencyUseCaseImpl) CountEdges(ctx context.Context, req issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { + return u.depRepo.CountEdges(ctx, req) +} + func (u *dependencyUseCaseImpl) GetDependencyTree(ctx context.Context, rootID string, opts DepTreeOpts) ([]*types.TreeNode, error) { if rootID == "" { return nil, fmt.Errorf("GetDependencyTree: rootID must not be empty") diff --git a/internal/storage/embeddeddolt/graph_counter.go b/internal/storage/embeddeddolt/graph_counter.go new file mode 100644 index 000000000..1c3b715c0 --- /dev/null +++ b/internal/storage/embeddeddolt/graph_counter.go @@ -0,0 +1,44 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storeops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// GraphCounter returns the guarded edge-count surface for this store. +func (s *EmbeddedDoltStore) GraphCounter() (issueops.GraphCounter, error) { + if s == nil { + return nil, &storage.ErrUnsupported{Op: "GraphCounter", Backend: "nil"} + } + return &graphCounter{store: s}, nil +} + +// graphCounter answers an edge count from one connection's transaction. +// +// It is a sibling of the server-backed store's body rather than a shared +// package for the reason that one gives: the probe and the tally need a +// TRANSACTION, which storage.DoltStorage does not publish, so the sharing +// happens below both of them at issueops.ExecuteEdgeCount. The two stores +// differ here only in how they reach a transaction. +type graphCounter struct{ store *EmbeddedDoltStore } + +var _ issueops.GraphCounter = (*graphCounter)(nil) + +func (c *graphCounter) CountEdges(ctx context.Context, req issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { + var result issueops.EdgeCountResult + err := c.store.withConn(ctx, false, func(tx *sql.Tx) error { + var err error + result, err = storeops.ExecuteEdgeCount(ctx, tx, req) + return err + }) + if err != nil { + return issueops.EdgeCountResult{}, err + } + return result, nil +} diff --git a/internal/storage/embeddeddolt/graph_counter_contract_test.go b/internal/storage/embeddeddolt/graph_counter_contract_test.go new file mode 100644 index 000000000..a255759fb --- /dev/null +++ b/internal/storage/embeddeddolt/graph_counter_contract_test.go @@ -0,0 +1,83 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestGraphCounterContract runs the GraphCounter contract against the embedded +// store. It reaches the same tx-level body the server-backed store reaches +// (issueops.ExecuteEdgeCount) and differs only in the engine underneath; that is +// what this wiring catches, and it is NOT an independent vote on the body. +// +// One environment for the whole suite. Every case seeds ids under its own prefix +// and asserts only about those, so the subtests are order-independent. +func TestGraphCounterContract(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "gcn") + ctx := t.Context() + fixture := newEmbeddedGraphCounterFixture(t, te, "gcn") + + t.Run("CountsOutboundEdges", func(t *testing.T) { + conformance.RunGraphCounterCountsOutboundEdges(t, ctx, fixture) + }) + t.Run("CountsInboundEdges", func(t *testing.T) { + conformance.RunGraphCounterCountsInboundEdges(t, ctx, fixture) + }) + t.Run("AnswersOnePerAnchorInRequestOrder", func(t *testing.T) { + conformance.RunGraphCounterAnswersOnePerAnchorInRequestOrder(t, ctx, fixture) + }) + t.Run("DistinguishesNoEdgesFromNoAnchor", func(t *testing.T) { + conformance.RunGraphCounterDistinguishesNoEdgesFromNoAnchor(t, ctx, fixture) + }) + t.Run("CollapsesRepeatedAnchors", func(t *testing.T) { + conformance.RunGraphCounterCollapsesRepeatedAnchors(t, ctx, fixture) + }) + t.Run("FiltersEdgesNotAnchors", func(t *testing.T) { + conformance.RunGraphCounterFiltersEdgesNotAnchors(t, ctx, fixture) + }) + t.Run("NarrowsInboundByDependentStatus", func(t *testing.T) { + conformance.RunGraphCounterNarrowsInboundByDependentStatus(t, ctx, fixture) + }) + t.Run("CountsAcrossBothPlanes", func(t *testing.T) { + conformance.RunGraphCounterCountsAcrossBothPlanes(t, ctx, fixture) + }) + t.Run("NarrowsAWispDependentByStatus", func(t *testing.T) { + conformance.RunGraphCounterNarrowsAWispDependentByStatus(t, ctx, fixture) + }) + t.Run("ResolvesIDsExactly", func(t *testing.T) { + conformance.RunGraphCounterResolvesIDsExactly(t, ctx, fixture) + }) + t.Run("AnswersAnEmptyRequest", func(t *testing.T) { + conformance.RunGraphCounterAnswersAnEmptyRequest(t, ctx, fixture) + }) + t.Run("RefusesAnUnusableRequest", func(t *testing.T) { + conformance.RunGraphCounterRefusesAnUnusableRequest(t, ctx, fixture) + }) + t.Run("LeavesTheRequestAlone", func(t *testing.T) { + conformance.RunGraphCounterLeavesTheRequestAlone(t, ctx, fixture) + }) + t.Run("WritesNothing", func(t *testing.T) { + conformance.RunGraphCounterWritesNothing(t, ctx, fixture) + }) +} + +func newEmbeddedGraphCounterFixture(t *testing.T, te *testEnv, prefix string) conformance.GraphCounterFixture { + t.Helper() + counter, err := te.store.GraphCounter() + if err != nil { + t.Fatalf("GraphCounter(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.GraphCounterFixture{ + IssuePrefix: kit.IssuePrefix, + GraphCounter: counter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/hook_graph_counter.go b/internal/storage/hook_graph_counter.go new file mode 100644 index 000000000..fb54beece --- /dev/null +++ b/internal/storage/hook_graph_counter.go @@ -0,0 +1,17 @@ +package storage + +import ( + "github.com/steveyegge/beads/issueops" +) + +// GraphCounter returns the inner store's edge-count surface. +// +// It recurses, like every other accessor on this decorator, rather than being +// absent: the accessor set is uniform across the chain, so a caller never has +// to know which decorators a store is wearing. What it does NOT do is wrap the +// result — counting edges fires no completion hooks, because nothing completed. +// That is the same statement hook_counter.go and hook_tree_walker.go make, and +// it is why this file is three lines. +func (h *HookFiringStore) GraphCounter() (issueops.GraphCounter, error) { + return h.inner.GraphCounter() +} diff --git a/internal/storage/issueops/edge_counts.go b/internal/storage/issueops/edge_counts.go new file mode 100644 index 000000000..59a94f287 --- /dev/null +++ b/internal/storage/issueops/edge_counts.go @@ -0,0 +1,226 @@ +package issueops + +import ( + "context" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// edgeCountPlanes are the two dependency tables an edge count spans, paired +// with the issue table an edge's SOURCE row lives in. The pairing is what a +// status-narrowed count joins through: a durable dependent's status is in +// `issues`, an ephemeral one's in `wisps`. +// +// The ephemeral pair is optional — older schemas predate that plane — and +// optionalBlockedTable is what says so, the same probe every other read over +// these two tables uses. +var edgeCountPlanes = []struct{ dependencies, sources string }{ + {dependencies: "dependencies", sources: "issues"}, + {dependencies: "wisp_dependencies", sources: "wisps"}, +} + +// ValidateEdgeCountRequest applies the request rules every GraphCounter +// implementation shares. +// +// THE ORDER IS PART OF THE CONTRACT. The direction is checked FIRST, so an +// empty request is a refusal about the direction rather than an empty answer: +// EdgeCountRequest{} names no anchors, and answering it with no anchors would +// let a caller that forgot the direction get a plausible response forever. The +// per-entry checks that follow tell a caller's mistake from a legitimately +// empty answer, exactly as ValidateEdgeReadRequest's do. +func ValidateEdgeCountRequest(request publicops.EdgeCountRequest) error { + switch request.Direction { + case publicops.EdgeDirectionIn, publicops.EdgeDirectionOut: + case "": + return fmt.Errorf("%w: count edges requires a direction (%q or %q)", + storage.ErrValidation, publicops.EdgeDirectionOut, publicops.EdgeDirectionIn) + default: + return fmt.Errorf("%w: count edges direction %q is not %q or %q", + storage.ErrValidation, request.Direction, publicops.EdgeDirectionOut, publicops.EdgeDirectionIn) + } + if request.Status != "" && request.Direction != publicops.EdgeDirectionIn { + return fmt.Errorf("%w: count edges status %q needs direction %q: an outbound edge's far end may be a row this database does not hold", + storage.ErrValidation, request.Status, publicops.EdgeDirectionIn) + } + for i, id := range request.IDs { + if id == "" { + return fmt.Errorf("%w: count edges id %d is empty", storage.ErrValidation, i) + } + } + for i, depType := range request.Types { + if !depType.IsValid() { + return fmt.Errorf("%w: count edges type %d is not a usable dependency type (non-empty, max %d chars)", + storage.ErrValidation, i, types.MaxDependencyTypeLen) + } + } + return nil +} + +// FinishEdgeCount assembles the per-anchor answer from the two things every +// implementation reads: which anchors exist, and the edge tallies keyed by +// anchor. +// +// It is a pure function beside the body for the reason the checklist gives: the +// parts that decide what the answer MEANS are pinned in milliseconds without a +// database, and the conformance contract is left to assert what only a real +// backend can show. What it decides here is the whole of the missing-anchor +// rule — a missing anchor counts 0 whatever rows are keyed to it, and a present +// anchor with no matching edges counts 0 too, which are the two facts a caller +// tells apart by Missing and by nothing else. +func FinishEdgeCount(anchors []string, present map[string]struct{}, tallies map[string]int64) publicops.EdgeCountResult { + out := publicops.EdgeCountResult{Anchors: make([]publicops.AnchorEdgeCount, 0, len(anchors))} + for _, id := range anchors { + _, exists := present[id] + entry := publicops.AnchorEdgeCount{ID: id, Missing: !exists} + // A missing anchor counts nothing even where rows are still keyed to + // it: a dependency row whose source has been deleted is orphaned data, + // and counting it would contradict the flag beside it. FinishEdgeRead + // drops the same rows from a missing anchor's edge list. + if exists { + entry.Count = tallies[id] + } + out.Anchors = append(out.Anchors, entry) + } + return out +} + +// ExecuteEdgeCount returns each anchor's edge cardinality in tx. It is the body +// behind the GraphCounter accessor on ALL THREE legs: the two stores wrap it in +// their own read transaction and the unit-of-work provider reaches it through +// the domain repository, whose runner publishes exactly the DBTX method set. +// +// The existence probe and the tally share ONE transaction, which is what lets +// AnchorEdgeCount.Missing mean what it says: a probe in its own transaction +// could report an anchor missing while a second transaction counted that +// anchor's edges, contradicting itself in one response body. +// +// VALIDATION HAPPENS HERE rather than at each accessor, which is where +// ExecuteEdgeRead's sibling leaves it. The difference is that this body is the +// only body: the two stores and the unit-of-work repository all land in this +// function, so a leg that forgot to validate would be a leg answering a +// different contract, and there is no second implementation for the check to +// belong to. It runs before the transaction opens nothing it needs to. +func ExecuteEdgeCount(ctx context.Context, tx DBTX, request publicops.EdgeCountRequest) (publicops.EdgeCountResult, error) { + if err := ValidateEdgeCountRequest(request); err != nil { + return publicops.EdgeCountResult{}, err + } + anchors := EdgeReadAnchors(request.IDs) + if len(anchors) == 0 { + return publicops.EdgeCountResult{Anchors: []publicops.AnchorEdgeCount{}}, nil + } + present, err := PresentIssueOrWispIDsInTx(ctx, tx, anchors) + if err != nil { + return publicops.EdgeCountResult{}, err + } + tallies, err := tallyEdgesInTx(ctx, tx, anchors, request) + if err != nil { + return publicops.EdgeCountResult{}, err + } + return FinishEdgeCount(anchors, present, tallies), nil +} + +// tallyEdgesInTx counts the matching edges per anchor across both dependency +// planes, batched at queryBatchSize. +// +// It SUMS the two planes rather than counting distinct row ids, which is the +// shipped answer of every raw count this role covers (dolt/counts.go's +// CountDependents, CountDependencies and CountDependentsByStatus) and of +// CountDependencyEdgesInTx, the domain body behind `bd show`'s counts on the +// unit-of-work leg. CountDependentRecordsInTx de-duplicates instead, because it +// must agree with a keyset PAGE of the same rows; a cardinality has no page and +// has never de-duplicated. +func tallyEdgesInTx(ctx context.Context, tx DBTX, anchors []string, request publicops.EdgeCountRequest) (map[string]int64, error) { + tallies := make(map[string]int64, len(anchors)) + for _, plane := range edgeCountPlanes { + for start := 0; start < len(anchors); start += queryBatchSize { + end := start + queryBatchSize + if end > len(anchors) { + end = len(anchors) + } + batch := anchors[start:end] + query := buildEdgeCountQuery(plane.dependencies, plane.sources, len(batch), request) + rows, err := tx.QueryContext(ctx, query, edgeCountArgs(batch, request)...) + if err != nil { + if optionalBlockedTable(plane.dependencies) && isTableNotExistError(err) { + break + } + return nil, fmt.Errorf("count edges in %s: %w", plane.dependencies, err) + } + for rows.Next() { + var id string + var n int64 + if scanErr := rows.Scan(&id, &n); scanErr != nil { + _ = rows.Close() + return nil, fmt.Errorf("count edges in %s: scan: %w", plane.dependencies, scanErr) + } + tallies[id] += n + } + _ = rows.Close() + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("count edges in %s: rows: %w", plane.dependencies, err) + } + } + } + return tallies, nil +} + +// buildEdgeCountQuery returns the grouped count for one dependency plane, keyed +// by the anchor end the request's direction names. +// +// THE TARGET END IS ALWAYS THE COALESCE EXPRESSION, never the STORED generated +// `depends_on_id` column. Both dependency tables define that column as +// GENERATED ALWAYS AS the same COALESCE, and inside an aggregate the pure-Go +// GMS analyzer can prune the base columns it derives from and then fail with +// "column depends_on_id could not be found in any table in scope" +// (dolt/counts.go says so at depTargetExpr). Every other aggregate over these +// tables in this package resolves the target the same way. +func buildEdgeCountQuery(depTable, sourceTable string, batchSize int, request publicops.EdgeCountRequest) string { + placeholders := strings.TrimSuffix(strings.Repeat("?,", batchSize), ",") + + typeClause, _ := buildDepTypeClause(request.Types) + if typeClause != "" { + typeClause = " AND d." + typeClause + } + + if request.Direction == publicops.EdgeDirectionOut { + //nolint:gosec // G201: table names are hardcoded literals and the IN clause holds only ? placeholders. + return fmt.Sprintf( + "SELECT d.issue_id AS anchor, COUNT(*) AS n FROM %s d WHERE d.issue_id IN (%s)%s GROUP BY d.issue_id", + depTable, placeholders, typeClause) + } + + anchorExpr := depTargetExpr("d") + if request.Status == "" { + //nolint:gosec // G201: table names are hardcoded literals and the IN clause holds only ? placeholders. + return fmt.Sprintf( + "SELECT %s AS anchor, COUNT(*) AS n FROM %s d WHERE %s%s GROUP BY %s", + anchorExpr, depTable, depTargetIn("d", placeholders), typeClause, anchorExpr) + } + // A status narrows by the DEPENDENT's row, which lives on the same plane as + // the edge: `dependencies` sources are durable issues, `wisp_dependencies` + // sources are wisps. An edge whose source row is gone joins to nothing and + // drops out, which the leaf doc states. + //nolint:gosec // G201: table names are hardcoded literals and the IN clause holds only ? placeholders. + return fmt.Sprintf( + "SELECT %s AS anchor, COUNT(*) AS n FROM %s d JOIN %s s ON s.id = d.issue_id WHERE %s%s AND s.status = ? GROUP BY %s", + anchorExpr, depTable, sourceTable, depTargetIn("d", placeholders), typeClause, anchorExpr) +} + +// edgeCountArgs binds the batch's anchor ids, then the type filter, then the +// status — the order buildEdgeCountQuery emits its placeholders in. +func edgeCountArgs(batch []string, request publicops.EdgeCountRequest) []any { + args := make([]any, 0, len(batch)+len(request.Types)+1) + for _, id := range batch { + args = append(args, id) + } + _, typeArgs := buildDepTypeClause(request.Types) + args = append(args, typeArgs...) + if request.Direction == publicops.EdgeDirectionIn && request.Status != "" { + args = append(args, request.Status) + } + return args +} diff --git a/internal/storage/issueops/edge_counts_test.go b/internal/storage/issueops/edge_counts_test.go new file mode 100644 index 000000000..90e9203de --- /dev/null +++ b/internal/storage/issueops/edge_counts_test.go @@ -0,0 +1,193 @@ +package issueops + +import ( + "errors" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// These are the parts of issueops.GraphCounter's answer that are decided +// without a database — the request vocabulary and the missing-anchor rule — so +// they are pinned here in milliseconds and the conformance contract is left to +// assert what only a real backend can show. + +func TestValidateEdgeCountRequestChecksTheDirectionBeforeAnythingElse(t *testing.T) { + // The empty request names no ids and no direction. It must refuse on the + // direction rather than fall through to the empty answer a well-formed + // id-less request gets, which is the ordering ValidateEdgeCountRequest + // documents. + err := ValidateEdgeCountRequest(publicops.EdgeCountRequest{}) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("empty request = %v, want ErrValidation", err) + } + if !strings.Contains(err.Error(), "direction") { + t.Errorf("empty request refusal = %q, want it to name the direction", err) + } + + // An empty id would also be a refusal, so a request carrying BOTH faults + // has to report the direction: a caller told only about the id would fix it + // and get the same refusal back. + both := ValidateEdgeCountRequest(publicops.EdgeCountRequest{IDs: []string{""}}) + if !strings.Contains(both.Error(), "direction") { + t.Errorf("refusal for a request missing both = %q, want it to name the direction", both) + } +} + +func TestValidateEdgeCountRequestRefusals(t *testing.T) { + for _, test := range []struct { + name string + req publicops.EdgeCountRequest + want bool + }{ + {"a bare outbound request", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut}, false}, + {"a bare inbound request", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionIn}, false}, + {"a direction outside the set", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirection("both")}, true}, + {"a status on the outbound direction", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, Status: string(types.StatusOpen)}, true}, + {"a status on the inbound direction", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionIn, Status: string(types.StatusOpen)}, false}, + {"an unrecognized status on the inbound direction", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionIn, Status: "never-a-status-here"}, false}, + {"an empty id beside a real one", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, IDs: []string{"bd-1", ""}}, true}, + {"an empty dependency type", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, Types: []types.DependencyType{""}}, true}, + {"an over-long dependency type", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, + Types: []types.DependencyType(nil)}, false}, + {"a workspace's own dependency type", publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, + Types: []types.DependencyType{"workspace-invented-type"}}, false}, + } { + err := ValidateEdgeCountRequest(test.req) + if got := errors.Is(err, storage.ErrValidation); got != test.want { + t.Errorf("%s: ErrValidation = %t (err %v), want %t", test.name, got, err, test.want) + } + } +} + +func TestValidateEdgeCountRequestRefusesATypeWiderThanTheColumn(t *testing.T) { + tooWide := types.DependencyType(strings.Repeat("x", types.MaxDependencyTypeLen+1)) + err := ValidateEdgeCountRequest(publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, + Types: []types.DependencyType{tooWide}, + }) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("an unstorable dependency type = %v, want ErrValidation", err) + } +} + +func TestFinishEdgeCountReportsAMissingAnchorRatherThanItsOrphanedRows(t *testing.T) { + // A tally keyed to an anchor no plane holds is orphaned data. Counting it + // would contradict the Missing flag beside it, which is the whole reason + // FinishEdgeCount reads the presence set rather than the tally's keys. + result := FinishEdgeCount( + []string{"present-with-edges", "present-bare", "ghost"}, + map[string]struct{}{"present-with-edges": {}, "present-bare": {}}, + map[string]int64{"present-with-edges": 3, "ghost": 9}, + ) + + want := []publicops.AnchorEdgeCount{ + {ID: "present-with-edges", Count: 3, Missing: false}, + {ID: "present-bare", Count: 0, Missing: false}, + {ID: "ghost", Count: 0, Missing: true}, + } + if len(result.Anchors) != len(want) { + t.Fatalf("anchors = %v, want %v", result.Anchors, want) + } + for i := range want { + if result.Anchors[i] != want[i] { + t.Errorf("anchor %d = %+v, want %+v", i, result.Anchors[i], want[i]) + } + } +} + +func TestFinishEdgeCountAnswersInAnchorOrderAndNeverNil(t *testing.T) { + result := FinishEdgeCount(nil, nil, nil) + if result.Anchors == nil { + t.Fatal("Anchors is nil for an empty anchor list; the contract promises a non-nil slice") + } + if len(result.Anchors) != 0 { + t.Fatalf("Anchors = %v for an empty anchor list, want none", result.Anchors) + } + + // The anchor list is the order, not the tally map — whose iteration order Go + // randomizes on purpose. + ordered := FinishEdgeCount( + []string{"c", "a", "b"}, + map[string]struct{}{"a": {}, "b": {}, "c": {}}, + map[string]int64{"a": 1, "b": 2, "c": 3}, + ) + for i, want := range []string{"c", "a", "b"} { + if ordered.Anchors[i].ID != want { + t.Fatalf("anchor %d = %q, want %q (the answer follows the anchor list)", i, ordered.Anchors[i].ID, want) + } + } +} + +func TestBuildEdgeCountQueryResolvesTheTargetWithoutTheGeneratedColumn(t *testing.T) { + // Inside an aggregate the pure-Go GMS analyzer can prune the base columns + // the STORED `depends_on_id` derives from and then fail to resolve it, which + // is why every count over these tables spells the COALESCE out. A query that + // named the generated column would work on one engine and fail on the other. + inbound := buildEdgeCountQuery("dependencies", "issues", 2, publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionIn, + }) + if strings.Contains(inbound, "depends_on_id") { + t.Errorf("the inbound count names the generated column:\n%s", inbound) + } + if !strings.Contains(inbound, "COALESCE(d.depends_on_issue_id") { + t.Errorf("the inbound count does not resolve the target from the base columns:\n%s", inbound) + } + if strings.Contains(inbound, "JOIN") { + t.Errorf("an unnarrowed inbound count joins the dependent's plane for nothing:\n%s", inbound) + } + + statusNarrowed := buildEdgeCountQuery("wisp_dependencies", "wisps", 1, publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionIn, Status: string(types.StatusOpen), + }) + if !strings.Contains(statusNarrowed, "JOIN wisps s ON s.id = d.issue_id") { + t.Errorf("the status narrowing does not join the DEPENDENT's own plane:\n%s", statusNarrowed) + } + + outbound := buildEdgeCountQuery("dependencies", "issues", 3, publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, + }) + if !strings.Contains(outbound, "d.issue_id IN (?,?,?)") { + t.Errorf("the outbound count is not keyed by source over the whole batch:\n%s", outbound) + } +} + +func TestEdgeCountArgsBindInPlaceholderOrder(t *testing.T) { + args := edgeCountArgs([]string{"a", "b"}, publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionIn, + Types: []types.DependencyType{types.DepBlocks}, + Status: string(types.StatusOpen), + }) + want := []any{"a", "b", string(types.DepBlocks), string(types.StatusOpen)} + if len(args) != len(want) { + t.Fatalf("args = %v, want %v", args, want) + } + for i := range want { + if args[i] != want[i] { + t.Fatalf("args = %v, want %v", args, want) + } + } + + // The status binds only where the query names it, so an outbound request + // must not carry a fourth argument its SQL has no placeholder for. + outbound := edgeCountArgs([]string{"a"}, publicops.EdgeCountRequest{ + Direction: publicops.EdgeDirectionOut, + Types: []types.DependencyType{types.DepBlocks}, + }) + if len(outbound) != 2 { + t.Fatalf("outbound args = %v, want the ids plus the type filter only", outbound) + } +} diff --git a/internal/storage/role_accessor_decorator_test.go b/internal/storage/role_accessor_decorator_test.go index d0d1afbae..a2a88650c 100644 --- a/internal/storage/role_accessor_decorator_test.go +++ b/internal/storage/role_accessor_decorator_test.go @@ -159,6 +159,7 @@ type roleAccessorStore struct { edges issueops.EdgeReader blocking issueops.BlockingAnnotator tree issueops.TreeWalker + graphCounter issueops.GraphCounter counter issueops.Counter settings issueops.WorkspaceConfig memories memoryops.Memories @@ -191,6 +192,7 @@ func newRoleAccessorStore() *roleAccessorStore { relations: sentinel, edges: sentinel, blocking: sentinel, + graphCounter: sentinel, counter: sentinel, settings: sentinel, versions: sentinel, @@ -265,6 +267,9 @@ func (s *roleAccessorStore) BatchCreator() (issueops.BatchCreator, error) { func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error) { return s.editor, s.err } +func (s *roleAccessorStore) GraphCounter() (issueops.GraphCounter, error) { + return s.graphCounter, s.err +} func (s *roleAccessorStore) MetadataCAS() (issueops.MetadataCAS, error) { return s.metadataCAS, s.err } @@ -315,6 +320,9 @@ func (*roleAccessorSentinel) Count(context.Context, issueops.CountRequest) (issu func (*roleAccessorSentinel) CountByGroup(context.Context, issueops.CountByGroupRequest) (issueops.CountByGroupResult, error) { return issueops.CountByGroupResult{}, nil } +func (*roleAccessorSentinel) CountEdges(context.Context, issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { + return issueops.EdgeCountResult{}, nil +} func (*roleAccessorSentinel) GetSetting(context.Context, issueops.GetSettingRequest) (issueops.SettingResult, error) { return issueops.SettingResult{}, nil } @@ -423,8 +431,9 @@ func (*memoryRoleSentinel) List(context.Context, memoryops.ListRequest) (memoryo // THE PASS-THROUGH ROLES are asserted the other way round on purpose, in one // paragraph rather than four near-identical ones (bd-8ri3m). Reads fire no // completion hooks, so IssueReader, IssueRelations, Counter, StatsReporter, -// CycleDetector, EdgeReader, BlockingAnnotator, TreeWalker, ReadyCounter, -// Querier and InitVerifier deliberately return the inner surface unwrapped, +// CycleDetector, EdgeReader, BlockingAnnotator, TreeWalker, GraphCounter, +// ReadyCounter, Querier and InitVerifier deliberately return the inner surface +// unwrapped, // each in its own hook_*.go. The ones in that column that are NOT reads are // WorkspaceConfig, Memories, VersionReconciler, Bootstrapper, Sweeper and // Deleter: a settings write changes the workspace rather than a bead, a @@ -458,6 +467,7 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {"EdgeReader", func() (any, error) { return store.EdgeReader() }, inner.edges, false}, {"BlockingAnnotator", func() (any, error) { return store.BlockingAnnotator() }, inner.blocking, false}, {"TreeWalker", func() (any, error) { return store.TreeWalker() }, inner.tree, false}, + {"GraphCounter", func() (any, error) { return store.GraphCounter() }, inner.graphCounter, false}, {"Counter", func() (any, error) { return store.Counter() }, inner.counter, false}, {"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }, inner.settings, false}, {"Memories", func() (any, error) { return store.Memories() }, inner.memories, false}, @@ -514,6 +524,7 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) { {"EdgeReader", func() (any, error) { return store.EdgeReader() }}, {"BlockingAnnotator", func() (any, error) { return store.BlockingAnnotator() }}, {"TreeWalker", func() (any, error) { return store.TreeWalker() }}, + {"GraphCounter", func() (any, error) { return store.GraphCounter() }}, {"Counter", func() (any, error) { return store.Counter() }}, {"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }}, {"Memories", func() (any, error) { return store.Memories() }}, diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 24a9c4f0d..e75f46329 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -246,6 +246,14 @@ type Storage interface { // walk has a depth, a cycle policy and a node shape of its own. Reads fire // no hooks, as for IssueReader. TreeWalker() (issueops.TreeWalker, error) + // GraphCounter returns the guarded edge-count surface for this store: how + // many dependency edges each of several anchors has, in one named + // direction, spanning both dependency planes. Its own role rather than a + // third Counter method (that one's predicate is a filter over the issues + // table and says nothing about an edge) and rather than a counted + // EdgeReader (that one answers with the stored ROWS, outbound only). Reads + // fire no hooks, as for IssueReader. + GraphCounter() (issueops.GraphCounter, error) // ReadyCounter returns the guarded ready-count surface for this store: the // size of the ready set, which is the number `bd ready`'s pagination // publishes and which no other role answers. Counter's predicate is a diff --git a/internal/storage/uow/graph_counter.go b/internal/storage/uow/graph_counter.go new file mode 100644 index 000000000..00694babd --- /dev/null +++ b/internal/storage/uow/graph_counter.go @@ -0,0 +1,45 @@ +package uow + +import ( + "context" + "fmt" + + publicops "github.com/steveyegge/beads/issueops" +) + +// GraphCounterSource is the capability accessor a unit-of-work provider offers +// for the edge-count role, the sibling of EdgeReaderSource and TreeWalkerSource. +type GraphCounterSource interface { + GraphCounter() (publicops.GraphCounter, error) +} + +// graphCounter answers an edge count through a unit of work. +type graphCounter struct { + provider UnitOfWorkProvider +} + +// GraphCounter returns the guarded edge-count surface for this provider. +func (p *doltSQLProvider) GraphCounter() (publicops.GraphCounter, error) { + return NewGraphCounter(p) +} + +// NewGraphCounter constructs a public edge counter backed by provider. +func NewGraphCounter(provider UnitOfWorkProvider) (publicops.GraphCounter, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new graph counter: unit-of-work provider must not be nil") + } + return &graphCounter{provider: provider}, nil +} + +var _ publicops.GraphCounter = (*graphCounter)(nil) + +// CountEdges counts inside ONE read-only unit of work. +// +// One unit of work is load-bearing rather than tidy: the answer is an existence +// probe plus a tally, and AnchorEdgeCount.Missing is only true of a graph that +// existed if the two saw one snapshot. +func (c *graphCounter) CountEdges(ctx context.Context, req publicops.EdgeCountRequest) (publicops.EdgeCountResult, error) { + return RunTxRead(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.EdgeCountResult, error) { + return uw.DependencyUseCase().CountEdges(ctx, req) + }) +} diff --git a/internal/storage/uow/graph_counter_contract_test.go b/internal/storage/uow/graph_counter_contract_test.go new file mode 100644 index 000000000..6ff44a8b9 --- /dev/null +++ b/internal/storage/uow/graph_counter_contract_test.go @@ -0,0 +1,95 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestGraphCounterContract runs the GraphCounter contract against the +// unit-of-work provider. +// +// For most roles this is the wiring where a genuine seam divergence shows up, +// because the unit of work is a second body. NOT FOR THIS ROLE: it reaches the +// same issueops.ExecuteEdgeCount through the domain repository, whose runner +// publishes exactly the DBTX method set that function takes. What this leg +// checks is the WRAPPER — that the request survives the trip and that +// ErrValidation still matches errors.Is after crossing two layers whose +// siblings wrap their errors. +// +// One provider for the whole suite and NO t.Parallel: this backend has no +// per-test copy-on-write branch, so the tables are database-global. Every case +// scopes itself by the ids it seeded. +func TestGraphCounterContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWGraphCounterFixture(t, ctx, "gcn") + + t.Run("CountsOutboundEdges", func(t *testing.T) { + conformance.RunGraphCounterCountsOutboundEdges(t, ctx, fixture) + }) + t.Run("CountsInboundEdges", func(t *testing.T) { + conformance.RunGraphCounterCountsInboundEdges(t, ctx, fixture) + }) + t.Run("AnswersOnePerAnchorInRequestOrder", func(t *testing.T) { + conformance.RunGraphCounterAnswersOnePerAnchorInRequestOrder(t, ctx, fixture) + }) + t.Run("DistinguishesNoEdgesFromNoAnchor", func(t *testing.T) { + conformance.RunGraphCounterDistinguishesNoEdgesFromNoAnchor(t, ctx, fixture) + }) + t.Run("CollapsesRepeatedAnchors", func(t *testing.T) { + conformance.RunGraphCounterCollapsesRepeatedAnchors(t, ctx, fixture) + }) + t.Run("FiltersEdgesNotAnchors", func(t *testing.T) { + conformance.RunGraphCounterFiltersEdgesNotAnchors(t, ctx, fixture) + }) + t.Run("NarrowsInboundByDependentStatus", func(t *testing.T) { + conformance.RunGraphCounterNarrowsInboundByDependentStatus(t, ctx, fixture) + }) + t.Run("CountsAcrossBothPlanes", func(t *testing.T) { + conformance.RunGraphCounterCountsAcrossBothPlanes(t, ctx, fixture) + }) + t.Run("NarrowsAWispDependentByStatus", func(t *testing.T) { + conformance.RunGraphCounterNarrowsAWispDependentByStatus(t, ctx, fixture) + }) + t.Run("ResolvesIDsExactly", func(t *testing.T) { + conformance.RunGraphCounterResolvesIDsExactly(t, ctx, fixture) + }) + t.Run("AnswersAnEmptyRequest", func(t *testing.T) { + conformance.RunGraphCounterAnswersAnEmptyRequest(t, ctx, fixture) + }) + t.Run("RefusesAnUnusableRequest", func(t *testing.T) { + conformance.RunGraphCounterRefusesAnUnusableRequest(t, ctx, fixture) + }) + t.Run("LeavesTheRequestAlone", func(t *testing.T) { + conformance.RunGraphCounterLeavesTheRequestAlone(t, ctx, fixture) + }) + t.Run("WritesNothing", func(t *testing.T) { + conformance.RunGraphCounterWritesNothing(t, ctx, fixture) + }) +} + +func newUOWGraphCounterFixture(t *testing.T, ctx context.Context, prefix string) conformance.GraphCounterFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + // Through the capability accessor, not NewGraphCounter: a provider that + // stopped offering the role is the regression, and a constructor call would + // hide it. + source, ok := provider.(GraphCounterSource) + if !ok { + t.Fatalf("provider %T does not offer the GraphCounter accessor", provider) + } + counter, err := source.GraphCounter() + if err != nil { + t.Fatalf("GraphCounter(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.GraphCounterFixture{ + IssuePrefix: kit.IssuePrefix, + GraphCounter: counter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/uow/notifying.go b/internal/storage/uow/notifying.go index 54d551a06..ddf8dc91b 100644 --- a/internal/storage/uow/notifying.go +++ b/internal/storage/uow/notifying.go @@ -234,6 +234,10 @@ func (p *notifyingProvider) BlockingAnnotator() (publicops.BlockingAnnotator, er func (p *notifyingProvider) TreeWalker() (publicops.TreeWalker, error) { return NewTreeWalker(p) } +func (p *notifyingProvider) GraphCounter() (publicops.GraphCounter, error) { + return NewGraphCounter(p) +} + func (p *notifyingProvider) Counter() (publicops.Counter, error) { return NewCounter(p) } func (p *notifyingProvider) ReadyCounter() (publicops.ReadyCounter, error) { @@ -385,6 +389,7 @@ var ( _ EdgeReaderSource = (*notifyingProvider)(nil) _ BlockingAnnotatorSource = (*notifyingProvider)(nil) _ TreeWalkerSource = (*notifyingProvider)(nil) + _ GraphCounterSource = (*notifyingProvider)(nil) _ CounterSource = (*notifyingProvider)(nil) _ ReadyCounterSource = (*notifyingProvider)(nil) _ ReadyClaimerSource = (*notifyingProvider)(nil) diff --git a/internal/storage/uow/notifying_parity_test.go b/internal/storage/uow/notifying_parity_test.go index a4c64c95f..b6c23385e 100644 --- a/internal/storage/uow/notifying_parity_test.go +++ b/internal/storage/uow/notifying_parity_test.go @@ -180,6 +180,7 @@ func TestRecordingDependencyUseCaseCoversItsSurface(t *testing.T) { assertPartition(t, "DependencyUseCase", interfaceMethods(reflect.TypeOf((*domain.DependencyUseCase)(nil)).Elem()), reflect.TypeOf((*recordingDepUC)(nil)), map[string]string{ "CountByIssueID": reads, + "CountEdges": reads, "CountByWispID": reads, "CountsByIssueIDs": reads, "CountsByWispIDs": reads, diff --git a/internal/telemetry/graph_counter.go b/internal/telemetry/graph_counter.go new file mode 100644 index 000000000..5abd2300a --- /dev/null +++ b/internal/telemetry/graph_counter.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// GraphCounter returns the inner store's edge-count surface wrapped in this +// layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner counter unspanned and untimed. +func (s *InstrumentedStorage) GraphCounter() (issueops.GraphCounter, error) { + inner, err := s.Unwrap().GraphCounter() + if err != nil { + return nil, err + } + return s.WrapGraphCounter(inner), nil +} + +// WrapGraphCounter instruments guarded edge counts with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapGraphCounter(inner issueops.GraphCounter) issueops.GraphCounter { + return &instrumentedGraphCounter{storage: s, inner: inner} +} + +type instrumentedGraphCounter struct { + storage *InstrumentedStorage + inner issueops.GraphCounter +} + +func (c *instrumentedGraphCounter) CountEdges(ctx context.Context, request issueops.EdgeCountRequest) (result issueops.EdgeCountResult, err error) { + ctx, span, started := c.storage.op(ctx, "GraphCounter.CountEdges") + result, err = c.inner.CountEdges(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/role_accessor_decorator_test.go b/internal/telemetry/role_accessor_decorator_test.go index 043e7dbf3..ed0aff349 100644 --- a/internal/telemetry/role_accessor_decorator_test.go +++ b/internal/telemetry/role_accessor_decorator_test.go @@ -129,6 +129,9 @@ func (s *roleAccessorStore) CycleDetector() (issueops.CycleDetector, error) { } func (s *roleAccessorStore) EdgeReader() (issueops.EdgeReader, error) { return s.surface, s.err } func (s *roleAccessorStore) TreeWalker() (issueops.TreeWalker, error) { return s.surface, s.err } +func (s *roleAccessorStore) GraphCounter() (issueops.GraphCounter, error) { + return s.surface, s.err +} func (s *roleAccessorStore) BlockingAnnotator() (issueops.BlockingAnnotator, error) { return s.surface, s.err } @@ -249,6 +252,10 @@ func (*roleAccessorSentinel) CountReady(context.Context, issueops.ReadyRequest) return issueops.ReadyCountResult{}, nil } +func (*roleAccessorSentinel) CountEdges(context.Context, issueops.EdgeCountRequest) (issueops.EdgeCountResult, error) { + return issueops.EdgeCountResult{}, nil +} + func (*roleAccessorSentinel) Query(context.Context, issueops.QueryRequest) (issueops.IssuePage, error) { return issueops.IssuePage{}, nil } @@ -344,6 +351,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) { {"EdgeReader", func() (any, error) { return wrapped.EdgeReader() }, sentinel}, {"BlockingAnnotator", func() (any, error) { return wrapped.BlockingAnnotator() }, sentinel}, {"TreeWalker", func() (any, error) { return wrapped.TreeWalker() }, sentinel}, + {"GraphCounter", func() (any, error) { return wrapped.GraphCounter() }, sentinel}, {"Counter", func() (any, error) { return wrapped.Counter() }, sentinel}, {"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }, sentinel}, {"Memories", func() (any, error) { return wrapped.Memories() }, memorySentinel}, @@ -398,6 +406,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) { {"EdgeReader", func() (any, error) { return wrapped.EdgeReader() }}, {"BlockingAnnotator", func() (any, error) { return wrapped.BlockingAnnotator() }}, {"TreeWalker", func() (any, error) { return wrapped.TreeWalker() }}, + {"GraphCounter", func() (any, error) { return wrapped.GraphCounter() }}, {"Counter", func() (any, error) { return wrapped.Counter() }}, {"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }}, {"Memories", func() (any, error) { return wrapped.Memories() }}, diff --git a/issue_roles_external_test.go b/issue_roles_external_test.go index c8f618a3c..f5c70fc34 100644 --- a/issue_roles_external_test.go +++ b/issue_roles_external_test.go @@ -625,6 +625,35 @@ func TestTreeWalkerExposesTypedUnsupportedError(t *testing.T) { } } +// TestGraphCounterKeepsTelemetryOutermost is the READ answer again: counting +// edges fires no completion hooks, so the hook decorator adds no layer. +func TestGraphCounterKeepsTelemetryOutermost(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + counter, err := storage.NewHookFiringStore(instrumented, nil).GraphCounter() + if err != nil { + t.Fatalf("GraphCounter() error = %v", err) + } + if got := reflect.TypeOf(counter).String(); got != "*telemetry.instrumentedGraphCounter" { + t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got) + } +} + +func TestGraphCounterExposesTypedUnsupportedError(t *testing.T) { + counter, err := (*dolt.DoltStore)(nil).GraphCounter() + if counter != nil { + t.Fatalf("GraphCounter() counter = %T, want nil", counter) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("GraphCounter() error = %v, want *beads.ErrUnsupported", err) + } +} + func TestCounterExposesTypedUnsupportedError(t *testing.T) { counter, err := (*dolt.DoltStore)(nil).Counter() if counter != nil { diff --git a/issueops/graphcounter.go b/issueops/graphcounter.go new file mode 100644 index 000000000..444bb307a --- /dev/null +++ b/issueops/graphcounter.go @@ -0,0 +1,280 @@ +package issueops + +import ( + "context" +) + +// EdgeDirection names which end of a dependency edge an anchor sits on. The set +// is CLOSED and there is no zero value in it: a request that leaves the +// direction unset is ErrValidation rather than a count in some default +// direction. +// +// Requiring it is the one deliberate unfriendliness on this request. The two +// answers are about DIFFERENT EDGE SETS — "what does this depend on" and "what +// depends on this" — 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. The raw storage seam +// spells the difference in the METHOD NAME (CountDependents, CountDependencies) +// and cannot make that mistake; a request field can, so it is required instead. +type EdgeDirection string + +const ( + // EdgeDirectionOut counts the anchor's DEPENDENCIES: edges whose source is + // the anchor. This is the direction `bd dep list` reads and the number + // `bd show` prints as the dependency count. + EdgeDirectionOut EdgeDirection = "out" + // EdgeDirectionIn counts the anchor's DEPENDENTS: edges whose target is the + // anchor. + EdgeDirectionIn EdgeDirection = "in" +) + +// EdgeCountRequest describes one edge-cardinality question asked of several +// anchors at once. +// +// IT IS THE COUNTING SIBLING OF EdgeReadRequest and is spelled to match it +// field for field where the two share a meaning — IDs de-duplicate onto first +// mention, Types narrows edges and never anchors, an empty slice asks about no +// anchors — so a caller holding both cannot believe the two questions are asked +// of different sets. Two things are here that are not there: Direction, which +// EdgeReadRequest deliberately lacks (edgereader.go's EdgeReader doc says the +// inbound bulk read "gets its own role" when something needs it, and counting +// is where something did), and Status. +// +// THERE IS NO PAGE, no limit and no offset, for the reason CountRequest gives: +// a count is a cardinality, and bounding the scan would answer "how many of the +// first N". +// +// THERE IS NO "BOTH" DIRECTION. A caller that wants the pair asks twice, which +// is what every front door in the tree already does — internal/workapi's detail +// assembly calls CountDependents and CountDependencies as two separate reads +// today. Answering both in one call would mean two numbers per anchor, and then +// Status — which narrows by a row only the inbound direction has (see that +// field) — would apply to one of them and silently not to the other. A field +// that quietly governs half an answer is the shape this request is written to +// avoid. +type EdgeCountRequest struct { + // IDs are the anchors, each an EXACT canonical id, with the same + // promise-rather-than-obligation EdgeReadRequest.IDs states: a case variant, + // surrounding whitespace, a prefix of a real id and a real id with a suffix + // are all MISSES, not resolutions. A front door that wants partial-id + // resolution resolves before it calls. + // + // A miss is PER ANCHOR and reported on that anchor — see + // AnchorEdgeCount.Missing — rather than failing the call. + // + // AN EMPTY ENTRY IS ErrValidation. 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. + // + // AN EMPTY SLICE IS NOT AN ERROR: it asks about no anchors and the answer is + // no anchors. The direction is still validated first, so EdgeCountRequest{} + // is ErrValidation on Direction and not an empty answer. + // + // REPEATS COLLAPSE onto the first mention, for EdgeReadRequest.IDs's reason: + // a second entry for the same anchor carries no second fact and would only + // invite a caller summing the result to count the same edges twice. + // + // THERE IS NO SIZE CAP HERE, exactly as there is none on EdgeReadRequest.IDs. + // The reads are batched internally, and an in-process caller that holds the + // role has already paid for the slice it is passing; a cap on the role would + // be a limit invented for a caller that is not the one that needs it. The + // bound belongs to the WIRE operation, where the request arrives from + // somewhere else and the cost of an unbounded one is a stranger's — the + // split ApplyBatchRequest.Items makes explicitly by bounding at 100. The + // graph-counts wire slice sets it. + IDs []string + + // Direction is which edges the count is over, and it is REQUIRED. An empty + // or unrecognized value is ErrValidation. See EdgeDirection. + Direction EdgeDirection + + // Types restricts the count to these edge types. Empty means every type. + // + // An entry is checked for being a value at all — non-empty, within the + // column's length — and NEVER for membership of a known-types list, exactly + // as EdgeReadRequest.Types is: the vocabulary is OPEN, so a workspace's own + // type has to be able to filter. An unusable entry is ErrValidation rather + // than a filter that quietly matches nothing; an unrecognized but usable one + // is accepted and matches no edge. + // + // 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. + Types []DependencyType + + // Status restricts the count to 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 EdgeDirectionIn, and a non-empty Status beside + // EdgeDirectionOut is ErrValidation rather than a filter that is ignored. + // The asymmetry is the substrate's, not a preference: narrowing by status + // means joining the far end of the edge to the row that holds its status, + // and an OUTBOUND edge's far end may be a row this database does not hold at + // all — DependencyEditor accepts an "external:" reference and an id + // belonging to another repository as targets. A status filter on that + // direction would silently drop every dangling edge, which is precisely the + // class of edge EdgeReader exists to return verbatim. The raw storage seam + // has the same asymmetry and states it the same way: it publishes + // CountDependentsByStatus and no CountDependenciesByStatus. + // + // It is NOT validated against the workspace vocabulary and is NOT a + // comma-separated OR set: an unrecognized name matches nothing and counts 0 + // rather than failing, exactly as CountRequest.Status does. A scripted + // caller counting a status its workspace has since dropped currently reads 0 + // and should keep reading 0. + // + // The status is read from the dependent's OWN PLANE: a durable dependent's + // from the issues table, an ephemeral one's from the wisps table. An edge + // whose source row has been deleted out from under it joins to nothing and + // is not counted, which is the one way a status-narrowed count can be + // smaller than the unnarrowed count by more than the statuses explain. + Status string +} + +// AnchorEdgeCount is one anchor's edge cardinality, or the report that the +// anchor is not there. +type AnchorEdgeCount struct { + // ID is the anchor, spelled exactly as the request spelled it. + ID string + // Count is how many stored edges match the request in the requested + // direction, after the type and status filters. + // + // IT SPANS BOTH DEPENDENCY PLANES. An edge lives in `dependencies` or in + // `wisp_dependencies` according to which plane its SOURCE sits on, and this + // count is the total across the two — so 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. That is the shipped answer of + // every raw count this role covers and of the domain body behind the + // unit-of-work leg (CountDependencyEdgesInTx), and it is what makes the + // number agree with the row list a caller gets from the matching read. + // + // It is a SUM over the two planes and NOT a distinct count of edge rows. The + // two are the same number unless one row id is present in both tables, which + // is a durable/ephemeral mirror the paging read de-duplicates for its keyset + // contract (CountDependentRecords) and this count never has. Nothing in this + // contract's reach can produce one — a seeded edge is routed to exactly one + // plane by its source — so the distinction is stated rather than pinned. + // + // UNREACHABLE HERE IS NOT UNREACHABLE IN PRODUCTION, and the difference is + // worth the extra sentence because "the contract cannot build it" reads too + // easily as "it cannot happen". A collision is real: dependency row ids are + // derived from (issue_id, target) and omit the table, so a wisp PROMOTED to + // durable, or two Dolt clones MERGED, leave one logical edge in both tables. + // TestDependentRecordsCrossTableCollision constructs exactly that state and + // names those two paths. What this role promises against it is the sum, the + // same answer the raw counts give, and a caller that needs the distinct + // total is asking CountDependentRecords' question rather than this one. + // + // A missing anchor counts 0. + Count int64 + // Missing reports that no issue and no wisp carries this id. + // + // It exists for AnchorEdges.Missing's reason and one sharper: a count of 0 + // is otherwise indistinguishable from a typo, and 0 is the COMMON answer — + // most issues have no edges in at least one direction — so the typo would + // never surface. This is the field that keeps this role from being a + // question a caller cannot tell it got wrong. + // + // A missing anchor's count is 0 even where orphaned rows are still keyed to + // it: a dependency row whose source has been deleted is orphaned data, and + // counting it would contradict the flag beside it. That mirrors + // FinishEdgeRead, which drops such rows from a missing anchor's edge list. + // + // DANGLING EDGES ARE NOT MISSING ANCHORS. This flag 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 +} + +// EdgeCountResult is the per-anchor answer. +type EdgeCountResult struct { + // Anchors carries one entry per DISTINCT requested id, in the order the + // request first named it. It is never nil for a successful call, and it is a + // slice rather than a map for EdgeReadResult.Anchors's reason: the request's + // order is part of the answer, and a map would have made that ordering each + // surface's own invention. A map would also be the one result shape a wire + // operation cannot carry without inventing a key vocabulary. + Anchors []AnchorEdgeCount +} + +// GraphCounter describes counting DEPENDENCY EDGES around several anchors at +// once — and, like Counter, EdgeReader and Relations, a role with its own +// accessor. A new capability gets a new role interface and its own accessor; +// never append a method here. +// +// IT IS ITS OWN ROLE RATHER THAN A THIRD Counter METHOD. Counter answers about +// a set of ISSUES described by a predicate over one table; its request carries +// twenty-odd filter fields and none of them says anything about an edge. This +// role answers about EDGES, is anchored on ids rather than described by a +// predicate, and its answer is per-anchor rather than one number. Folding it in +// would have meant a CountRequest carrying an anchor list and a direction that +// every other count must ignore. +// +// IT IS ALSO NOT EdgeReader COUNTED. That role answers with the edge ROWS, in a +// pinned order, for the outbound direction only; the rows are the answer there, +// and the front door prints them. Here the number is the answer, both directions +// are askable, and no row is materialized — which is the point, because the +// surfaces that want these numbers (`bd show`'s header, a list view's +// per-row decoration) want them for issues whose edges they will never print. +// +// WHAT IS DELIBERATELY NOT HERE, and why, since the never-append rule makes +// each of these a decision rather than an omission: +// +// - THE COMMENT COUNT. `bd show` prints one beside the two edge counts and +// the raw seam publishes CountIssueComments, so it is genuinely consumed — +// but a comment is not an edge, it has no direction, no type and no far +// end, and every field of EdgeCountRequest below IDs would be meaningless +// to it. It is a different QUESTION in the sense the role test means, and it +// belongs beside Commenter. +// - THE EVENT COUNT. CountEvents has no caller in this tree at all, and the +// audit journal is a plane of its own with its own retention and scoping +// rules. It follows the journal, not the graph. +// - THE ISSUE COUNT and its grouped form, which are Counter's, and the READY +// count, which is ReadyCounter's. +// - THE PAIRED, BLOCKS-ONLY BATCH the raw seam publishes as +// GetDependencyCounts. Its answer is expressible here as two calls with +// Types set to the blocking type, and its callers are front doors this role +// does not re-route; naming it as a third method would have added a shape +// — a map keyed by id carrying two numbers — that no wire operation can +// carry and that this result deliberately does not have. +// +// Implementations never mutate caller-owned request values, snapshot the +// request at method entry, and apply validation and normalization only to +// attempt-local clones. EdgeCountRequest travels by value, so IDs and Types are +// the members a body could otherwise write through to the caller: reading them +// into a set is fine, sorting or de-duplicating them in place is not. +// +// Counting edges is a READ. Nothing here records a history entry, fires a +// completion hook or changes a row, and a refusal changes nothing either. +// Deterministic request-validation failures match ErrValidation; result values +// are unspecified when error is non-nil. +// +// THERE IS NO CLI FRONT DOOR IN THE SLICE THAT INTRODUCED THIS ROLE, and no +// HTTP operation either. That is written down here rather than left to be +// inferred, the way VersionReconciler writes down its absent HTTP half and +// BatchApplier its absent CLI. The numbers this role answers are already +// printed by `bd show`, which reads them through internal/workapi's detail +// seam — a seam shared with an HTTP handler, so moving it is its own change +// with its own parity argument — and the wire operation that publishes them +// lands in the graph-counts wire slice. What this slice buys is the facade: one +// place where the direction, the plane span, the missing-anchor rule and the +// status asymmetry are stated once and held to on three legs. +type GraphCounter interface { + // CountEdges returns each anchor's edge cardinality in the requested + // direction. + // + // The anchors' existence and their edge counts are read from ONE consistent + // view, so an anchor cannot be reported missing by a probe that raced a + // create the count then saw. That is the same promise EdgeReader.ReadEdges + // makes, and it is the reason this is one method rather than a caller's + // existence check followed by a caller's count. + // + // A request naming only anchors that are not there is a successful call + // whose every entry reports Missing with a count of 0: there is no + // ErrNotFound on this role, because a batch that failed for one absent id + // would throw away the answers for the ids that were found — and because a + // question about a set has an answer even when the set is empty, which is + // the whole of Counter's not-found story too. + CountEdges(ctx context.Context, req EdgeCountRequest) (EdgeCountResult, error) +}