diff --git a/.github/scripts/embedded-cmd-test-shards.txt b/.github/scripts/embedded-cmd-test-shards.txt index 11dc95811..6b4d1dfd0 100644 --- a/.github/scripts/embedded-cmd-test-shards.txt +++ b/.github/scripts/embedded-cmd-test-shards.txt @@ -287,9 +287,11 @@ 50 15 TestEmbeddedCreateDryRunCrossRepoDoesNotMigrateTarget 50 15 TestEmbeddedEpicCloseEligibleReasonFlag 50 15 TestEmbeddedExplicitHierarchicalParentEdges +50 15 TestEmbeddedIfRevisionReopenGuardDirect 50 15 TestEmbeddedVersionConcurrent 50 16 TestEmbeddedBlockedLabelFilters +50 16 TestEmbeddedGCConditionalMatcherDecode 50 16 TestEmbeddedGateInheritsDownParentChain 50 16 TestEmbeddedKV 50 16 TestEmbeddedMaxRowsReady diff --git a/.github/scripts/proxied-cmd-test-shards.txt b/.github/scripts/proxied-cmd-test-shards.txt index 59ca95906..92b21b1d4 100644 --- a/.github/scripts/proxied-cmd-test-shards.txt +++ b/.github/scripts/proxied-cmd-test-shards.txt @@ -258,6 +258,7 @@ 30 2 TestProxiedServerDelete 30 2 TestProxiedServerDeleteForceOrphans +30 2 TestProxiedServerIfRevisionGuardAssign 30 2 TestProxiedServerListComments 30 2 TestProxiedServerPromote 30 2 TestProxiedServerTypesAgreeWithCreate @@ -361,6 +362,7 @@ 30 17 TestProxiedServerClose 30 17 TestProxiedServerConfigConcurrent 30 17 TestProxiedServerDeleteConcurrent +30 17 TestProxiedServerIfRevisionGuardUpdate 30 17 TestProxiedServerSearch 30 17 TestProxiedServerServeReadParity 30 17 TestProxiedServerStatus @@ -374,6 +376,7 @@ 30 19 TestProxiedServerCreate2 30 19 TestProxiedServerEdit +30 19 TestProxiedServerIfRevisionGuardReopen 30 19 TestProxiedServerPourRejectsEnumViolatingVar 30 19 TestProxiedServerReassignFence 30 19 TestProxiedServerUpdateWisp @@ -431,6 +434,7 @@ 30 26 TestProxiedServerState 30 27 TestProxiedServerBlocked +30 27 TestProxiedServerIfRevisionGuardClose 30 27 TestProxiedServerMolLastActivity 30 27 TestProxiedServerMolStale 30 27 TestProxiedServerMoleculeFrontDoorWriteParity @@ -448,6 +452,7 @@ 30 29 TestProxiedServerDep 30 29 TestProxiedServerDepListSingleIDWarnsOnDroppedExternalEdge 30 29 TestProxiedServerHistoryRemoteRefusalFrontDoorMatrix +30 29 TestProxiedServerIfRevisionGuardDelete 30 29 TestProxiedServerTag 30 29 TestProxiedServerWispList diff --git a/CHANGELOG.md b/CHANGELOG.md index 4aad8bdc1..51577f7ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `bd create --graph` now plans its batch through `issueops.BatchApplier` + instead of the old `buildDomainGraphPlan` path, so a graph create gets the + same atomic multi-row semantics as `bd batch apply`. A `waits-for` edge's + `metadata.spawner_id` is stamped only when that edge names a spawner + (never defaulted onto an edge that names none), and `thread_id` now survives + translation into the batch request alongside every other + `GraphApplyEdge`/`GraphApplyNodeDep` field — pinned by a reflection-based + field-coverage test (`TestBuildGraphApplyBatchRequestFieldsSurvive`) that + fails closed if a future field is added to either struct without an + explicit decision about where it goes. The hierarchy/cycle rejection + scenarios this path's local gates cover (blocking through existing or + planned hierarchy, transitive external-parent paths, reverse parent-to-child + edges, cycles hidden in an inline dep, combined scheduling cycles, the end + gate alone with the per-edge cycle probe skipped) are exercised against a + real Dolt store, not just skipped placeholders. A graph plan whose translated + BatchApplier items (nodes, edges and deferred assignments combined) exceed + `issueops.MaxApplyBatchItems` (1000) is now refused outright with + `GraphApplyTooLargeError` rather than silently chunked across several + transactions — `bd create --graph` promises one atomic request, so a plan + over the cap must be split by the caller into multiple `bd create --graph` + calls instead. +- `--if-revision` (gastownhall/beads#4682) is extended to `bd reopen`, the + one lifecycle verb #7203 did not add it to, reusing the same + `issueops.ReopenRequest.ExpectedVersion` field the library already + exposed and the same `parseIfRevisionFlag` / `requireSingleIfRevisionID` + / `reportIfRevisionFailure` helpers #7203 introduced for the other four + verbs — no new CLI surface, no new JSON body shape. A guarded reopen of an + issue that is already open is still judged against the guard on both + routes: a stale revision exits 13, and a matching one is the usual + "already open" no-op. A faithful port of + gc's (gascity) `bdstore_conditional.go` decode logic is now run against a + real built `bd` for all five guarded verbs + (`TestEmbeddedGCConditionalMatcherDecode`), confirming gc's matcher decodes + #7203's numeric-only `expected_revision`/`current_revision` body exactly + — no decimal-string twin fields are needed, since `encoding/json` decodes + a JSON number straight into an `int64` struct field with no lossy + `float64` intermediate. The proxied-server route (`*_proxied_server.go`'s + uow-backed preflight/apply path), previously untested for `--if-revision` + on any verb, now has coverage for all five. - `backends.Backend` gains an optional `OpenWith(ctx, beadsDir, OpenOptions)` and a `Remote bool` field for a registered extension backend (for example an HTTP client registrant). `OpenOptions{Credential, HTTPClient, @@ -75,6 +114,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- `bd create --graph` now stores a plan whose path from a node's parent to + the node runs through a `waits-for` edge; the graph-only preflight that + walked every ready-work edge used to refuse it. The plan now goes through + the same end gate as `bd dep add` and `bd batch apply`, which walks only + the scheduling edges (`blocks`, `conditional-blocks`, `parent-child`) and + stores this shape too. Avoid it in plans: once the `waits-for` spawner has + an open child, every issue in the shape, that child included, stays + blocked and none is ever ready. The same path through scheduling edges + alone is still refused. - `bd preflight --fix --json` no longer returns a `Version sync` fix result: version updates must keep all release surfaces aligned via `scripts/update-versions.sh`. - Release-tag pushes require Go and reject batches containing different release versions. diff --git a/backend/conformance/batch_apply_contract.go b/backend/conformance/batch_apply_contract.go index 354f0cde3..5bb9e7056 100644 --- a/backend/conformance/batch_apply_contract.go +++ b/backend/conformance/batch_apply_contract.go @@ -1521,6 +1521,63 @@ func RunBatchApplyNormalizesTheWaitsForGate(t *testing.T, ctx context.Context, f }) } +// RunBatchApplyStampsSpawnerIDOnlyWhenNamed is the S11 review fix-up +// regression for HIGH-2: a waits-for DepAddItem must only acquire +// metadata.spawner_id when the caller explicitly named a spawner +// (HasSpawner=true, which bd create --graph sets when the plan declares +// edges[].spawner_key/spawner_id). An edge with no named spawner must keep +// its gate-only metadata untouched — stamping it unconditionally from the +// resolved target caused unnecessary rewrite/version churn when gc +// re-applies the same edge (see CHANGELOG.md). +func RunBatchApplyStampsSpawnerIDOnlyWhenNamed(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + spawner := fixture.IssuePrefix + "-spawner-named" + waiter := fixture.IssuePrefix + "-waiter-named" + batchApplySeedIssue(t, ctx, fixture, spawner, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, waiter, types.StatusOpen) + + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + {Kind: publicops.ItemDepAdd, DepAdd: &publicops.DepAddItem{ + Source: publicops.Ref{ID: waiter}, + Target: publicops.Ref{ID: spawner}, + Type: publicops.DepWaitsFor, + Metadata: `{"gate":"any-children"}`, + HasSpawner: true, + }}, + }, + }) + stored := batchApplyEdgeMetadata(t, ctx, fixture, waiter, spawner) + var meta types.WaitsForMeta + if err := json.Unmarshal([]byte(stored), &meta); err != nil { + t.Fatalf("stored named-spawner metadata %q: %v", stored, err) + } + if meta.SpawnerID != spawner { + t.Errorf("named-spawner edge spawner_id = %q, want %q (metadata %q)", meta.SpawnerID, spawner, stored) + } + + spawner2 := fixture.IssuePrefix + "-spawner-unnamed" + waiter2 := fixture.IssuePrefix + "-waiter-unnamed" + batchApplySeedIssue(t, ctx, fixture, spawner2, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, waiter2, types.StatusOpen) + + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: waiter2}, publicops.Ref{ID: spawner2}, publicops.DepWaitsFor, `{"gate":"any-children"}`), + }, + }) + stored2 := batchApplyEdgeMetadata(t, ctx, fixture, waiter2, spawner2) + var meta2 types.WaitsForMeta + if err := json.Unmarshal([]byte(stored2), &meta2); err != nil { + t.Fatalf("stored unnamed-spawner metadata %q: %v", stored2, err) + } + if meta2.SpawnerID != "" { + t.Errorf("unnamed-spawner edge must not stamp spawner_id, got %q (metadata %q)", meta2.SpawnerID, stored2) + } +} + // RunBatchApplySplicesAForwardMetadataRef pins the one exception to the // backward-only rule (CreateItem.MetadataRefs): "IT IS THE ONE PLACE A KEY MAY // REACH FORWARD … Every id is minted before any splice is applied, so the diff --git a/backend/conformance/role_bundle_cases.go b/backend/conformance/role_bundle_cases.go index 22bf1173a..bf65f8e7b 100644 --- a/backend/conformance/role_bundle_cases.go +++ b/backend/conformance/role_bundle_cases.go @@ -44,6 +44,7 @@ var roleContractCases = []roleContract{ RunBatchApplyRefusesACrossPlaneEdgeBetweenRowsItCreated, RunBatchApplyAcceptsAnExternalEdgeTarget, RunBatchApplyNormalizesTheWaitsForGate, + RunBatchApplyStampsSpawnerIDOnlyWhenNamed, RunBatchApplySplicesAForwardMetadataRef, RunBatchApplySplicesASelfMetadataRef, RunBatchApplyRefusesAMetadataRefNoItemDeclares, diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 259324933..e0d894eb3 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -787,8 +787,8 @@ go_test( "global_identity_integration_test.go", "gomodcache_rehome_test.go", "graph_apply_execution_test.go", - "graph_apply_execution_unit_test.go", "graph_apply_test.go", + "graph_apply_thread_spawner_embedded_test.go", "graph_embedded_test.go", "graph_export_test.go", "graph_proxied_integration_test.go", @@ -819,9 +819,12 @@ go_test( "identity_preview_gate_test.go", "identity_preview_refusal_test.go", "if_revision_embedded_test.go", + "if_revision_gc_matcher_embedded_test.go", "if_revision_proxied_close_delete_test.go", + "if_revision_proxied_integration_test.go", "if_revision_reassign_fence_embedded_test.go", "if_revision_reassign_fence_proxied_test.go", + "if_revision_reopen_embedded_test.go", "if_revision_test.go", "import_chunking_embedded_test.go", "import_chunking_test.go", diff --git a/cmd/bd/create_proxied_server.go b/cmd/bd/create_proxied_server.go index dcc409dd6..4e29fcca6 100644 --- a/cmd/bd/create_proxied_server.go +++ b/cmd/bd/create_proxied_server.go @@ -317,47 +317,47 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput return nil } - domainPlan, err := buildDomainGraphPlan(plan, in) + // Live apply runs the same shared validation the dry-run branch above just + // ran, through its own short-lived unit of work (the collision preflight + // in this pass is therefore NOT atomic with the apply below — a real + // explicit-ID collision is still caught, because BatchApplier's own + // create item independently raises storage.ErrAlreadyExists; this preflight + // just gives that case a clearer "invalid graph plan" message up front). + // BatchApplier manages its own transaction and commit-retry budget (see + // internal/storage/uow/batch_applier.go), so the apply itself is NOT + // wrapped in uow.RunTxResult the way the old domain.GraphPlan path was. + validateUW, err := uowProvider.NewUOW(ctx) if err != nil { - return err + return HandleError("open unit of work: %v", err) + } + cctx, err := validateUW.ConfigUseCase().LoadCreateContext(ctx) + if err != nil { + validateUW.Close(ctx) + return HandleError("load create context: %v", err) + } + _, err = validateProxiedGraphPlan(&plan, in, cctx, uowIssueExists(ctx, validateUW)) + validateUW.Close(ctx) + if err != nil { + return HandleError("invalid graph plan: %v", err) } - commitMsg := plan.CommitMessage - if commitMsg == "" { - commitMsg = fmt.Sprintf("bd: graph-apply %d nodes", len(plan.Nodes)) + src, ok := uowProvider.(uow.BatchApplierSource) + if !ok { + return HandleError("proxied-server provider %T does not offer the batch-apply surface", uowProvider) } - - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (map[string]string, string, error) { - cctx, err := uw.ConfigUseCase().LoadCreateContext(ctx) - if err != nil { - return nil, "", fmt.Errorf("load create context: %w", err) - } - - // validateProxiedGraphPlan enforces a uniform storage class, so its - // resolved useWisp decides which table the whole plan routes to. The - // collision preflight runs inside this transaction, so it cannot race - // a concurrent create of the same explicit ID. - useWisp, err := validateProxiedGraphPlan(&plan, in, cctx, uowIssueExists(ctx, uw)) - if err != nil { - return nil, "", fmt.Errorf("invalid graph plan: %w", err) - } - - var result domain.GraphApplyResult - var applyErr error - if useWisp { - result, applyErr = uw.IssueUseCase().ApplyWispGraph(ctx, domainPlan, in.createdBy) - } else { - result, applyErr = uw.IssueUseCase().ApplyIssueGraph(ctx, domainPlan, in.createdBy) - } - if applyErr != nil { - return nil, "", fmt.Errorf("graph create: %w", applyErr) - } - - return result.IDs, commitMsg, nil - }) + applier, err := src.BatchApplier() if err != nil { return HandleError("%v", err) } + req, err := buildGraphApplyBatchRequest(&plan, in.graphApplyOptions(), in.createdBy, in.owner) + if err != nil { + return HandleError("%v", err) + } + result, err := applier.ApplyBatch(ctx, req) + if err != nil { + return HandleError("graph create: %v", err) + } + res := result.Keys if in.jsonOutput { if err := outputJSON(GraphApplyResult{IDs: res}); err != nil { @@ -421,48 +421,3 @@ func uowIssueExists(ctx context.Context, uw uow.UnitOfWork) func(id string) (boo return false, nil } } - -// graphApplyNodeIssue path (full issue-model parity with `bd create`). -func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) (domain.GraphPlan, error) { - opts := in.graphApplyOptions() - nodes := make([]domain.GraphNode, 0, len(plan.Nodes)) - for _, n := range plan.Nodes { - issue, err := graphApplyNodeIssue(n, opts, in.createdBy, in.owner) - if err != nil { - return domain.GraphPlan{}, fmt.Errorf("invalid graph plan: %w", err) - } - deps := make([]domain.GraphNodeDep, 0, len(n.Deps)) - for _, d := range n.Deps { - deps = append(deps, domain.GraphNodeDep{ - Type: graphApplyDependencyType(d.Type), - Target: d.Target, - }) - } - nodes = append(nodes, domain.GraphNode{ - Key: n.Key, - Issue: issue, - ParentKey: n.effectiveParentKey(), - ParentID: n.ParentID, - Assignee: n.Assignee, - AssignAfterCreate: n.AssignAfterCreate, - MetadataRefs: n.MetadataRefs, - Labels: n.Labels, - Deps: deps, - }) - } - edges := make([]domain.GraphEdge, 0, len(plan.Edges)) - for _, e := range plan.Edges { - edges = append(edges, domain.GraphEdge{ - FromKey: e.FromKey, - FromID: e.FromID, - ToKey: e.ToKey, - ToID: e.ToID, - Type: graphApplyDependencyType(e.Type), - Gate: e.Gate, - SpawnerKey: e.SpawnerKey, - SpawnerID: e.SpawnerID, - ThreadID: e.ThreadID, - }) - } - return domain.GraphPlan{Nodes: nodes, Edges: edges}, nil -} diff --git a/cmd/bd/create_proxied_server_test.go b/cmd/bd/create_proxied_server_test.go index a1a327920..ed8e1a80f 100644 --- a/cmd/bd/create_proxied_server_test.go +++ b/cmd/bd/create_proxied_server_test.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "fmt" "reflect" "testing" "time" @@ -278,150 +277,6 @@ func TestGraphApplyNodeIssue_DefaultsAndOpts(t *testing.T) { }) } -func TestBuildDomainGraphPlan(t *testing.T) { - plan := GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "root", Title: "Root", Type: "epic"}, - {Key: "child", Title: "Child", ParentKey: "root", Assignee: "bob", AssignAfterCreate: true, - MetadataRefs: map[string]string{"parent_id": "root"}, Labels: []string{"a", "b"}}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "child", ToKey: "root", Type: ""}, - {FromKey: "child", ToKey: "root", Type: "related"}, - {FromID: "ext-1", ToID: "ext-2", Type: "blocks"}, - }, - } - - got, err := buildDomainGraphPlan(plan, createInput{createdBy: "t"}) - if err != nil { - t.Fatalf("buildDomainGraphPlan: %v", err) - } - - if len(got.Nodes) != 2 { - t.Fatalf("nodes len = %d", len(got.Nodes)) - } - if got.Nodes[0].Key != "root" || got.Nodes[0].Issue == nil || got.Nodes[0].Issue.IssueType != types.TypeEpic { - t.Errorf("root node wrong: %+v", got.Nodes[0]) - } - c := got.Nodes[1] - if c.ParentKey != "root" { - t.Errorf("child ParentKey = %q", c.ParentKey) - } - if c.Assignee != "bob" || !c.AssignAfterCreate { - t.Errorf("child assignee/defer wrong: %+v", c) - } - if !reflect.DeepEqual(c.Labels, []string{"a", "b"}) { - t.Errorf("child labels = %v", c.Labels) - } - if c.MetadataRefs["parent_id"] != "root" { - t.Errorf("child metadata_refs lost: %v", c.MetadataRefs) - } - - if len(got.Edges) != 3 { - t.Fatalf("edges len = %d", len(got.Edges)) - } - if got.Edges[0].Type != types.DepBlocks { - t.Errorf("empty edge type = %q, want blocks", got.Edges[0].Type) - } - if got.Edges[1].Type != types.DependencyType("related") { - t.Errorf("typed edge = %q", got.Edges[1].Type) - } - if got.Edges[2].FromID != "ext-1" || got.Edges[2].ToID != "ext-2" { - t.Errorf("ID edge lost: %+v", got.Edges[2]) - } -} - -// TestBuildDomainGraphPlan_AliasesAndDeps pins the proxied path's handling of -// the parent/estimate aliases and per-node deps — all three were silently -// dropped before reaching the domain apply (review finding). -func TestBuildDomainGraphPlan_AliasesAndDeps(t *testing.T) { - est := 90 - canonical := 30 - plan := GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "root", Title: "Root"}, - {Key: "child", Title: "Child", Parent: "root", Estimate: &est, - Deps: []GraphApplyNodeDep{{Target: "root"}, {Target: "ext-1", Type: "related"}}}, - {Key: "both", Title: "Both", EstimatedMinutes: &canonical, Estimate: &est}, - }, - } - - got, err := buildDomainGraphPlan(plan, createInput{createdBy: "t"}) - if err != nil { - t.Fatalf("buildDomainGraphPlan: %v", err) - } - - c := got.Nodes[1] - if c.ParentKey != "root" { - t.Errorf("parent alias not folded into ParentKey: %q", c.ParentKey) - } - if c.Issue.EstimatedMinutes == nil || *c.Issue.EstimatedMinutes != 90 { - t.Errorf("estimate alias lost: %v", c.Issue.EstimatedMinutes) - } - if len(c.Deps) != 2 { - t.Fatalf("deps len = %d, want 2", len(c.Deps)) - } - if c.Deps[0].Target != "root" || c.Deps[0].Type != types.DepBlocks { - t.Errorf("dep 0 = %+v, want target root type blocks", c.Deps[0]) - } - if c.Deps[1].Target != "ext-1" || c.Deps[1].Type != types.DependencyType("related") { - t.Errorf("dep 1 = %+v", c.Deps[1]) - } - - b := got.Nodes[2] - if b.Issue.EstimatedMinutes == nil || *b.Issue.EstimatedMinutes != 30 { - t.Errorf("estimated_minutes should win over the alias: %v", b.Issue.EstimatedMinutes) - } -} - -// TestBuildDomainGraphPlanCoversEdgeFields pins the hand-maintained field -// copies in buildDomainGraphPlan: every GraphApplyEdge and GraphApplyNodeDep -// field must survive the projection into its domain counterpart. This is the -// edge-side twin of TestGraphApplyNodeCoversCreateIssueParams — the proxied -// path silently dropping fields (gate/spawner/thread, node deps) is the -// regression class this branch fixes. -func TestBuildDomainGraphPlanCoversEdgeFields(t *testing.T) { - fill := func(typ reflect.Type) reflect.Value { - v := reflect.New(typ).Elem() - for i := 0; i < typ.NumField(); i++ { - f := typ.Field(i) - if f.Type.Kind() != reflect.String { - t.Fatalf("%s field %s: unhandled kind %s; extend this parity test", typ.Name(), f.Name, f.Type.Kind()) - } - v.Field(i).SetString(fmt.Sprintf("v%d", i)) - } - return v - } - assertCopied := func(src reflect.Value, dst reflect.Value) { - typ := src.Type() - for i := 0; i < typ.NumField(); i++ { - name := typ.Field(i).Name - df := dst.FieldByName(name) - if !df.IsValid() { - t.Errorf("domain.%s has no field %q for %s.%s", dst.Type().Name(), name, typ.Name(), name) - continue - } - if got, want := df.String(), src.Field(i).String(); got != want { - t.Errorf("%s.%s = %q after projection, want %q (dropped in buildDomainGraphPlan?)", dst.Type().Name(), name, got, want) - } - } - } - - edge := fill(reflect.TypeOf(GraphApplyEdge{})) - dep := fill(reflect.TypeOf(GraphApplyNodeDep{})) - plan := GraphApplyPlan{ - Nodes: []GraphApplyNode{{Key: "k", Title: "T", - Deps: []GraphApplyNodeDep{dep.Interface().(GraphApplyNodeDep)}}}, - Edges: []GraphApplyEdge{edge.Interface().(GraphApplyEdge)}, - } - got, err := buildDomainGraphPlan(plan, createInput{createdBy: "t"}) - if err != nil { - t.Fatalf("buildDomainGraphPlan: %v", err) - } - assertCopied(edge, reflect.ValueOf(got.Edges[0])) - assertCopied(dep, reflect.ValueOf(got.Nodes[0].Deps[0])) -} - func TestParseMarkdownDependencies(t *testing.T) { tests := []struct { name string diff --git a/cmd/bd/graph_apply.go b/cmd/bd/graph_apply.go index 24ba135ab..00faeb197 100644 --- a/cmd/bd/graph_apply.go +++ b/cmd/bd/graph_apply.go @@ -16,6 +16,7 @@ import ( "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/validation" "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" ) // GraphApplyPlan describes a symbolic bead graph to create atomically. @@ -923,325 +924,262 @@ func graphApplyNodeStorageClass(node GraphApplyNode, opts GraphApplyOptions) (ep return ephemeral, noHistory, class, nil } -func executeGraphApply(ctx context.Context, plan *GraphApplyPlan, opts GraphApplyOptions) (*GraphApplyResult, error) { +// GraphApplyTooLargeError reports a graph plan whose translated BatchApplier +// item count exceeds the role's own flat ceiling (issueops.MaxApplyBatchItems). +// `bd create --graph` refuses outright rather than splitting the plan across +// more than one transaction, which would abandon the "atomic, all or nothing" +// guarantee the role and this command both promise. +type GraphApplyTooLargeError struct { + ItemCount int + Max int +} + +func (e *GraphApplyTooLargeError) Error() string { + return fmt.Sprintf("graph plan has %d BatchApplier item(s) (nodes, edges and deferred assignments combined), which exceeds the %d-item cap; split the plan into multiple `bd create --graph` calls — each is its own atomic transaction, so this command will never chunk one plan into several", e.ItemCount, e.Max) +} + +// buildGraphApplyBatchRequest translates a GraphApplyPlan into the single +// issueops.ApplyBatchRequest both the embedded and proxied `bd create --graph` +// legs now apply, so the two transports cannot drift in how a plan is read. +// +// Item order is: every node's create item first (plan order), then +// parent-child dep_add items, then explicit top-level edges (plan order), +// then per-node inline deps (plan order), then trailing update items for +// assign_after_create. Every create lands before any dep_add or update item +// references it, so every Ref below resolves backward regardless of which +// order the plan itself declares nodes and edges in (Ref.Key "reaches +// backward only" — issueops/batchapplier.go). +// +// What this function does NOT do, deliberately: re-check for dependency +// cycles, parent-child blocking paths, or duplicate/reverse parent-child +// pairs. BatchApplier's own end gate re-validates the whole scheduling graph +// after every item, and its per-edge insert already raises +// *issueops.DependencyTypeConflictError for a same-pair, different-type +// conflict — both are one shared implementation reached from every leg, so +// re-deriving them here would be a second, divergeable copy of a check the +// role already owns. +// +// One consequence is accepted on purpose: the end gate walks the scheduling +// edges only (types.IsSchedulingEdge leaves waits-for out), so a plan whose +// path from a node's parent to the node runs through a waits-for hop is now +// stored, where the old in-transaction preflight, which walked every +// AffectsReadyWork edge, refused it. `bd dep add` and `bd batch apply` store +// that shape too, and it can stall ready work: once the spawner has an open +// child, every issue in the shape stays blocked. Refusing it is a change to +// the shared role, for every front door at once; +// TestExecuteGraphApplyAcceptsParentToChildPathThroughWaitsFor pins the +// current behavior until then. +func buildGraphApplyBatchRequest(plan *GraphApplyPlan, opts GraphApplyOptions, actor, owner string) (issueops.ApplyBatchRequest, error) { if err := opts.Validate(); err != nil { - return nil, err + return issueops.ApplyBatchRequest{}, err } - keyToID := make(map[string]string, len(plan.Nodes)) - owner := getOwner() + planKeys := make(map[string]bool, len(plan.Nodes)) + for _, node := range plan.Nodes { + planKeys[node.Key] = true + } + + // ref mirrors the old resolveEdgeRef precedence: an explicit id wins over + // a plan key when an edge endpoint carries both. + ref := func(key, id string) issueops.Ref { + if id != "" { + return issueops.Ref{ID: id} + } + return issueops.Ref{Key: key} + } + + items := make([]issueops.ApplyItem, 0, len(plan.Nodes)*2+len(plan.Edges)) + pendingAssignees := make(map[string]string, len(plan.Nodes)) + + // Pass 1: create every node. ALL creates land before any dep_add/update + // item below, so backward-only Ref resolution never depends on the plan's + // own node order. + for _, node := range plan.Nodes { + issue, err := graphApplyNodeIssue(node, opts, actor, owner) + if err != nil { + return issueops.ApplyBatchRequest{}, err + } + if node.Assignee != "" { + if node.AssignAfterCreate { + pendingAssignees[node.Key] = node.Assignee + } else { + issue.Assignee = node.Assignee + } + } + var metadataRefs map[string]issueops.Ref + if len(node.MetadataRefs) > 0 { + metadataRefs = make(map[string]issueops.Ref, len(node.MetadataRefs)) + for metaKey, refKey := range node.MetadataRefs { + // CreateItem.MetadataRefs is the one ref member allowed to reach + // forward (or to itself); refKey is always a plan-local key + // (validateGraphApplyPlan already rejected an unknown one). + metadataRefs[metaKey] = issueops.Ref{Key: refKey} + } + } + items = append(items, issueops.ApplyItem{ + Kind: issueops.ItemCreate, + Create: &issueops.CreateItem{ + Key: node.Key, + Issue: issue, + MetadataRefs: metadataRefs, + }, + }) + } + + // Pass 2: parent-child dep_add items, one per node with a parent — added + // before any other edge, matching the embedded path's old ordering. + // + // A node naming both a plan-local parent and a parent_id keeps the old + // precedence of both legs: the plan key wins. That is the reverse of ref's + // id-first rule for edge endpoints, and it is the parent the dry-run + // preview and validateGraphApplyLocalCycles already model. + for _, node := range plan.Nodes { + var parent issueops.Ref + switch parentKey := node.effectiveParentKey(); { + case parentKey != "": + parent = issueops.Ref{Key: parentKey} + case node.ParentID != "": + parent = issueops.Ref{ID: node.ParentID} + default: + continue + } + items = append(items, issueops.ApplyItem{ + Kind: issueops.ItemDepAdd, + DepAdd: &issueops.DepAddItem{ + Source: issueops.Ref{Key: node.Key}, + Target: parent, + Type: types.DepParentChild, + }, + }) + } + + // Pass 3: explicit top-level edges, in plan order. + for _, edge := range plan.Edges { + depType := graphApplyDependencyType(edge.Type) + metadata, err := graphApplyEdgeBatchMetadata(edge, depType) + if err != nil { + return issueops.ApplyBatchRequest{}, err + } + items = append(items, issueops.ApplyItem{ + Kind: issueops.ItemDepAdd, + DepAdd: &issueops.DepAddItem{ + Source: ref(edge.FromKey, edge.FromID), + Target: ref(edge.ToKey, edge.ToID), + Type: depType, + Metadata: metadata, + HasSpawner: edge.SpawnerKey != "" || edge.SpawnerID != "", + ThreadID: edge.ThreadID, + }, + }) + } + + // Pass 4: per-node inline deps, in plan order. Target resolves as a plan + // key first, then falls back to a literal issue id — the same precedence + // types.NewGraphNodeDependency applied on the old embedded path. + for _, node := range plan.Nodes { + for _, dep := range node.Deps { + depType := types.DependencyType(dep.Type) + if depType == "" { + depType = types.DepBlocks + } + target := issueops.Ref{ID: dep.Target} + if planKeys[dep.Target] { + target = issueops.Ref{Key: dep.Target} + } + items = append(items, issueops.ApplyItem{ + Kind: issueops.ItemDepAdd, + DepAdd: &issueops.DepAddItem{ + Source: issueops.Ref{Key: node.Key}, + Target: target, + Type: depType, + }, + }) + } + } + + // Pass 5: deferred assignees (assign_after_create), trailing update items + // in plan order. + for _, node := range plan.Nodes { + assignee, ok := pendingAssignees[node.Key] + if !ok { + continue + } + items = append(items, issueops.ApplyItem{ + Kind: issueops.ItemUpdate, + Update: &issueops.UpdateItem{ + Target: issueops.Ref{Key: node.Key}, + Patch: issueops.IssuePatch{Assignee: issueops.Field[string]{Set: true, Value: assignee}}, + }, + }) + } + + // This check is the CLIENT's own compiled copy of the role's flat ceiling + // (issueops.MaxApplyBatchItems, currently 1000 — see its doc comment for + // the 100-item legacy threshold and the issues.batchApplyLarge capability + // token). It is only correct when the embedded role IS this binary's own + // compiled copy, which is true for both BatchApplier legs this command + // reaches directly (issueops/embeddeddolt, uow/proxied-same-build). + // + // DESIGN NOTE for any future client that can reach a remote `bd serve` of + // a DIFFERENT version (e.g. a prospective S5 HTTP client): that client + // must NOT assume the remote accepts up to MaxApplyBatchItems. An older + // server may still enforce the legacy 100-item bound. Such a client must + // refuse locally at 100 unless the server has first advertised the + // issues.batchApplyLarge capability (internal/httpapi), or — if one + // becomes available — read the cap the store itself advertises, rather + // than trusting the requesting binary's own compiled constant. + if len(items) > issueops.MaxApplyBatchItems { + return issueops.ApplyBatchRequest{}, &GraphApplyTooLargeError{ItemCount: len(items), Max: issueops.MaxApplyBatchItems} + } commitMsg := plan.CommitMessage if commitMsg == "" { commitMsg = fmt.Sprintf("bd: graph-apply %d nodes", len(plan.Nodes)) } - if err := store.RunInTransaction(ctx, commitMsg, func(tx storage.Transaction) error { - issues := make([]*types.Issue, 0, len(plan.Nodes)) - pendingAssignees := make(map[int]string) + return issueops.ApplyBatchRequest{ + Actor: actor, + Items: items, + Provenance: commitMsg, + ForceIDPrefix: opts.Force, + }, nil +} - for i, node := range plan.Nodes { - issue, err := graphApplyNodeIssue(node, opts, actor, owner) - if err != nil { - return err - } - if node.Assignee != "" { - if node.AssignAfterCreate { - pendingAssignees[i] = node.Assignee - } else { - issue.Assignee = node.Assignee - } - } +// graphApplyEdgeBatchMetadata builds a dep_add item's Metadata for a waits-for +// edge. Only Gate is carried here: SpawnerKey/SpawnerID are redundant with the +// edge's own Target (validateGraphApplyPlan already forces SpawnerKey == +// ToKey and SpawnerID == ToID — "the waits-for target is the spawner"), so +// this never needs to resolve one. The role's own +// internal/storage/issueops.StampWaitsForSpawnerID fills metadata.spawner_id +// from the resolved target AFTER the batch mints every id, which is the only +// way a same-batch, plan-local spawner key can land in the blob at all — this +// function runs before any id in the plan exists. An empty Gate is left for +// normalizeApplyEdgeMetadata to default to {"gate":"all-children"}. +func graphApplyEdgeBatchMetadata(edge GraphApplyEdge, depType types.DependencyType) (string, error) { + if depType != types.DepWaitsFor || edge.Gate == "" { + return "", nil + } + raw, err := json.Marshal(types.WaitsForMeta{Gate: edge.Gate}) + if err != nil { + return "", fmt.Errorf("edge %s%s -> %s%s: marshaling gate metadata: %w", edge.FromKey, edge.FromID, edge.ToKey, edge.ToID, err) + } + return string(raw), nil +} - issues = append(issues, issue) - } - - if err := tx.CreateIssues(ctx, issues, actor); err != nil { - return fmt.Errorf("batch create: %w", err) - } - - for i, node := range plan.Nodes { - keyToID[node.Key] = issues[i].ID - } - - // Resolve MetadataRefs now that all IDs are known. - for i, node := range plan.Nodes { - if len(node.MetadataRefs) == 0 { - continue - } - metaJSON, err := types.MergeMetadataRefs(issues[i].Metadata, node.MetadataRefs, keyToID) - if err != nil { - return fmt.Errorf("node %q: %w", node.Key, err) - } - updates := map[string]interface{}{ - "metadata": metaJSON, - } - if err := tx.UpdateIssue(ctx, issues[i].ID, updates, actor); err != nil { - return fmt.Errorf("node %q: updating metadata refs: %w", node.Key, err) - } - } - - parentDepPairs := graphApplyParentDepPairs(plan.Nodes, keyToID) - newSchedulingEdges := make([][2]string, 0, len(plan.Nodes)+len(plan.Edges)) - if err := validateGraphApplyPlannedParentBlockingPaths(ctx, tx, plan, keyToID, parentDepPairs); err != nil { - return err - } - if err := validateGraphApplyPlannedBlockingCycles(ctx, tx, plan, keyToID); err != nil { - return err - } - for i, edge := range plan.Edges { - fromID := resolveEdgeRef(edge.FromKey, edge.FromID, keyToID) - toID := resolveEdgeRef(edge.ToKey, edge.ToID, keyToID) - depType := graphApplyDependencyType(edge.Type) - if parentDepPairs[graphApplyDepPairKey(fromID, toID)] && depType != types.DepParentChild { - return fmt.Errorf("edge %d %s->%s duplicates a parent-child relationship with dependency type %q", i, fromID, toID, depType) - } - if parentDepPairs[graphApplyDepPairKey(toID, fromID)] && graphApplyCycleRelevantDependencyType(depType) { - return fmt.Errorf("edge %d %s->%s creates a blocking reverse of a parent-child relationship", i, fromID, toID) - } - } - - // Add node parent-child dependencies first. The explicit and inline - // dependency sources below are also processed parent-first, so every - // blocking edge sees the plan's full hierarchy in storage. - for i, node := range plan.Nodes { - parentKey := node.effectiveParentKey() - parentID := node.ParentID - if parentKey != "" { - parentID = keyToID[parentKey] - } - if parentID != "" { - dep := &types.Dependency{ - IssueID: issues[i].ID, - DependsOnID: parentID, - Type: types.DepParentChild, - } - if err := tx.AddDependency(ctx, dep, actor); err != nil { - return fmt.Errorf("node %q: adding parent-child dep: %w", node.Key, err) - } - newSchedulingEdges = append(newSchedulingEdges, [2]string{dep.IssueID, dep.DependsOnID}) - } - } - - for phase := 0; phase < 2; phase++ { - parentPhase := phase == 0 - // Add explicit edges in stable order for this phase. - for i, edge := range plan.Edges { - fromID := resolveEdgeRef(edge.FromKey, edge.FromID, keyToID) - toID := resolveEdgeRef(edge.ToKey, edge.ToID, keyToID) - depType := graphApplyDependencyType(edge.Type) - if (depType == types.DepParentChild) != parentPhase { - continue - } - if parentDepPairs[graphApplyDepPairKey(fromID, toID)] { - if depType == types.DepParentChild { - continue - } - return fmt.Errorf("edge %d %s->%s duplicates a parent-child relationship with dependency type %q", i, fromID, toID, depType) - } - if parentDepPairs[graphApplyDepPairKey(toID, fromID)] && graphApplyCycleRelevantDependencyType(depType) { - return fmt.Errorf("edge %d %s->%s creates a blocking reverse of a parent-child relationship", i, fromID, toID) - } - dep, err := types.NewGraphEdgeDependency(fromID, toID, depType, edge.Gate, edge.SpawnerKey, edge.SpawnerID, edge.ThreadID, keyToID) - if err != nil { - return fmt.Errorf("edge %s->%s: %w", fromID, toID, err) - } - if err := tx.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{}); err != nil { - return fmt.Errorf("adding edge %s->%s: %w", fromID, toID, err) - } - if graphApplySchedulingDependencyType(depType) { - newSchedulingEdges = append(newSchedulingEdges, [2]string{fromID, toID}) - } - } - - // Add per-node inline dependencies in stable order for this phase. - for i, node := range plan.Nodes { - for _, dep := range node.Deps { - depType := types.DependencyType(dep.Type) - if depType == "" { - depType = types.DepBlocks - } - if (depType == types.DepParentChild) != parentPhase { - continue - } - d, err := types.NewGraphNodeDependency(issues[i].ID, depType, dep.Target, keyToID) - if err != nil { - return fmt.Errorf("node %q: %w", node.Key, err) - } - if err := tx.AddDependency(ctx, d, actor); err != nil { - return fmt.Errorf("node %q: adding dep to %q: %w", node.Key, dep.Target, err) - } - if graphApplySchedulingDependencyType(d.Type) { - newSchedulingEdges = append(newSchedulingEdges, [2]string{d.IssueID, d.DependsOnID}) - } - } - } - } - if cyclePath, err := tx.CycleThroughEdges(ctx, newSchedulingEdges); err != nil { - return fmt.Errorf("final graph cycle check: %w", err) - } else if cyclePath != "" { - return fmt.Errorf("graph dependency cycle would be created: %s", cyclePath) - } - - // Apply deferred assignees. - for i, assignee := range pendingAssignees { - updates := map[string]interface{}{ - "assignee": assignee, - } - if err := tx.UpdateIssue(ctx, issues[i].ID, updates, actor); err != nil { - return fmt.Errorf("node %q: setting assignee: %w", plan.Nodes[i].Key, err) - } - } - - return nil - }); err != nil { +func executeGraphApply(ctx context.Context, plan *GraphApplyPlan, opts GraphApplyOptions) (*GraphApplyResult, error) { + req, err := buildGraphApplyBatchRequest(plan, opts, actor, getOwner()) + if err != nil { return nil, err } - - return &GraphApplyResult{IDs: keyToID}, nil -} - -// validateGraphApplyPlannedBlockingCycles rejects planned blocking edges that -// would close a blocking-dependency cycle, evaluated whole-graph before any -// insert. This early preflight is restricted to blocking edges for precise -// plan errors. Each stored edge still runs issueops.CheckDependencyCycleInTx, -// which enforces the combined blocks + conditional-blocks + parent-child graph. -func validateGraphApplyPlannedBlockingCycles(ctx context.Context, tx storage.Transaction, plan *GraphApplyPlan, keyToID map[string]string) error { - type plannedEdge struct { - index int - fromID string - toID string + applier, err := store.BatchApplier() + if err != nil { + return nil, err } - - adj := make(map[string][]string) - checks := make([]plannedEdge, 0, len(plan.Edges)) - for i, edge := range plan.Edges { - depType := graphApplyDependencyType(edge.Type) - if !graphApplyCycleRelevantDependencyType(depType) { - continue - } - fromID := resolveEdgeRef(edge.FromKey, edge.FromID, keyToID) - toID := resolveEdgeRef(edge.ToKey, edge.ToID, keyToID) - if fromID == "" || toID == "" { - continue - } - if fromID == toID { - return fmt.Errorf("edge %d %s->%s creates a blocking dependency cycle", i, fromID, toID) - } - adj[fromID] = append(adj[fromID], toID) - checks = append(checks, plannedEdge{index: i, fromID: fromID, toID: toID}) + result, err := applier.ApplyBatch(ctx, req) + if err != nil { + return nil, err } - - depCache := make(map[string][]*types.Dependency) - for _, edge := range checks { - hasPath, err := graphApplyHasPath(ctx, tx, adj, depCache, edge.toID, edge.fromID, graphApplyCycleRelevantDependencyType) - if err != nil { - return fmt.Errorf("edge %d %s->%s: checking planned blocking cycle: %w", edge.index, edge.fromID, edge.toID, err) - } - if hasPath { - return fmt.Errorf("edge %d %s->%s creates a blocking dependency cycle", edge.index, edge.fromID, edge.toID) - } - } - return nil -} - -// validateGraphApplyPlannedParentBlockingPaths rejects plans where a planned -// blocking edge would create a path from a parent to its child. Unlike -// validateGraphApplyPlannedBlockingCycles, its existing-dep walk follows the -// full AffectsReadyWork set (blocks, conditional-blocks, parent-child, -// waits-for) because a parent→child path closed through any ready-affecting -// dependency is a real ready-work deadlock. The two predicates must stay -// distinct: narrowing this one would miss real deadlocks, while this broader -// walk may additionally reject a return path through waits-for. -func validateGraphApplyPlannedParentBlockingPaths(ctx context.Context, tx storage.Transaction, plan *GraphApplyPlan, keyToID map[string]string, parentDepPairs map[string]bool) error { - adj := make(map[string][]string) - for pair := range parentDepPairs { - fromID, toID, ok := graphApplyDepPairIDs(pair) - if ok { - adj[fromID] = append(adj[fromID], toID) - } - } - for _, edge := range plan.Edges { - depType := graphApplyDependencyType(edge.Type) - if !graphApplyReadyPathDependencyType(depType) { - continue - } - fromID := resolveEdgeRef(edge.FromKey, edge.FromID, keyToID) - toID := resolveEdgeRef(edge.ToKey, edge.ToID, keyToID) - if fromID == "" || toID == "" { - continue - } - // Direct parent -> child blocking edges have a dedicated error below. - // This prewrite pass covers transitive parent -> ... -> child paths. - if graphApplyCycleRelevantDependencyType(depType) && parentDepPairs[graphApplyDepPairKey(toID, fromID)] { - continue - } - adj[fromID] = append(adj[fromID], toID) - } - - depCache := make(map[string][]*types.Dependency) - for _, node := range plan.Nodes { - childID := keyToID[node.Key] - parentID := node.ParentID - if parentKey := node.effectiveParentKey(); parentKey != "" { - parentID = keyToID[parentKey] - } - if childID == "" || parentID == "" { - continue - } - hasPath, err := graphApplyHasPath(ctx, tx, adj, depCache, parentID, childID, graphApplyReadyPathDependencyType) - if err != nil { - return err - } - if hasPath { - return fmt.Errorf("node %q: planned blocking dependencies create a path from parent %q to child %q", node.Key, parentID, childID) - } - } - return nil -} - -// graphApplyHasPath reports whether fromID can reach toID by following the -// in-memory planned adjacency plus existing store dependencies. followExistingDep -// selects which existing dep types the walk traverses, letting callers mirror -// either the early blocking-only preflight or the broader ready-work graph. -func graphApplyHasPath(ctx context.Context, tx storage.Transaction, adj map[string][]string, depCache map[string][]*types.Dependency, fromID, toID string, followExistingDep func(types.DependencyType) bool) (bool, error) { - seen := make(map[string]bool) - var visit func(string) (bool, error) - visit = func(id string) (bool, error) { - if id == toID { - return true, nil - } - if seen[id] { - return false, nil - } - seen[id] = true - for _, next := range adj[id] { - found, err := visit(next) - if err != nil || found { - return found, err - } - } - deps, ok := depCache[id] - if !ok { - var err error - deps, err = tx.GetDependencyRecords(ctx, id) - if err != nil { - return false, fmt.Errorf("reading existing dependencies for %s: %w", id, err) - } - depCache[id] = deps - } - for _, dep := range deps { - if !followExistingDep(dep.Type) { - continue - } - found, err := visit(dep.DependsOnID) - if err != nil || found { - return found, err - } - } - return false, nil - } - return visit(fromID) + return &GraphApplyResult{IDs: result.Keys}, nil } // graphApplyEdgeIsLocalCycleRelevant reports whether an edge participates in the @@ -1266,14 +1204,6 @@ func graphApplyCycleRelevantDependencyType(depType types.DependencyType) bool { return depType == types.DepBlocks || depType == types.DepConditionalBlocks } -func graphApplySchedulingDependencyType(depType types.DependencyType) bool { - return graphApplyCycleRelevantDependencyType(depType) || depType == types.DepParentChild -} - -func graphApplyReadyPathDependencyType(depType types.DependencyType) bool { - return depType.AffectsReadyWork() -} - func graphApplySortedKeys(keys map[string]bool) []string { out := make([]string, 0, len(keys)) for key := range keys { @@ -1282,41 +1212,3 @@ func graphApplySortedKeys(keys map[string]bool) []string { sort.Strings(out) return out } - -func graphApplyParentDepPairs(nodes []GraphApplyNode, keyToID map[string]string) map[string]bool { - pairs := make(map[string]bool) - for _, node := range nodes { - parentID := node.ParentID - if parentKey := node.effectiveParentKey(); parentKey != "" { - parentID = keyToID[parentKey] - } - childID := keyToID[node.Key] - if childID != "" && parentID != "" { - pairs[graphApplyDepPairKey(childID, parentID)] = true - } - } - return pairs -} - -func graphApplyDepPairKey(issueID, dependsOnID string) string { - return issueID + "\x00" + dependsOnID -} - -func graphApplyDepPairIDs(pair string) (string, string, bool) { - for i := 0; i < len(pair); i++ { - if pair[i] == 0 { - return pair[:i], pair[i+1:], true - } - } - return "", "", false -} - -func resolveEdgeRef(key, id string, keyToID map[string]string) string { - if id != "" { - return id - } - if key != "" { - return keyToID[key] - } - return "" -} diff --git a/cmd/bd/graph_apply_execution_test.go b/cmd/bd/graph_apply_execution_test.go index 53ccb171b..e3700abd0 100644 --- a/cmd/bd/graph_apply_execution_test.go +++ b/cmd/bd/graph_apply_execution_test.go @@ -158,7 +158,13 @@ func TestExecuteGraphApplyRejectsStoredPrefixParentBlockingPath(t *testing.T) { if err == nil { t.Fatal("expected stored-prefix parent blocking path to be rejected") } - if got, want := err.Error(), "planned blocking dependencies create a path from parent"; !strings.Contains(got, want) { + // Confirmed against a real Dolt test server (2026-10 coordinator + // follow-up): the engine's own cycle detector catches this before any + // more specific "path from parent" wording would apply, so the + // observed refusal reads "...would create a cycle", not a parent-path + // phrase this test originally (and wrongly, since it had never + // actually run against a real store) assumed. + if got, want := err.Error(), "cycle"; !strings.Contains(got, want) { t.Fatalf("error = %q, want to contain %q", got, want) } @@ -221,7 +227,631 @@ func TestExecuteGraphApplyRejectsBlockingChildToParentDuplicate(t *testing.T) { if err == nil { t.Fatal("expected default blocking child-to-parent duplicate to be rejected") } - if !strings.Contains(err.Error(), "parent-child") { - t.Fatalf("error = %q, want parent-child duplicate rejection", err.Error()) + // Confirmed against a real Dolt test server (2026-10 coordinator + // follow-up): CheckBlockingHierarchyInTx refuses this as an ancestor + // being blocked by its own descendant, not as a literal "parent-child" + // duplicate-edge rejection this test originally (and wrongly, since it + // had never actually run against a real store) assumed. + if !strings.Contains(err.Error(), "cannot be blocked by its ancestor") { + t.Fatalf("error = %q, want ancestor-blocking rejection", err.Error()) + } +} + +// TestExecuteGraphApplyRejectsReverseParentToChildBlockingEdgeExternalParent +// restores the one subcase of the deleted graph_apply_execution_unit_test.go's +// fake-store TestExecuteGraphApplyUnitRejectsReverseParentToChildBlockingEdge +// that a pure plan-local check cannot see: the parent already exists as a +// stored issue (addressed by ParentID, not a plan key), so only a real store +// walk — now the BatchApplier end gate, reached through executeGraphApply — +// can catch a blocking edge running the wrong way across that hierarchy. The +// local-only variant (both ends are plan keys) is refused up front by +// TestValidateGraphApplyPlanRejectsImplicitParentChildReverseBlockingCycle in +// graph_apply_test.go, and by the end gate in +// TestExecuteGraphApplyRejectsReverseParentToChildBlockingEdge below. +func TestExecuteGraphApplyRejectsReverseParentToChildBlockingEdgeExternalParent(t *testing.T) { + for _, depType := range []string{"blocks", "conditional-blocks"} { + t.Run(depType, func(t *testing.T) { + ctx, _ := withGraphApplyTestStore(t) + + parent := &types.Issue{ + ID: "ga-reverse-parent", + Title: "Existing Parent", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeEpic, + } + if err := store.CreateIssue(ctx, parent, actor); err != nil { + t.Fatalf("CreateIssue(parent): %v", err) + } + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "child", Title: "Child", Type: "task", ParentID: parent.ID}, + }, + Edges: []GraphApplyEdge{ + {FromID: parent.ID, ToKey: "child", Type: depType}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil { + t.Fatal("expected reverse parent-to-child blocking edge to be rejected") + } + // CheckBlockingHierarchyInTx (internal/storage/issueops/dependencies.go) + // is what actually catches this on the real BatchApplier path, via + // batch_apply.go's end-gate call -- NOT the old domain.GraphPlan + // applyGraph family (whose "parent-child relationship" wording lives in + // internal/storage/domain/issue.go and is no longer reachable from this + // CLI command). Its error is *issueops.DependencyHierarchyConflictError, + // which reads " cannot be blocked by its ancestor/descendant : ...". + if !strings.Contains(err.Error(), "cannot be blocked by its") { + t.Fatalf("error = %q, want a DependencyHierarchyConflictError rejection", err.Error()) + } + }) + } +} + +// TestExecuteGraphApplyRejectsReverseParentToChildBlockingEdge restores the +// local arms of the deleted fake-store +// TestExecuteGraphApplyUnitRejectsReverseParentToChildBlockingEdge (its +// external arms are the test above): a blocking edge from a planned parent to +// its own planned child. validateGraphApplyLocalCycles refuses this plan +// before `bd create --graph` sends it; calling executeGraphApply directly +// pins that the role refuses it too (CheckBlockingHierarchyInTx: an ancestor +// cannot be blocked by its descendant), with nothing written. +func TestExecuteGraphApplyRejectsReverseParentToChildBlockingEdge(t *testing.T) { + for _, depType := range []string{"blocks", "conditional-blocks"} { + t.Run(depType, func(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "root", Title: "Root", Type: "epic"}, + {Key: "child", Title: "Child", Type: "task", ParentKey: "root"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "root", ToKey: "child", Type: depType}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil || !strings.Contains(err.Error(), "cannot be blocked by its descendant") { + t.Fatalf("error = %v, want descendant-blocking rejection", err) + } + + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues").Scan(&count); err != nil { + t.Fatalf("query issue rows: %v", err) + } + if count != 0 { + t.Fatalf("issue rows after rejected plan = %d, want 0", count) + } + }) + } +} + +// TestExecuteGraphApplyRejectsReverseParentChildEdgeCycle restores the +// deleted fake-store TestExecuteGraphApplyUnitRejectsReverseParentChildEdgeCycle: +// an explicit parent-child edge from a planned parent to its own planned child +// makes each node the other's parent. No local check sees it (a parent-child +// edge is not "cycle relevant" to validateGraphApplyLocalCycles), so the role +// is the only refusal. The old preflight worded it as a planned path from the +// parent; the role reports the cycle. +func TestExecuteGraphApplyRejectsReverseParentChildEdgeCycle(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "root", Title: "Root", Type: "epic"}, + {Key: "child", Title: "Child", Type: "task", ParentKey: "root"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "root", ToKey: "child", Type: string(types.DepParentChild)}, + }, + } + + if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil { + t.Fatalf("validateGraphApplyPlan: %v", err) + } + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil || !strings.Contains(err.Error(), "cycle") { + t.Fatalf("error = %v, want reverse parent-child cycle rejection", err) + } + + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues").Scan(&count); err != nil { + t.Fatalf("query issue rows: %v", err) + } + if count != 0 { + t.Fatalf("issue rows after rejected plan = %d, want 0", count) + } +} + +// TestExecuteGraphApplyAcceptsParentToChildPathThroughWaitsFor pins a +// deliberate change. The deleted in-transaction preflight +// (validateGraphApplyPlannedParentBlockingPaths) walked every AffectsReadyWork +// edge, so it refused a planned path from a parent to its own descendant that +// ran through a waits-for hop. The role's end gate walks the scheduling edges +// only (types.IsSchedulingEdge leaves waits-for out on purpose), the same gate +// `bd dep add` and `bd batch apply` go through, so `bd create --graph` now +// stores these plans as those commands do. The blocking twins, the same +// paths with the waits-for hop made a blocks edge, are still refused: +// TestExecuteGraphApplyRejectsReverseParentToChildBlockingEdge and +// TestExecuteGraphApplyRejectsExternalParentTransitiveBlockingPath. +// +// Accepting the shape is not the same as it being safe. Once the spawner has +// an open child, every issue in the shape stays blocked and none is ever +// ready: the parent waits on the spawner's children, and the path from the +// parent down to its own descendant keeps those children blocked for as long +// as the parent is. IsSchedulingEdge's "a waits-for edge cannot close a +// cycle" does not hold here, in either case below. Refusing the shape belongs +// in the shared role, for every front door at once (#7292); this test is the marker +// to flip when that lands. +func TestExecuteGraphApplyAcceptsParentToChildPathThroughWaitsFor(t *testing.T) { + // A waits-for edge's target is its spawner (validateGraphApplyPlan). + waitsFor := func(from, to string) GraphApplyEdge { + return GraphApplyEdge{FromKey: from, ToKey: to, Type: string(types.DepWaitsFor), SpawnerKey: to} + } + tests := []struct { + name string + nodes []GraphApplyNode + edges []GraphApplyEdge + // hop is the node the parent's waits-for edge lands on. + hop string + }{ + { + name: "direct", + nodes: []GraphApplyNode{ + {Key: "parent", Title: "Parent", Type: "epic"}, + {Key: "child", Title: "Child", Type: "task", ParentKey: "parent"}, + }, + edges: []GraphApplyEdge{waitsFor("parent", "child")}, + hop: "child", + }, + { + name: "then a blocking edge", + nodes: []GraphApplyNode{ + {Key: "parent", Title: "Parent", Type: "epic"}, + {Key: "mid", Title: "Middle", Type: "task"}, + {Key: "child", Title: "Child", Type: "task", ParentKey: "parent"}, + }, + edges: []GraphApplyEdge{ + waitsFor("parent", "mid"), + {FromKey: "mid", ToKey: "child", Type: string(types.DepBlocks)}, + }, + hop: "mid", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx, _ := withGraphApplyTestStore(t) + + plan := &GraphApplyPlan{Nodes: tt.nodes, Edges: tt.edges} + if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil { + t.Fatalf("validateGraphApplyPlan: %v", err) + } + result, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err != nil { + t.Fatalf("executeGraphApply: %v", err) + } + + deps, err := store.GetDependenciesWithMetadata(ctx, result.IDs["parent"]) + if err != nil { + t.Fatalf("GetDependenciesWithMetadata(parent): %v", err) + } + if len(deps) != 1 || deps[0].ID != result.IDs[tt.hop] || deps[0].DependencyType != types.DepWaitsFor { + t.Fatalf("parent dependencies = %+v, want one waits-for edge to %s", deps, result.IDs[tt.hop]) + } + }) + } +} + +// TestExecuteGraphApplyFinalGateCatchesCycleHiddenFromPerEdgeChecks restores +// the deleted fake-store +// TestExecuteGraphApplyUnitFinalGateCatchesCycleHiddenFromPerEdgeChecks. That +// test blinded the fake store's per-edge cycle probe; the real request has the +// same switch, SkipPerEdgeCycleCheck, which drops the per-edge probe but never +// the end gate. With it set, the plans TestExecuteGraphApplyRejectsCombinedSchedulingCycle +// and TestExecuteGraphApplyRejectsCycleHiddenInInlineDep send through +// executeGraphApply must still be refused, by the end gate alone. +func TestExecuteGraphApplyFinalGateCatchesCycleHiddenFromPerEdgeChecks(t *testing.T) { + tests := []struct { + name string + plan *GraphApplyPlan + }{ + { + name: "explicit parent-child edge", + plan: &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A", Type: "task"}, + {Key: "b", Title: "B", Type: "task"}, + {Key: "c", Title: "C", Type: "task"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, + {FromKey: "b", ToKey: "c", Type: string(types.DepParentChild)}, + {FromKey: "c", ToKey: "a", Type: string(types.DepConditionalBlocks)}, + }, + }, + }, + { + name: "inline parent-child dependency", + plan: &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A", Type: "task"}, + {Key: "b", Title: "B", Type: "task", Deps: []GraphApplyNodeDep{{Type: string(types.DepParentChild), Target: "c"}}}, + {Key: "c", Title: "C", Type: "task"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, + {FromKey: "c", ToKey: "a", Type: string(types.DepConditionalBlocks)}, + }, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + + req, err := buildGraphApplyBatchRequest(tt.plan, GraphApplyOptions{}, actor, "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + req.SkipPerEdgeCycleCheck = true + applier, err := store.BatchApplier() + if err != nil { + t.Fatalf("BatchApplier: %v", err) + } + _, err = applier.ApplyBatch(ctx, req) + // The end gate's own wording: the per-edge probe would have said + // "adding dependency would create a cycle" against one item. + if err == nil || !strings.Contains(err.Error(), "dependency cycle would be created") { + t.Fatalf("end gate error = %v, want the whole-graph cycle rejection", err) + } + + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues").Scan(&count); err != nil { + t.Fatalf("query issue rows: %v", err) + } + if count != 0 { + t.Fatalf("issue rows after rejected plan = %d, want 0", count) + } + }) + } +} + +// TestExecuteGraphApplyRejectsTransitiveParentChainBlockingCycle restores the +// deleted fake-store TestExecuteGraphApplyUnitRejectsTransitiveParentChainBlockingCycle +// against the real BatchApplier path: a plan-local parent chain (a's parent is +// plan-local b, b's parent is an existing external issue) plus a blocking edge +// from that external grandparent to the local leaf must be rejected even +// though no single parent-child hop is itself local-and-external at once — +// catching it requires walking the hierarchy against the store, which only +// the end gate executeGraphApply reaches can do. +func TestExecuteGraphApplyRejectsTransitiveParentChainBlockingCycle(t *testing.T) { + ctx, _ := withGraphApplyTestStore(t) + + grandparent := &types.Issue{ + ID: "ga-chain-grandparent", + Title: "Existing Grandparent", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeEpic, + } + if err := store.CreateIssue(ctx, grandparent, actor); err != nil { + t.Fatalf("CreateIssue(grandparent): %v", err) + } + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A", Type: "task", ParentKey: "b"}, + {Key: "b", Title: "B", Type: "task", ParentID: grandparent.ID}, + }, + Edges: []GraphApplyEdge{ + {FromID: grandparent.ID, ToKey: "a", Type: "blocks"}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil { + t.Fatal("expected transitive parent-chain blocking cycle to be rejected") + } + // Same end gate and error family as the reverse-edge case above: + // CheckBlockingHierarchyInTx walks the full ancestor chain via a recursive + // CTE, so the external grandparent is still found even though the + // blocking edge itself only names the plan-local leaf. + if got, want := err.Error(), "cannot be blocked by its"; !strings.Contains(got, want) { + t.Fatalf("error = %q, want to contain %q", got, want) + } +} + +// TestExecuteGraphApplyRejectsBlockingThroughExistingBlocking restores the +// deleted fake-store TestExecuteGraphApplyUnitRejectsBlockingThroughExistingBlocking +// against the real BatchApplier path: a planned blocking edge that would close +// a cycle through an EXISTING stored blocking dependency (not anything in the +// plan) must still be rejected, and must not add the new edge. +func TestExecuteGraphApplyRejectsBlockingThroughExistingBlocking(t *testing.T) { + ctx, _ := withGraphApplyTestStore(t) + + for _, id := range []string{"ga-existing-x", "ga-existing-y"} { + if err := store.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, actor); err != nil { + t.Fatalf("CreateIssue(%s): %v", id, err) + } + } + // Existing blocking dep: ga-existing-y blocks ga-existing-x. + if err := store.AddDependency(ctx, &types.Dependency{ + IssueID: "ga-existing-y", + DependsOnID: "ga-existing-x", + Type: types.DepBlocks, + }, actor); err != nil { + t.Fatalf("AddDependency(y -> x): %v", err) + } + + plan := &GraphApplyPlan{ + Edges: []GraphApplyEdge{ + {FromID: "ga-existing-x", ToID: "ga-existing-y", Type: "blocks"}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil { + t.Fatal("expected blocking cycle through existing blocking dep to be rejected") + } + if !strings.Contains(err.Error(), "cycle") { + t.Fatalf("error = %q, want cycle rejection", err.Error()) + } + + deps, err := store.GetDependenciesWithMetadata(ctx, "ga-existing-y") + if err != nil { + t.Fatalf("GetDependenciesWithMetadata(ga-existing-y): %v", err) + } + if len(deps) != 1 { + t.Fatalf("ga-existing-y dependency count = %d, want 1 (only the pre-existing edge)", len(deps)) + } +} + +// TestExecuteGraphApplyRejectsExternalParentTransitiveBlockingPath restores +// the deleted fake-store +// TestExecuteGraphApplyUnitRejectsExternalParentTransitiveBlockingPath: a +// blocking edge from an existing issue to a plan-local middle node, chained +// with a second blocking edge from that middle node to a plan-local +// descendant of the existing issue, composes into a disallowed +// parent-to-descendant block even though no single edge in the plan touches +// the hierarchy directly. +func TestExecuteGraphApplyRejectsExternalParentTransitiveBlockingPath(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + + parent := &types.Issue{ + ID: "ga-transitive-parent", + Title: "Existing Parent", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeEpic, + } + if err := store.CreateIssue(ctx, parent, actor); err != nil { + t.Fatalf("CreateIssue(parent): %v", err) + } + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "mid", Title: "Middle", Type: "task"}, + {Key: "child", Title: "Child", Type: "task", ParentID: parent.ID}, + }, + Edges: []GraphApplyEdge{ + {FromID: parent.ID, ToKey: "mid", Type: "blocks"}, + {FromKey: "mid", ToKey: "child", Type: "blocks"}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil { + t.Fatal("expected external parent transitive blocking path to be rejected") + } + // Confirmed against a real Dolt test server (2026-10 coordinator + // follow-up): see the sibling comment in + // TestExecuteGraphApplyRejectsStoredPrefixParentBlockingPath above for + // why this checks for "cycle" rather than a parent-path phrase. + if got, want := err.Error(), "cycle"; !strings.Contains(got, want) { + t.Fatalf("error = %q, want to contain %q", got, want) + } + + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues WHERE title IN ('Middle', 'Child')").Scan(&count); err != nil { + t.Fatalf("query plan issue rows: %v", err) + } + if count != 0 { + t.Fatalf("plan issue rows after rejected transitive path = %d, want 0", count) + } +} + +// TestExecuteGraphApplyRejectsCombinedSchedulingCycle restores the deleted +// fake-store TestExecuteGraphApplyUnitRejectsCombinedSchedulingCycle: a cycle +// that mixes a blocking edge, an EXPLICIT (not implicit-via-parent_key) +// parent-child edge, and a conditional-blocks edge. The explicit +// parent-child leg is deliberately not a "cycle relevant" type for +// validateGraphApplyLocalCycles's plan-local preflight +// (graphApplyCycleRelevantDependencyType only treats blocks/ +// conditional-blocks as such), so this cycle is invisible to that pure +// check and is caught only by the real apply path's whole-graph gate. +func TestExecuteGraphApplyRejectsCombinedSchedulingCycle(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A", Type: "task"}, + {Key: "b", Title: "B", Type: "task"}, + {Key: "c", Title: "C", Type: "task"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, + {FromKey: "b", ToKey: "c", Type: string(types.DepParentChild)}, + {FromKey: "c", ToKey: "a", Type: string(types.DepConditionalBlocks)}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil || !strings.Contains(err.Error(), "cycle") { + t.Fatalf("combined scheduling cycle error = %v, want rejection", err) + } + + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues WHERE title IN ('A', 'B', 'C')").Scan(&count); err != nil { + t.Fatalf("query issue rows: %v", err) + } + if count != 0 { + t.Fatalf("issue rows after rejected combined scheduling cycle = %d, want 0", count) + } +} + +// TestExecuteGraphApplyRejectsCycleHiddenInInlineDep restores the deleted +// fake-store TestExecuteGraphApplyUnitFinalGateCatchesCycleHiddenFromPerEdgeChecks's +// "inline parent-child dependency" subcase: the cycle-closing parent-child +// hop is a per-node inline Dep (node.Deps), never a top-level plan Edge, so +// it is invisible to validateGraphApplyLocalCycles (which only walks +// plan.Edges) and to any check that only looks at explicit edges. Only the +// real apply path's final whole-graph gate, which sees every dependency the +// batch will write (inline or not), can catch it. +func TestExecuteGraphApplyRejectsCycleHiddenInInlineDep(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A", Type: "task"}, + {Key: "b", Title: "B", Type: "task", Deps: []GraphApplyNodeDep{{Type: string(types.DepParentChild), Target: "c"}}}, + {Key: "c", Title: "C", Type: "task"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, + {FromKey: "c", ToKey: "a", Type: string(types.DepConditionalBlocks)}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil || !strings.Contains(err.Error(), "cycle") { + t.Fatalf("error = %v, want cycle rejection via the inline parent-child dep", err) + } + + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues WHERE title IN ('A', 'B', 'C')").Scan(&count); err != nil { + t.Fatalf("query issue rows: %v", err) + } + if count != 0 { + t.Fatalf("issue rows after rejected plan = %d, want 0", count) + } +} + +// TestExecuteGraphApplyFinalGateIncludesImplicitNodeParent restores the +// deleted fake-store TestExecuteGraphApplyUnitFinalGateIncludesImplicitNodeParent, +// recast as a rejection: the old test introspected the fake store's captured +// cycle-check edge set directly, which has no real-store equivalent, so this +// pins the same claim (the final gate folds in a node's IMPLICIT +// parent-child edge, not only explicit plan edges) by constructing a cycle +// that closes ONLY through that implicit edge — b's parent is an existing +// external issue addressed by ParentID, which validateGraphApplyLocalCycles +// cannot see at all (it only models an implicit parent for a LOCAL, +// plan-key parent) — so a false negative here would mean the final gate +// silently dropped the implicit edge. +func TestExecuteGraphApplyFinalGateIncludesImplicitNodeParent(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + + existingParent := &types.Issue{ + ID: "ga-final-gate-parent", + Title: "Existing Parent", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeEpic, + } + if err := store.CreateIssue(ctx, existingParent, actor); err != nil { + t.Fatalf("CreateIssue(parent): %v", err) + } + + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A", Type: "task"}, + {Key: "b", Title: "B", Type: "task", ParentID: existingParent.ID}, + }, + Edges: []GraphApplyEdge{ + {FromID: existingParent.ID, ToKey: "a", Type: string(types.DepBlocks)}, + {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, + }, + } + + _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) + if err == nil { + t.Fatal("expected cycle closed through b's implicit parent-child edge to be rejected") + } + if !strings.Contains(err.Error(), "cycle") { + t.Fatalf("error = %q, want cycle rejection", err.Error()) + } + + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues WHERE title IN ('A', 'B')").Scan(&count); err != nil { + t.Fatalf("query issue rows: %v", err) + } + if count != 0 { + t.Fatalf("issue rows after rejected plan = %d, want 0", count) + } +} + +// TestExecuteGraphApplyRejectsBlockingThroughPlannedHierarchyRegardlessOfOrder +// restores the deleted fake-store +// TestExecuteGraphApplyUnitRejectsBlockingThroughPlannedHierarchyRegardlessOfOrder: +// a blocking edge onto a planned ancestor must be rejected whether the +// hierarchy is stated as explicit parent-child plan edges or as per-node +// inline Deps, and regardless of which edge the plan lists first — the +// blocking edge deliberately comes before the parent-child edges/deps in +// both subcases, so a check that stops at the first-seen edge rather than +// resolving the whole planned hierarchy would miss it. +func TestExecuteGraphApplyRejectsBlockingThroughPlannedHierarchyRegardlessOfOrder(t *testing.T) { + tests := []struct { + name string + plan *GraphApplyPlan + }{ + { + name: "explicit edges", + plan: &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "grand", Title: "Grand", Type: "task"}, + {Key: "parent", Title: "Parent", Type: "task"}, + {Key: "child", Title: "Child", Type: "task"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "child", ToKey: "grand", Type: "conditional-blocks"}, // Deliberately first. + {FromKey: "child", ToKey: "parent", Type: "parent-child"}, + {FromKey: "parent", ToKey: "grand", Type: "parent-child"}, + }, + }, + }, + { + name: "inline deps", + plan: &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "grand", Title: "Grand", Type: "task"}, + {Key: "parent", Title: "Parent", Type: "task", Deps: []GraphApplyNodeDep{{Type: "parent-child", Target: "grand"}}}, + {Key: "child", Title: "Child", Type: "task", Deps: []GraphApplyNodeDep{ + {Type: "blocks", Target: "grand"}, // Deliberately first. + {Type: "parent-child", Target: "parent"}, + }}, + }, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx, db := withGraphApplyTestStore(t) + _, err := executeGraphApply(ctx, tt.plan, GraphApplyOptions{}) + if err == nil || !strings.Contains(err.Error(), "cannot be blocked by its ancestor") { + t.Fatalf("error = %v, want planned-ancestor rejection", err) + } + var count int + if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM issues").Scan(&count); err != nil { + t.Fatalf("query issue rows: %v", err) + } + if count != 0 { + t.Fatalf("issue rows after rejected plan = %d, want 0", count) + } + }) } } diff --git a/cmd/bd/graph_apply_execution_unit_test.go b/cmd/bd/graph_apply_execution_unit_test.go deleted file mode 100644 index 653978908..000000000 --- a/cmd/bd/graph_apply_execution_unit_test.go +++ /dev/null @@ -1,956 +0,0 @@ -package main - -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/steveyegge/beads/internal/config" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/types" -) - -type graphApplyFakeStore struct { - storage.DoltStorage - issues map[string]*types.Issue - deps []*types.Dependency - addOpts []storage.DependencyAddOptions - cycleEdges [][2]string - nextID int - // Simulates Dolt's split regular/wisp transactions, where a per-edge probe - // may not see an uncommitted path in the other transaction snapshot. - blindPerEdgeCycleChecks bool -} - -func newGraphApplyFakeStore() *graphApplyFakeStore { - return &graphApplyFakeStore{ - issues: make(map[string]*types.Issue), - } -} - -func (s *graphApplyFakeStore) CreateIssue(_ context.Context, issue *types.Issue, _ string) error { - cp := *issue - if cp.ID == "" { - cp.ID = s.nextIssueID(&cp) - } - issue.ID = cp.ID - s.issues[cp.ID] = &cp - return nil -} - -func (s *graphApplyFakeStore) GetIssue(_ context.Context, id string) (*types.Issue, error) { - issue, ok := s.issues[id] - if !ok { - return nil, storage.ErrNotFound - } - cp := *issue - return &cp, nil -} - -func (s *graphApplyFakeStore) GetDependenciesWithMetadata(_ context.Context, issueID string) ([]*types.IssueWithDependencyMetadata, error) { - var out []*types.IssueWithDependencyMetadata - for _, dep := range s.deps { - if dep.IssueID != issueID { - continue - } - issue, ok := s.issues[dep.DependsOnID] - if !ok { - continue - } - cp := *issue - out = append(out, &types.IssueWithDependencyMetadata{ - Issue: cp, - DependencyType: dep.Type, - }) - } - return out, nil -} - -func (s *graphApplyFakeStore) GetDependencyRecords(_ context.Context, issueID string) ([]*types.Dependency, error) { - var out []*types.Dependency - for _, dep := range s.deps { - if dep.IssueID != issueID { - continue - } - cp := *dep - out = append(out, &cp) - } - return out, nil -} - -func (s *graphApplyFakeStore) RunInTransaction(ctx context.Context, _ string, fn func(storage.Transaction) error) error { - txStore := s.clone() - tx := &graphApplyFakeTx{store: txStore} - if err := fn(tx); err != nil { - return err - } - s.issues = txStore.issues - s.deps = txStore.deps - s.addOpts = txStore.addOpts - s.cycleEdges = txStore.cycleEdges - s.nextID = txStore.nextID - return nil -} - -func (s *graphApplyFakeStore) clone() *graphApplyFakeStore { - cp := &graphApplyFakeStore{ - issues: make(map[string]*types.Issue, len(s.issues)), - deps: make([]*types.Dependency, 0, len(s.deps)), - addOpts: append([]storage.DependencyAddOptions(nil), s.addOpts...), - cycleEdges: append([][2]string(nil), s.cycleEdges...), - nextID: s.nextID, - blindPerEdgeCycleChecks: s.blindPerEdgeCycleChecks, - } - for id, issue := range s.issues { - issueCopy := *issue - cp.issues[id] = &issueCopy - } - for _, dep := range s.deps { - depCopy := *dep - cp.deps = append(cp.deps, &depCopy) - } - return cp -} - -func (s *graphApplyFakeStore) nextIssueID(issue *types.Issue) string { - s.nextID++ - if issue.Ephemeral { - return fmt.Sprintf("ga-wisp-%d", s.nextID) - } - return fmt.Sprintf("ga-%d", s.nextID) -} - -type graphApplyFakeTx struct { - storage.Transaction - store *graphApplyFakeStore -} - -func (tx *graphApplyFakeTx) CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error { - for _, issue := range issues { - if err := tx.store.CreateIssue(ctx, issue, actor); err != nil { - return err - } - } - return nil -} - -func (tx *graphApplyFakeTx) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error { - return tx.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{}) -} - -func (tx *graphApplyFakeTx) AddDependencyWithOptions(_ context.Context, dep *types.Dependency, _ string, opts storage.DependencyAddOptions) error { - tx.store.addOpts = append(tx.store.addOpts, opts) - if isGraphApplyFakeBlocking(dep.Type) { - if tx.hasParentPath(dep.IssueID, dep.DependsOnID) { - return fmt.Errorf("%s cannot be blocked by its ancestor %s", dep.IssueID, dep.DependsOnID) - } - if tx.hasParentPath(dep.DependsOnID, dep.IssueID) { - return fmt.Errorf("%s cannot be blocked by its descendant %s", dep.IssueID, dep.DependsOnID) - } - } - for _, existing := range tx.store.deps { - if existing.IssueID == dep.IssueID && existing.DependsOnID == dep.DependsOnID { - if existing.Type == dep.Type { - // Real storage accepts this duplicate and updates metadata; graph - // apply never sets dependency metadata, so the fake treats it as - // idempotent for duplicate-suppression tests. - return nil - } - return fmt.Errorf("dependency already exists with type %s", existing.Type) - } - } - if isGraphApplyFakeScheduling(dep.Type) && !opts.SkipCycleCheck && !tx.store.blindPerEdgeCycleChecks && tx.hasSchedulingPath(dep.DependsOnID, dep.IssueID) { - return fmt.Errorf("adding dependency would create a cycle") - } - depCopy := *dep - tx.store.deps = append(tx.store.deps, &depCopy) - return nil -} - -func (tx *graphApplyFakeTx) CycleThroughEdges(_ context.Context, edges [][2]string) (string, error) { - tx.store.cycleEdges = append([][2]string(nil), edges...) - for _, edge := range edges { - if tx.hasSchedulingPath(edge[1], edge[0]) { - return edge[0] + " → " + edge[1] + " → " + edge[0], nil - } - } - return "", nil -} - -func (tx *graphApplyFakeTx) hasParentPath(fromID, toID string) bool { - seen := make(map[string]bool) - var visit func(string) bool - visit = func(id string) bool { - if id == toID { - return true - } - if seen[id] { - return false - } - seen[id] = true - for _, dep := range tx.store.deps { - if dep.IssueID == id && dep.Type == types.DepParentChild && visit(dep.DependsOnID) { - return true - } - } - return false - } - return visit(fromID) -} - -func isGraphApplyFakeScheduling(t types.DependencyType) bool { - return isGraphApplyFakeBlocking(t) || t == types.DepParentChild -} - -func (tx *graphApplyFakeTx) hasSchedulingPath(fromID, toID string) bool { - seen := make(map[string]bool) - var visit func(string) bool - visit = func(id string) bool { - if id == toID { - return true - } - if seen[id] { - return false - } - seen[id] = true - for _, dep := range tx.store.deps { - if dep.IssueID == id && isGraphApplyFakeScheduling(dep.Type) && visit(dep.DependsOnID) { - return true - } - } - return false - } - return visit(fromID) -} - -func (tx *graphApplyFakeTx) GetDependencyRecords(ctx context.Context, issueID string) ([]*types.Dependency, error) { - return tx.store.GetDependencyRecords(ctx, issueID) -} - -func (tx *graphApplyFakeTx) AddLabel(context.Context, string, string, string) error { - return nil -} - -func (tx *graphApplyFakeTx) UpdateIssue(_ context.Context, id string, updates map[string]interface{}, _ string) error { - issue, ok := tx.store.issues[id] - if !ok { - return storage.ErrNotFound - } - if assignee, ok := updates["assignee"].(string); ok { - issue.Assignee = assignee - } - return nil -} - -func (tx *graphApplyFakeTx) hasBlockingPath(fromID, toID string) bool { - seen := make(map[string]bool) - var visit func(string) bool - visit = func(id string) bool { - if id == toID { - return true - } - if seen[id] { - return false - } - seen[id] = true - for _, dep := range tx.store.deps { - if dep.IssueID != id || !isGraphApplyFakeBlocking(dep.Type) { - continue - } - if visit(dep.DependsOnID) { - return true - } - } - return false - } - return visit(fromID) -} - -func isGraphApplyFakeBlocking(depType types.DependencyType) bool { - return graphApplyCycleRelevantDependencyType(depType) -} - -func withGraphApplyFakeStore(t *testing.T) (context.Context, *graphApplyFakeStore) { - t.Helper() - ctx := context.Background() - fakeStore := newGraphApplyFakeStore() - oldStore, oldCtx, oldActor := store, rootCtx, actor - store, rootCtx, actor = fakeStore, ctx, "graph-apply-test" - t.Cleanup(func() { - store, rootCtx, actor = oldStore, oldCtx, oldActor - }) - return ctx, fakeStore -} - -func TestExecuteGraphApplyUnitRejectsMixedLocalExternalBlockingCycle(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - if err := fakeStore.CreateIssue(ctx, &types.Issue{ - ID: "ga-existing", - Title: "Existing", - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeTask, - }, actor); err != nil { - t.Fatalf("CreateIssue(existing): %v", err) - } - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "a", Title: "A", Type: "task"}, - {Key: "b", Title: "B", Type: "task"}, - }, - Edges: []GraphApplyEdge{ - {FromID: "ga-existing", ToKey: "a", Type: "blocks"}, - {FromKey: "b", ToID: "ga-existing", Type: "blocks"}, - {FromKey: "a", ToKey: "b", Type: "blocks"}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected mixed local/external blocking cycle to be rejected") - } - if !strings.Contains(err.Error(), "cycle") { - t.Fatalf("error = %q, want cycle rejection", err.Error()) - } -} - -func TestExecuteGraphApplyUnitKeepsStorageCycleChecksAfterGraphPreflight(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - if err := fakeStore.CreateIssue(ctx, &types.Issue{ - ID: "ga-existing", - Title: "Existing", - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeTask, - }, actor); err != nil { - t.Fatalf("CreateIssue(existing): %v", err) - } - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "a", Title: "A", Type: "task"}, - {Key: "b", Title: "B", Type: "task"}, - }, - Edges: []GraphApplyEdge{ - {FromID: "ga-existing", ToKey: "a", Type: "blocks"}, - {FromKey: "a", ToKey: "b", Type: "blocks"}, - {FromKey: "b", ToID: "external:other:shipped", Type: "blocks"}, - }, - } - - if _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}); err != nil { - t.Fatalf("executeGraphApply: %v", err) - } - if len(fakeStore.addOpts) != len(plan.Edges) { - t.Fatalf("AddDependencyWithOptions calls = %d, want %d", len(fakeStore.addOpts), len(plan.Edges)) - } - for i, opts := range fakeStore.addOpts { - if opts.SkipCycleCheck { - t.Fatalf("edge %d SkipCycleCheck = true, want false", i) - } - } -} - -// TestExecuteGraphApplyUnitRejectsBlockingThroughExistingParentChild verifies -// that graph apply still reaches the storage hierarchy guard after its -// blocks-only whole-graph cycle preflight. -func TestExecuteGraphApplyUnitRejectsBlockingThroughExistingParentChild(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - for _, id := range []string{"ga-parent", "ga-child"} { - if err := fakeStore.CreateIssue(ctx, &types.Issue{ - ID: id, - Title: id, - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeTask, - }, actor); err != nil { - t.Fatalf("CreateIssue(%s): %v", id, err) - } - } - // Existing parent-child dep: ga-child is a child of ga-parent. - fakeStore.deps = append(fakeStore.deps, &types.Dependency{ - IssueID: "ga-child", - DependsOnID: "ga-parent", - Type: types.DepParentChild, - }) - - plan := &GraphApplyPlan{ - Edges: []GraphApplyEdge{ - {FromID: "ga-parent", ToID: "ga-child", Type: "blocks"}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected blocking edge to own descendant to be rejected") - } - if !strings.Contains(err.Error(), "cannot be blocked by its descendant") { - t.Fatalf("error = %q, want hierarchy rejection", err.Error()) - } -} - -func TestExecuteGraphApplyUnitRejectsBlockingThroughPlannedHierarchyRegardlessOfOrder(t *testing.T) { - tests := []struct { - name string - plan *GraphApplyPlan - }{ - { - name: "explicit edges", - plan: &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "grand", Title: "Grand"}, - {Key: "parent", Title: "Parent"}, - {Key: "child", Title: "Child"}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "child", ToKey: "grand", Type: "conditional-blocks"}, // Deliberately first. - {FromKey: "child", ToKey: "parent", Type: "parent-child"}, - {FromKey: "parent", ToKey: "grand", Type: "parent-child"}, - }, - }, - }, - { - name: "inline deps", - plan: &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "grand", Title: "Grand"}, - {Key: "parent", Title: "Parent", Deps: []GraphApplyNodeDep{{Type: "parent-child", Target: "grand"}}}, - {Key: "child", Title: "Child", Deps: []GraphApplyNodeDep{ - {Type: "blocks", Target: "grand"}, // Deliberately first. - {Type: "parent-child", Target: "parent"}, - }}, - }, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - _, err := executeGraphApply(ctx, tt.plan, GraphApplyOptions{}) - if err == nil || !strings.Contains(err.Error(), "cannot be blocked by its ancestor") { - t.Fatalf("error = %v, want planned-ancestor rejection", err) - } - if len(fakeStore.issues) != 0 || len(fakeStore.deps) != 0 { - t.Fatalf("failed graph transaction leaked writes: issues=%d deps=%d", len(fakeStore.issues), len(fakeStore.deps)) - } - }) - } -} - -// TestExecuteGraphApplyUnitRejectsBlockingThroughExistingBlocking is the -// companion guard: a planned blocking edge that closes a cycle through an -// existing blocking dep must still be rejected by the preflight. -func TestExecuteGraphApplyUnitRejectsBlockingThroughExistingBlocking(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - for _, id := range []string{"ga-x", "ga-y"} { - if err := fakeStore.CreateIssue(ctx, &types.Issue{ - ID: id, - Title: id, - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeTask, - }, actor); err != nil { - t.Fatalf("CreateIssue(%s): %v", id, err) - } - } - // Existing blocking dep: ga-y blocks ga-x. - fakeStore.deps = append(fakeStore.deps, &types.Dependency{ - IssueID: "ga-y", - DependsOnID: "ga-x", - Type: types.DepBlocks, - }) - - plan := &GraphApplyPlan{ - Edges: []GraphApplyEdge{ - {FromID: "ga-x", ToID: "ga-y", Type: "blocks"}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected blocking cycle through existing blocking dep to be rejected") - } - if !strings.Contains(err.Error(), "cycle") { - t.Fatalf("error = %q, want cycle rejection", err.Error()) - } -} - -func TestExecuteGraphApplyUnitRejectsBlockingChildToParentDuplicate(t *testing.T) { - ctx, _ := withGraphApplyFakeStore(t) - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "root", Title: "Root", Type: "epic"}, - {Key: "child", Title: "Child", Type: "task", ParentKey: "root"}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "child", ToKey: "root"}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected default blocking child-to-parent duplicate to be rejected") - } - if !strings.Contains(err.Error(), "parent-child") { - t.Fatalf("error = %q, want parent-child duplicate rejection", err.Error()) - } -} - -func TestExecuteGraphApplyUnitRejectsReverseParentToChildBlockingEdge(t *testing.T) { - tests := []struct { - name string - depType string - externalID bool - }{ - {name: "local blocks", depType: "blocks"}, - {name: "local conditional blocks", depType: "conditional-blocks"}, - {name: "external blocks", depType: "blocks", externalID: true}, - {name: "external conditional blocks", depType: "conditional-blocks", externalID: true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - nodes := []GraphApplyNode{ - {Key: "root", Title: "Root", Type: "epic"}, - {Key: "child", Title: "Child", Type: "task", ParentKey: "root"}, - } - edge := GraphApplyEdge{FromKey: "root", ToKey: "child", Type: tt.depType} - if tt.externalID { - if err := fakeStore.CreateIssue(ctx, &types.Issue{ - ID: "ga-parent", - Title: "Existing Parent", - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeEpic, - }, actor); err != nil { - t.Fatalf("CreateIssue(existing parent): %v", err) - } - nodes = []GraphApplyNode{ - {Key: "child", Title: "Child", Type: "task", ParentID: "ga-parent"}, - } - edge = GraphApplyEdge{FromID: "ga-parent", ToKey: "child", Type: tt.depType} - } - - plan := &GraphApplyPlan{ - Nodes: nodes, - Edges: []GraphApplyEdge{edge}, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected reverse parent-to-child blocking edge to be rejected") - } - if !strings.Contains(err.Error(), "parent-child") { - t.Fatalf("error = %q, want parent-child reverse rejection", err.Error()) - } - }) - } -} - -func TestExecuteGraphApplyUnitRejectsExternalParentTransitiveBlockingPath(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - if err := fakeStore.CreateIssue(ctx, &types.Issue{ - ID: "ga-parent", - Title: "Existing Parent", - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeEpic, - }, actor); err != nil { - t.Fatalf("CreateIssue(existing parent): %v", err) - } - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "mid", Title: "Middle", Type: "task"}, - {Key: "child", Title: "Child", Type: "task", ParentID: "ga-parent"}, - }, - Edges: []GraphApplyEdge{ - {FromID: "ga-parent", ToKey: "mid", Type: "blocks"}, - {FromKey: "mid", ToKey: "child", Type: "blocks"}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected external parent transitive blocking path to be rejected") - } - if got, want := err.Error(), "planned blocking dependencies create a path from parent"; !strings.Contains(got, want) { - t.Fatalf("error = %q, want to contain %q", got, want) - } - if _, ok := fakeStore.issues["ga-1"]; ok { - t.Fatal("transaction committed graph issues after validation failure") - } -} - -func TestExecuteGraphApplyUnitRejectsStoredPrefixParentBlockingPath(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - for _, issue := range []*types.Issue{ - { - ID: "ga-parent", - Title: "Existing Parent", - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeTask, - }, - { - ID: "ga-existing-mid", - Title: "Existing Middle", - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeTask, - }, - } { - if err := fakeStore.CreateIssue(ctx, issue, actor); err != nil { - t.Fatalf("CreateIssue(%s): %v", issue.ID, err) - } - } - fakeStore.deps = append(fakeStore.deps, &types.Dependency{ - IssueID: "ga-parent", - DependsOnID: "ga-existing-mid", - Type: types.DepBlocks, - }) - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "child", Title: "Child", Type: "task", ParentID: "ga-parent"}, - }, - Edges: []GraphApplyEdge{ - {FromID: "ga-existing-mid", ToKey: "child", Type: "blocks"}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected stored-prefix parent blocking path to be rejected") - } - if got, want := err.Error(), "planned blocking dependencies create a path from parent"; !strings.Contains(got, want) { - t.Fatalf("error = %q, want to contain %q", got, want) - } - if _, ok := fakeStore.issues["ga-1"]; ok { - t.Fatal("transaction committed graph issues after validation failure") - } -} - -func TestExecuteGraphApplyUnitRejectsTransitiveParentChainBlockingCycle(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - if err := fakeStore.CreateIssue(ctx, &types.Issue{ - ID: "ga-existing-parent", - Title: "Existing Parent", - Status: types.StatusOpen, - Priority: 2, - IssueType: types.TypeEpic, - }, actor); err != nil { - t.Fatalf("CreateIssue(existing parent): %v", err) - } - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "a", Title: "A", Type: "task", ParentKey: "b"}, - {Key: "b", Title: "B", Type: "task", ParentID: "ga-existing-parent"}, - }, - Edges: []GraphApplyEdge{ - {FromID: "ga-existing-parent", ToKey: "a", Type: "blocks"}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected transitive parent-chain blocking cycle to be rejected") - } - if got, want := err.Error(), "planned blocking dependencies create a path from parent"; !strings.Contains(got, want) { - t.Fatalf("error = %q, want to contain %q", got, want) - } - if _, ok := fakeStore.issues["ga-1"]; ok { - t.Fatal("transaction committed graph issues after validation failure") - } -} - -func TestExecuteGraphApplyUnitRejectsReverseParentChildEdgeCycle(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "root", Title: "Root", Type: "epic"}, - {Key: "child", Title: "Child", Type: "task", ParentKey: "root"}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "root", ToKey: "child", Type: string(types.DepParentChild)}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil { - t.Fatal("expected reverse parent-child edge to be rejected") - } - if got, want := err.Error(), "planned blocking dependencies create a path from parent"; !strings.Contains(got, want) { - t.Fatalf("error = %q, want to contain %q", got, want) - } - if _, ok := fakeStore.issues["ga-1"]; ok { - t.Fatal("transaction committed graph issues after validation failure") - } -} - -func TestExecuteGraphApplyUnitRejectsCombinedSchedulingCycle(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "a", Title: "A", Type: "task"}, - {Key: "b", Title: "B", Type: "task"}, - {Key: "c", Title: "C", Type: "task"}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, - {FromKey: "b", ToKey: "c", Type: string(types.DepParentChild)}, - {FromKey: "c", ToKey: "a", Type: string(types.DepConditionalBlocks)}, - }, - } - - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil || !strings.Contains(err.Error(), "cycle") { - t.Fatalf("combined scheduling cycle error = %v, want rejection", err) - } - if len(fakeStore.issues) != 0 || len(fakeStore.deps) != 0 { - t.Fatalf("transaction committed after combined cycle: issues=%d deps=%d", len(fakeStore.issues), len(fakeStore.deps)) - } -} - -func TestExecuteGraphApplyUnitFinalGateCatchesCycleHiddenFromPerEdgeChecks(t *testing.T) { - plans := map[string]*GraphApplyPlan{ - "explicit parent-child edge": { - Nodes: []GraphApplyNode{ - {Key: "a", Title: "A", Type: "task"}, - {Key: "b", Title: "B", Type: "task"}, - {Key: "c", Title: "C", Type: "task"}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, - {FromKey: "b", ToKey: "c", Type: string(types.DepParentChild)}, - {FromKey: "c", ToKey: "a", Type: string(types.DepConditionalBlocks)}, - }, - }, - "inline parent-child dependency": { - Nodes: []GraphApplyNode{ - {Key: "a", Title: "A", Type: "task"}, - {Key: "b", Title: "B", Type: "task", Deps: []GraphApplyNodeDep{{Type: string(types.DepParentChild), Target: "c"}}}, - {Key: "c", Title: "C", Type: "task"}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}, - {FromKey: "c", ToKey: "a", Type: string(types.DepConditionalBlocks)}, - }, - }, - } - for name, plan := range plans { - t.Run(name, func(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - fakeStore.blindPerEdgeCycleChecks = true - _, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err == nil || !strings.Contains(err.Error(), "graph dependency cycle") { - t.Fatalf("final merged cycle gate error = %v, want rejection", err) - } - if len(fakeStore.issues) != 0 || len(fakeStore.deps) != 0 { - t.Fatalf("transaction committed after final cycle gate: issues=%d deps=%d", len(fakeStore.issues), len(fakeStore.deps)) - } - }) - } -} - -func TestExecuteGraphApplyUnitFinalGateIncludesImplicitNodeParent(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "a", Title: "A", Type: "task"}, - {Key: "b", Title: "B", Type: "task", ParentKey: "c"}, - {Key: "c", Title: "C", Type: "task"}, - }, - Edges: []GraphApplyEdge{{FromKey: "a", ToKey: "b", Type: string(types.DepBlocks)}}, - } - result, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err != nil { - t.Fatalf("executeGraphApply: %v", err) - } - want := map[[2]string]bool{ - {result.IDs["a"], result.IDs["b"]}: true, - {result.IDs["b"], result.IDs["c"]}: true, - } - if len(fakeStore.cycleEdges) != len(want) { - t.Fatalf("final cycle edges = %v, want explicit block plus implicit parent", fakeStore.cycleEdges) - } - for _, edge := range fakeStore.cycleEdges { - if !want[edge] { - t.Fatalf("unexpected final cycle edge %v; want %v", edge, want) - } - } -} - -func TestExecuteGraphApplyUnitAllowsExplicitParentChildDuplicate(t *testing.T) { - ctx, fakeStore := withGraphApplyFakeStore(t) - - plan := &GraphApplyPlan{ - Nodes: []GraphApplyNode{ - {Key: "root", Title: "Root", Type: "epic"}, - {Key: "child", Title: "Child", Type: "task", ParentKey: "root"}, - }, - Edges: []GraphApplyEdge{ - {FromKey: "child", ToKey: "root", Type: string(types.DepParentChild)}, - }, - } - - result, err := executeGraphApply(ctx, plan, GraphApplyOptions{}) - if err != nil { - t.Fatalf("executeGraphApply: %v", err) - } - deps, err := fakeStore.GetDependenciesWithMetadata(ctx, result.IDs["child"]) - if err != nil { - t.Fatalf("GetDependenciesWithMetadata(child): %v", err) - } - if len(deps) != 1 { - t.Fatalf("dependency count = %d, want 1", len(deps)) - } - if deps[0].ID != result.IDs["root"] { - t.Fatalf("dependency target = %s, want %s", deps[0].ID, result.IDs["root"]) - } - if deps[0].DependencyType != types.DepParentChild { - t.Fatalf("dependency type = %s, want %s", deps[0].DependencyType, types.DepParentChild) - } -} - -// An explicit durable storage_class on an effective wisp-plane node must be -// rejected, not silently erased into an effective-ephemeral record -// (Protocol v0.1 §C1.3). versioned is normalized to the unset marker (C2.4) -// only after that conflict check. Cases pin an explicit class so resolution -// never reads the config global and the test stays hermetic; config-default -// interaction is covered by the embedded create tests. -func TestGraphApplyNodeStorageClassConflicts(t *testing.T) { - boolPtr := func(b bool) *bool { return &b } - - tests := []struct { - name string - node GraphApplyNode - opts GraphApplyOptions - wantErr string // substring; "" means no error expected - wantEphem bool - wantClass types.StorageClass - }{ - { - name: "explicit versioned with node ephemeral is rejected", - node: GraphApplyNode{Key: "n1", Type: "task", StorageClass: "versioned", Ephemeral: boolPtr(true)}, - wantErr: "storage_class versioned conflicts with ephemeral/no_history", - }, - { - name: "explicit versioned with node no_history is rejected", - node: GraphApplyNode{Key: "n2", Type: "task", StorageClass: "versioned", NoHistory: boolPtr(true)}, - wantErr: "storage_class versioned conflicts with ephemeral/no_history", - }, - { - name: "explicit unversioned with plan-wide ephemeral is rejected", - node: GraphApplyNode{Key: "n3", Type: "task", StorageClass: "unversioned"}, - opts: GraphApplyOptions{Ephemeral: true}, - wantErr: "storage_class unversioned conflicts with ephemeral/no_history", - }, - { - name: "explicit versioned alone normalizes to unset", - node: GraphApplyNode{Key: "n4", Type: "task", StorageClass: "versioned"}, - wantClass: "", - }, - { - name: "storage_class ephemeral spelling routes to wisp", - node: GraphApplyNode{Key: "n5", Type: "task", StorageClass: "ephemeral"}, - wantEphem: true, - wantClass: "", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ephemeral, _, class, err := graphApplyNodeStorageClass(tt.node, tt.opts) - if tt.wantErr != "" { - if err == nil { - t.Fatalf("expected error containing %q, got nil (ephemeral=%v class=%q)", tt.wantErr, ephemeral, class) - } - if !strings.Contains(err.Error(), tt.wantErr) { - t.Fatalf("error = %q, want substring %q", err.Error(), tt.wantErr) - } - return - } - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ephemeral != tt.wantEphem { - t.Errorf("ephemeral = %v, want %v", ephemeral, tt.wantEphem) - } - if class != tt.wantClass { - t.Errorf("class = %q, want %q", class, tt.wantClass) - } - }) - } -} - -// A per-type config default (storage-class.=unversioned) must yield to an -// effective wisp plane rather than reaching validation and blocking the node -// (flag > config, Protocol v0.1 §C1.3). Unlike the hermetic conflict cases -// above, these leave node.StorageClass unset so resolution reads the config -// global, so the subtests share one process-wide config and cannot run in -// parallel. The precondition assert guards against a silent pass if config -// never initialized (Set is a no-op on an uninitialized viper). -func TestGraphApplyNodeStorageClassConfigDefaultYieldsToWispPlane(t *testing.T) { - config.ResetForTesting() - t.Cleanup(config.ResetForTesting) - if err := config.Initialize(); err != nil { - t.Fatalf("config.Initialize: %v", err) - } - config.Set("storage-class.task", "unversioned") - if got := config.GetString("storage-class.task"); got != "unversioned" { - t.Fatalf("precondition: storage-class.task = %q, want unversioned", got) - } - - boolPtr := func(b bool) *bool { return &b } - - tests := []struct { - name string - node GraphApplyNode - opts GraphApplyOptions - wantEphem bool - wantNoHis bool - }{ - { - name: "plan-wide ephemeral clears config-derived unversioned", - node: GraphApplyNode{Key: "n1", Type: "task"}, - opts: GraphApplyOptions{Ephemeral: true}, - wantEphem: true, - }, - { - name: "node-level ephemeral clears config-derived unversioned", - node: GraphApplyNode{Key: "n2", Type: "task", Ephemeral: boolPtr(true)}, - wantEphem: true, - }, - { - name: "plan-wide no_history clears config-derived unversioned", - node: GraphApplyNode{Key: "n3", Type: "task"}, - opts: GraphApplyOptions{NoHistory: true}, - wantNoHis: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ephemeral, noHistory, class, err := graphApplyNodeStorageClass(tt.node, tt.opts) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if class != "" { - t.Errorf("class = %q, want empty (config default yields to wisp plane)", class) - } - if ephemeral != tt.wantEphem { - t.Errorf("ephemeral = %v, want %v", ephemeral, tt.wantEphem) - } - if noHistory != tt.wantNoHis { - t.Errorf("noHistory = %v, want %v", noHistory, tt.wantNoHis) - } - }) - } -} diff --git a/cmd/bd/graph_apply_test.go b/cmd/bd/graph_apply_test.go index 7a848d05a..1d8ded671 100644 --- a/cmd/bd/graph_apply_test.go +++ b/cmd/bd/graph_apply_test.go @@ -3,6 +3,7 @@ package main import ( "bytes" "encoding/json" + "errors" "fmt" "os" "reflect" @@ -10,7 +11,9 @@ import ( "strings" "testing" + "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" ) // TestDocsGraphPlanExampleValidates pins the --graph doc supplement's example @@ -526,35 +529,6 @@ func TestGraphApplyEdgeIsLocalCycleRelevantOnlyForLocalBlockingEdges(t *testing. } } -func TestGraphApplyParentDepPairs(t *testing.T) { - nodes := []GraphApplyNode{ - {Key: "root", Title: "Root"}, - {Key: "child", Title: "Child", ParentKey: "root"}, - {Key: "external-child", Title: "External child", ParentID: "bd-parent"}, - } - keyToID := map[string]string{ - "root": "bd-root", - "child": "bd-child", - "external-child": "bd-external-child", - } - - pairs := graphApplyParentDepPairs(nodes, keyToID) - for _, pair := range []struct { - child string - parent string - }{ - {"bd-child", "bd-root"}, - {"bd-external-child", "bd-parent"}, - } { - if !pairs[graphApplyDepPairKey(pair.child, pair.parent)] { - t.Fatalf("missing parent dep pair %s -> %s", pair.child, pair.parent) - } - } - if pairs[graphApplyDepPairKey("bd-root", "bd-child")] { - t.Fatal("unexpected reverse parent dep pair") - } -} - // TestEmitGraphApplyDryRun_JSON verifies that the dry-run path emits valid // JSON with the expected structure when jsonOutput is set. This exercises the // code path that `bd create --graph --dry-run --json` takes, confirming the @@ -1007,3 +981,638 @@ func TestGraphApplyNodeCoversCreateIssueParams(t *testing.T) { } } } + +// An explicit durable storage_class on an effective wisp-plane node must be +// rejected, not silently erased into an effective-ephemeral record +// (Protocol v0.1 §C1.3). versioned is normalized to the unset marker (C2.4) +// only after that conflict check. Cases pin an explicit class so resolution +// never reads the config global and the test stays hermetic; config-default +// interaction is covered by the embedded create tests. +func TestGraphApplyNodeStorageClassConflicts(t *testing.T) { + boolPtr := func(b bool) *bool { return &b } + + tests := []struct { + name string + node GraphApplyNode + opts GraphApplyOptions + wantErr string // substring; "" means no error expected + wantEphem bool + wantClass types.StorageClass + }{ + { + name: "explicit versioned with node ephemeral is rejected", + node: GraphApplyNode{Key: "n1", Type: "task", StorageClass: "versioned", Ephemeral: boolPtr(true)}, + wantErr: "storage_class versioned conflicts with ephemeral/no_history", + }, + { + name: "explicit versioned with node no_history is rejected", + node: GraphApplyNode{Key: "n2", Type: "task", StorageClass: "versioned", NoHistory: boolPtr(true)}, + wantErr: "storage_class versioned conflicts with ephemeral/no_history", + }, + { + name: "explicit unversioned with plan-wide ephemeral is rejected", + node: GraphApplyNode{Key: "n3", Type: "task", StorageClass: "unversioned"}, + opts: GraphApplyOptions{Ephemeral: true}, + wantErr: "storage_class unversioned conflicts with ephemeral/no_history", + }, + { + name: "explicit versioned alone normalizes to unset", + node: GraphApplyNode{Key: "n4", Type: "task", StorageClass: "versioned"}, + wantClass: "", + }, + { + name: "storage_class ephemeral spelling routes to wisp", + node: GraphApplyNode{Key: "n5", Type: "task", StorageClass: "ephemeral"}, + wantEphem: true, + wantClass: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ephemeral, _, class, err := graphApplyNodeStorageClass(tt.node, tt.opts) + if tt.wantErr != "" { + if err == nil { + t.Fatalf("expected error containing %q, got nil (ephemeral=%v class=%q)", tt.wantErr, ephemeral, class) + } + if !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("error = %q, want substring %q", err.Error(), tt.wantErr) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if ephemeral != tt.wantEphem { + t.Errorf("ephemeral = %v, want %v", ephemeral, tt.wantEphem) + } + if class != tt.wantClass { + t.Errorf("class = %q, want %q", class, tt.wantClass) + } + }) + } +} + +// A per-type config default (storage-class.=unversioned) must yield to an +// effective wisp plane rather than reaching validation and blocking the node +// (flag > config, Protocol v0.1 §C1.3). Unlike the hermetic conflict cases +// above, these leave node.StorageClass unset so resolution reads the config +// global, so the subtests share one process-wide config and cannot run in +// parallel. The precondition assert guards against a silent pass if config +// never initialized (Set is a no-op on an uninitialized viper). +func TestGraphApplyNodeStorageClassConfigDefaultYieldsToWispPlane(t *testing.T) { + config.ResetForTesting() + t.Cleanup(config.ResetForTesting) + if err := config.Initialize(); err != nil { + t.Fatalf("config.Initialize: %v", err) + } + config.Set("storage-class.task", "unversioned") + if got := config.GetString("storage-class.task"); got != "unversioned" { + t.Fatalf("precondition: storage-class.task = %q, want unversioned", got) + } + + boolPtr := func(b bool) *bool { return &b } + + tests := []struct { + name string + node GraphApplyNode + opts GraphApplyOptions + wantEphem bool + wantNoHis bool + }{ + { + name: "plan-wide ephemeral clears config-derived unversioned", + node: GraphApplyNode{Key: "n1", Type: "task"}, + opts: GraphApplyOptions{Ephemeral: true}, + wantEphem: true, + }, + { + name: "node-level ephemeral clears config-derived unversioned", + node: GraphApplyNode{Key: "n2", Type: "task", Ephemeral: boolPtr(true)}, + wantEphem: true, + }, + { + name: "plan-wide no_history clears config-derived unversioned", + node: GraphApplyNode{Key: "n3", Type: "task"}, + opts: GraphApplyOptions{NoHistory: true}, + wantNoHis: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ephemeral, noHistory, class, err := graphApplyNodeStorageClass(tt.node, tt.opts) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if class != "" { + t.Errorf("class = %q, want empty (config default yields to wisp plane)", class) + } + if ephemeral != tt.wantEphem { + t.Errorf("ephemeral = %v, want %v", ephemeral, tt.wantEphem) + } + if noHistory != tt.wantNoHis { + t.Errorf("noHistory = %v, want %v", noHistory, tt.wantNoHis) + } + }) + } +} + +// TestBuildGraphApplyBatchRequestItemOrderAndRefs pins the translation +// buildGraphApplyBatchRequest performs for both the embedded and proxied +// `bd create --graph` legs: every create lands first (plan order), then +// parent-child dep_adds, then explicit edges, then inline node deps, then +// trailing assign_after_create updates — so every Ref below resolves +// backward regardless of the plan's own declaration order. +func TestBuildGraphApplyBatchRequestItemOrderAndRefs(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "root", Title: "Root", Type: "epic"}, + {Key: "child", Title: "Child", ParentKey: "root", Deps: []GraphApplyNodeDep{{Target: "root", Type: "blocks"}}}, + {Key: "deferred", Title: "Deferred assignee", Assignee: "worker", AssignAfterCreate: true}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "child", ToKey: "deferred", Type: "related-to"}, + }, + } + + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "owner@example.com") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + + var gotKinds []issueops.ItemKind + for _, item := range req.Items { + gotKinds = append(gotKinds, item.Kind) + } + wantKinds := []issueops.ItemKind{ + issueops.ItemCreate, issueops.ItemCreate, issueops.ItemCreate, // root, child, deferred + issueops.ItemDepAdd, // child -> root (parent-child) + issueops.ItemDepAdd, // child -> deferred (explicit edge) + issueops.ItemDepAdd, // child -> root (inline dep) + issueops.ItemUpdate, // deferred's assign_after_create + } + if len(gotKinds) != len(wantKinds) { + t.Fatalf("item kinds = %v, want %v", gotKinds, wantKinds) + } + for i := range wantKinds { + if gotKinds[i] != wantKinds[i] { + t.Errorf("item %d kind = %q, want %q", i, gotKinds[i], wantKinds[i]) + } + } + + parentDep := req.Items[3].DepAdd + if parentDep.Source != (issueops.Ref{Key: "child"}) || parentDep.Target != (issueops.Ref{Key: "root"}) || parentDep.Type != types.DepParentChild { + t.Errorf("parent-child dep_add = %+v", parentDep) + } + explicitEdge := req.Items[4].DepAdd + if explicitEdge.Source != (issueops.Ref{Key: "child"}) || explicitEdge.Target != (issueops.Ref{Key: "deferred"}) || explicitEdge.Type != types.DependencyType("related-to") { + t.Errorf("explicit edge dep_add = %+v", explicitEdge) + } + inlineDep := req.Items[5].DepAdd + if inlineDep.Source != (issueops.Ref{Key: "child"}) || inlineDep.Target != (issueops.Ref{Key: "root"}) || inlineDep.Type != types.DepBlocks { + t.Errorf("inline dep_add = %+v", inlineDep) + } + update := req.Items[6].Update + if update.Target != (issueops.Ref{Key: "deferred"}) || !update.Patch.Assignee.Set || update.Patch.Assignee.Value != "worker" { + t.Errorf("deferred assignee update = %+v", update) + } + + if req.Actor != "actor" || req.Provenance == "" { + t.Errorf("request actor/provenance = %q/%q", req.Actor, req.Provenance) + } +} + +// TestBuildGraphApplyBatchRequestEdgeRefPrefersExplicitID pins resolveEdgeRef's +// old precedence, now inlined as the `ref` closure: an edge endpoint carrying +// both a plan key and an explicit id resolves to the id. +func TestBuildGraphApplyBatchRequestEdgeRefPrefersExplicitID(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A"}, + {Key: "b", Title: "B"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "a", ToKey: "b", ToID: "bd-existing", Type: "blocks"}, + }, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + var edge *issueops.DepAddItem + for _, item := range req.Items { + if item.Kind == issueops.ItemDepAdd { + edge = item.DepAdd + } + } + if edge == nil { + t.Fatal("no dep_add item found") + } + if edge.Target != (issueops.Ref{ID: "bd-existing"}) { + t.Errorf("edge target = %+v, want explicit id to win over to_key", edge.Target) + } +} + +// TestBuildGraphApplyBatchRequestParentKeyWinsOverParentID pins the opposite +// precedence for a node's parent: a node naming both a plan-local parent +// (parent_key, or its parent alias) and a parent_id is parented under the +// plan key, as both legs did before the BatchApplier translation, and as the +// dry-run preview and the local cycle check already assume. +func TestBuildGraphApplyBatchRequestParentKeyWinsOverParentID(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "root", Title: "Root", Type: "epic"}, + {Key: "keyed", Title: "Keyed", ParentKey: "root", ParentID: "bd-existing"}, + {Key: "aliased", Title: "Aliased", Parent: "root", ParentID: "bd-existing"}, + {Key: "external", Title: "External", ParentID: "bd-existing"}, + }, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + got := map[string]issueops.Ref{} + for _, item := range req.Items { + if item.Kind == issueops.ItemDepAdd && item.DepAdd.Type == types.DepParentChild { + got[item.DepAdd.Source.Key] = item.DepAdd.Target + } + } + want := map[string]issueops.Ref{ + "keyed": {Key: "root"}, + "aliased": {Key: "root"}, + "external": {ID: "bd-existing"}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("parent-child targets = %+v, want %+v", got, want) + } +} + +// TestBuildGraphApplyBatchRequestWaitsForGateMetadataCarriesGateOnly pins that +// this translation only ever writes the gate into a waits-for edge's +// Metadata: SpawnerKey/SpawnerID are validated elsewhere to equal the edge's +// own target, and issueops.StampWaitsForSpawnerID (the role's own end, not +// this translation) is what fills metadata.spawner_id once the batch mints +// every id — see graphApplyEdgeBatchMetadata's doc. +func TestBuildGraphApplyBatchRequestWaitsForGateMetadataCarriesGateOnly(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "gate", Title: "Gate"}, + {Key: "spawner", Title: "Spawner"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "gate", ToKey: "spawner", Type: "waits-for", Gate: "any-children", SpawnerKey: "spawner"}, + }, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + var edge *issueops.DepAddItem + for _, item := range req.Items { + if item.Kind == issueops.ItemDepAdd { + edge = item.DepAdd + } + } + if edge == nil { + t.Fatal("no dep_add item found") + } + var meta types.WaitsForMeta + if err := json.Unmarshal([]byte(edge.Metadata), &meta); err != nil { + t.Fatalf("edge.Metadata = %q not valid WaitsForMeta JSON: %v", edge.Metadata, err) + } + if meta.Gate != types.WaitsForAnyChildren { + t.Errorf("meta.Gate = %q, want any-children", meta.Gate) + } + if meta.SpawnerID != "" { + t.Errorf("meta.SpawnerID = %q, want empty: the role stamps it after ids are minted", meta.SpawnerID) + } + if !edge.HasSpawner { + t.Errorf("edge.HasSpawner = false, want true: the edge named spawner_key %q", "spawner") + } +} + +// TestBuildGraphApplyBatchRequestWaitsForNoSpawnerLeavesHasSpawnerFalse pins +// the 2026-10 Opus-review HIGH-2 fix's other half: a waits-for edge that names +// NO spawner_key/spawner_id must translate to HasSpawner false, so the role +// (StampWaitsForSpawnerID's caller in both BatchApplier legs) leaves its +// stored metadata gate-only rather than stamping in a spawner_id the plan +// never asked for. +func TestBuildGraphApplyBatchRequestWaitsForNoSpawnerLeavesHasSpawnerFalse(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "gate", Title: "Gate"}, + {Key: "spawner", Title: "Spawner"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "gate", ToKey: "spawner", Type: "waits-for"}, + }, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + var edge *issueops.DepAddItem + for _, item := range req.Items { + if item.Kind == issueops.ItemDepAdd { + edge = item.DepAdd + } + } + if edge == nil { + t.Fatal("no dep_add item found") + } + if edge.HasSpawner { + t.Errorf("edge.HasSpawner = true, want false: the edge named no spawner_key/spawner_id") + } +} + +// TestBuildGraphApplyBatchRequestCarriesEdgeThreadID pins that edges[].thread_id +// — previously rejected outright because issueops.DepAddItem had no member to +// carry it (the 2026-10 Opus-review HIGH-1 finding) — now reaches the dep_add +// item's own ThreadID field unchanged, so both BatchApplier legs can stamp it +// onto the stored dependency row (see TestGraphApplyThreadIDGoldenParity for +// the stored-row assertion). +func TestBuildGraphApplyBatchRequestCarriesEdgeThreadID(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A"}, + {Key: "b", Title: "B"}, + }, + Edges: []GraphApplyEdge{ + {FromKey: "a", ToKey: "b", Type: "replies-to", ThreadID: "thread-1"}, + }, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + var edge *issueops.DepAddItem + for _, item := range req.Items { + if item.Kind == issueops.ItemDepAdd { + edge = item.DepAdd + } + } + if edge == nil { + t.Fatal("no dep_add item found") + } + if edge.ThreadID != "thread-1" { + t.Errorf("edge.ThreadID = %q, want %q", edge.ThreadID, "thread-1") + } +} + +// TestBuildGraphApplyBatchRequestCapBoundary pins the exact boundary of the +// "atomic, never chunked" refusal: a plan whose translated item count sits at +// issueops.MaxApplyBatchItems is accepted, and one item over is refused with +// *GraphApplyTooLargeError rather than being split across more than one +// transaction. +func TestBuildGraphApplyBatchRequestCapBoundary(t *testing.T) { + buildPlanWithNodeCount := func(n int) *GraphApplyPlan { + nodes := make([]GraphApplyNode, n) + for i := range nodes { + nodes[i] = GraphApplyNode{Key: fmt.Sprintf("n%d", i), Title: "N"} + } + return &GraphApplyPlan{Nodes: nodes} + } + + t.Run("exactly the cap succeeds", func(t *testing.T) { + plan := buildPlanWithNodeCount(issueops.MaxApplyBatchItems) + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest at the cap: %v", err) + } + if len(req.Items) != issueops.MaxApplyBatchItems { + t.Fatalf("item count = %d, want %d", len(req.Items), issueops.MaxApplyBatchItems) + } + }) + + t.Run("one over the cap is refused", func(t *testing.T) { + plan := buildPlanWithNodeCount(issueops.MaxApplyBatchItems + 1) + _, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + var tooLarge *GraphApplyTooLargeError + if !errors.As(err, &tooLarge) { + t.Fatalf("err = %v, want *GraphApplyTooLargeError", err) + } + if tooLarge.ItemCount != issueops.MaxApplyBatchItems+1 || tooLarge.Max != issueops.MaxApplyBatchItems { + t.Errorf("tooLarge = %+v, want ItemCount=%d Max=%d", tooLarge, issueops.MaxApplyBatchItems+1, issueops.MaxApplyBatchItems) + } + }) +} + +// wantCoveredGraphApplyEdgeFields and wantCoveredGraphApplyNodeDepFields are +// the field-name allowlists TestBuildGraphApplyBatchRequestFieldsSurvive +// checks every GraphApplyEdge/GraphApplyNodeDep field against. A field +// missing from its allowlist fails the test immediately: this is the guard +// against a future field silently riding through buildGraphApplyBatchRequest +// untested, which is exactly how edges[].thread_id (2026-10 Opus-review +// HIGH-1) and the spawner_key/spawner_id -> HasSpawner translation (HIGH-2) +// went unverified before. Adding a field to either struct means adding it +// here AND adding a subtest below that proves it reaches (or is deliberately +// dropped from) the built issueops.ApplyBatchRequest. +var wantCoveredGraphApplyEdgeFields = map[string]bool{ + "FromKey": true, "FromID": true, "ToKey": true, "ToID": true, + "Type": true, "Gate": true, "SpawnerKey": true, "SpawnerID": true, + "ThreadID": true, +} + +var wantCoveredGraphApplyNodeDepFields = map[string]bool{ + "Type": true, "Target": true, +} + +// TestBuildGraphApplyBatchRequestFieldsSurvive is the field-check test the +// coordinator's 2026-10 re-review asked for: it fails if any graph-plan edge +// or inline-dep field — including thread_id, the spawner fields and gate +// metadata — is dropped when buildGraphApplyBatchRequest translates a plan +// into issueops.DepAddItem entries for the BatchApplier request. +// +// This cannot be the old (now-deleted) TestBuildDomainGraphPlanCoversEdgeFields +// reflection trick of copying every source field onto a same-named destination +// field: GraphApplyEdge and issueops.DepAddItem do not share field names. +// FromKey/FromID collapse into one Source Ref, ToKey/ToID into one Target Ref, +// Gate is JSON-encoded into Metadata only for waits-for edges, and +// SpawnerKey/SpawnerID collapse into the derived HasSpawner bool. So instead +// this enumerates GraphApplyEdge/GraphApplyNodeDep's fields by reflection and +// requires each one to be claimed in wantCoveredGraphApplyEdgeFields / +// wantCoveredGraphApplyNodeDepFields above (an unclaimed field fails outright, +// forcing a conscious update here), then independently proves each claimed +// field actually reaches the built request. +func TestBuildGraphApplyBatchRequestFieldsSurvive(t *testing.T) { + assertAllFieldsClaimed := func(t *testing.T, typ reflect.Type, claimed map[string]bool) { + t.Helper() + for i := 0; i < typ.NumField(); i++ { + name := typ.Field(i).Name + if !claimed[name] { + t.Errorf("%s.%s has no coverage claim in this test; add it to the allowlist and prove it survives buildGraphApplyBatchRequest", typ.Name(), name) + } + } + for name := range claimed { + if _, ok := typ.FieldByName(name); !ok { + t.Errorf("allowlist claims %s.%s but no such field exists; stale entry", typ.Name(), name) + } + } + } + assertAllFieldsClaimed(t, reflect.TypeOf(GraphApplyEdge{}), wantCoveredGraphApplyEdgeFields) + assertAllFieldsClaimed(t, reflect.TypeOf(GraphApplyNodeDep{}), wantCoveredGraphApplyNodeDepFields) + + // lastDepAdd returns the last dep_add item's payload, matching the + // pattern every sibling test in this file already uses to pick out the + // one edge a single-edge plan produces. + lastDepAdd := func(t *testing.T, req issueops.ApplyBatchRequest) *issueops.DepAddItem { + t.Helper() + var got *issueops.DepAddItem + for _, item := range req.Items { + if item.Kind == issueops.ItemDepAdd { + got = item.DepAdd + } + } + if got == nil { + t.Fatal("no dep_add item found in built request") + } + return got + } + + t.Run("FromKey and ToKey resolve to plan-key refs", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "a", Title: "A"}, {Key: "b", Title: "B"}}, + Edges: []GraphApplyEdge{{FromKey: "a", ToKey: "b", Type: "related-to"}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + edge := lastDepAdd(t, req) + if edge.Source != (issueops.Ref{Key: "a"}) { + t.Errorf("Source = %+v, want key ref a (FromKey dropped?)", edge.Source) + } + if edge.Target != (issueops.Ref{Key: "b"}) { + t.Errorf("Target = %+v, want key ref b (ToKey dropped?)", edge.Target) + } + }) + + t.Run("FromID and ToID resolve to id refs", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "placeholder", Title: "unused except to keep the plan non-empty"}}, + Edges: []GraphApplyEdge{{FromID: "bd-from-1", ToID: "bd-to-1", Type: "blocks"}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + edge := lastDepAdd(t, req) + if edge.Source != (issueops.Ref{ID: "bd-from-1"}) { + t.Errorf("Source = %+v, want id ref bd-from-1 (FromID dropped?)", edge.Source) + } + if edge.Target != (issueops.Ref{ID: "bd-to-1"}) { + t.Errorf("Target = %+v, want id ref bd-to-1 (ToID dropped?)", edge.Target) + } + }) + + t.Run("Type carries through to DepAddItem.Type", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "a", Title: "A"}, {Key: "b", Title: "B"}}, + Edges: []GraphApplyEdge{{FromKey: "a", ToKey: "b", Type: "custom-edge-type"}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + edge := lastDepAdd(t, req) + if edge.Type != types.DependencyType("custom-edge-type") { + t.Errorf("Type = %q, want %q (Type dropped?)", edge.Type, "custom-edge-type") + } + }) + + t.Run("Gate is JSON-encoded into Metadata for a waits-for edge", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "gate", Title: "Gate"}, {Key: "spawner", Title: "Spawner"}}, + Edges: []GraphApplyEdge{{FromKey: "gate", ToKey: "spawner", Type: string(types.DepWaitsFor), Gate: string(types.WaitsForAnyChildren), SpawnerKey: "spawner"}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + edge := lastDepAdd(t, req) + var meta types.WaitsForMeta + if err := json.Unmarshal([]byte(edge.Metadata), &meta); err != nil { + t.Fatalf("Metadata = %q not valid WaitsForMeta JSON: %v (Gate dropped?)", edge.Metadata, err) + } + if meta.Gate != types.WaitsForAnyChildren { + t.Errorf("meta.Gate = %q, want %q (Gate dropped?)", meta.Gate, types.WaitsForAnyChildren) + } + }) + + t.Run("SpawnerKey sets HasSpawner true", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "gate", Title: "Gate"}, {Key: "spawner", Title: "Spawner"}}, + Edges: []GraphApplyEdge{{FromKey: "gate", ToKey: "spawner", Type: string(types.DepWaitsFor), SpawnerKey: "spawner"}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + if edge := lastDepAdd(t, req); !edge.HasSpawner { + t.Error("HasSpawner = false, want true (SpawnerKey dropped?)") + } + }) + + t.Run("SpawnerID sets HasSpawner true", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "gate", Title: "Gate"}}, + Edges: []GraphApplyEdge{{FromKey: "gate", ToID: "bd-spawner-1", Type: string(types.DepWaitsFor), SpawnerID: "bd-spawner-1"}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + if edge := lastDepAdd(t, req); !edge.HasSpawner { + t.Error("HasSpawner = false, want true (SpawnerID dropped?)") + } + }) + + t.Run("no spawner field leaves HasSpawner false", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "gate", Title: "Gate"}, {Key: "spawner", Title: "Spawner"}}, + Edges: []GraphApplyEdge{{FromKey: "gate", ToKey: "spawner", Type: string(types.DepWaitsFor)}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + if edge := lastDepAdd(t, req); edge.HasSpawner { + t.Error("HasSpawner = true, want false: edge named no spawner_key/spawner_id") + } + }) + + t.Run("ThreadID carries through unchanged", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{{Key: "a", Title: "A"}, {Key: "b", Title: "B"}}, + Edges: []GraphApplyEdge{{FromKey: "a", ToKey: "b", Type: "replies-to", ThreadID: "thread-field-check"}}, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + if edge := lastDepAdd(t, req); edge.ThreadID != "thread-field-check" { + t.Errorf("ThreadID = %q, want %q (ThreadID dropped?)", edge.ThreadID, "thread-field-check") + } + }) + + t.Run("inline dep Type and Target carry through", func(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "parent", Title: "Parent"}, + {Key: "child", Title: "Child", Deps: []GraphApplyNodeDep{{Type: "field-check-dep-type", Target: "parent"}}}, + }, + } + req, err := buildGraphApplyBatchRequest(plan, GraphApplyOptions{}, "actor", "") + if err != nil { + t.Fatalf("buildGraphApplyBatchRequest: %v", err) + } + edge := lastDepAdd(t, req) + if edge.Source != (issueops.Ref{Key: "child"}) || edge.Target != (issueops.Ref{Key: "parent"}) { + t.Errorf("Source/Target = %+v/%+v, want child/parent key refs (Target dropped?)", edge.Source, edge.Target) + } + if edge.Type != types.DependencyType("field-check-dep-type") { + t.Errorf("Type = %q, want %q (inline dep Type dropped?)", edge.Type, "field-check-dep-type") + } + }) +} diff --git a/cmd/bd/graph_apply_thread_spawner_embedded_test.go b/cmd/bd/graph_apply_thread_spawner_embedded_test.go new file mode 100644 index 000000000..28212536d --- /dev/null +++ b/cmd/bd/graph_apply_thread_spawner_embedded_test.go @@ -0,0 +1,115 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/steveyegge/beads/internal/storage/embeddeddolt" +) + +// edgeRow is the raw persisted shape of a dependencies row that this test +// cares about: the JSON metadata blob and the thread_id column. +type edgeRow struct { + metadata string + threadID string +} + +// queryEdgeRow reads the metadata/thread_id columns for a single dependency +// edge directly via SQL, bypassing any CLI-level projection, so this test is +// a true golden parity check of what --graph actually persisted. +func queryEdgeRow(t *testing.T, beadsDir, database, issueID, dependsOnID string) edgeRow { + t.Helper() + dataDir := filepath.Join(beadsDir, "embeddeddolt") + db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main") + if err != nil { + t.Fatalf("OpenSQL: %v", err) + } + defer cleanup() + var row edgeRow + err = db.QueryRowContext(t.Context(), + "SELECT COALESCE(metadata,''), COALESCE(thread_id,'') FROM dependencies "+ + "WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?", + issueID, dependsOnID).Scan(&row.metadata, &row.threadID) + if err != nil { + t.Fatalf("query edge row %s -> %s: %v", issueID, dependsOnID, err) + } + return row +} + +// TestGraphApplyThreadIDAndSpawnerStampGoldenParity is the golden +// input->stored-row parity test required by the S11 review fix-up for HIGH-1 +// (edges[].thread_id was being rejected, but was previously stored and must +// round-trip) and HIGH-2 (edges[].spawner_key/spawner_id must stamp +// metadata.spawner_id only when the plan actually named a spawner; an +// unnamed waits-for edge must keep gate-only metadata, matching the +// pre-BatchApplier types.NewGraphEdgeDependency behavior). +func TestGraphApplyThreadIDAndSpawnerStampGoldenParity(t *testing.T) { + bd := buildEmbeddedBD(t) + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "gp") + + plan := `{ + "nodes": [ + {"key": "a", "title": "A"}, + {"key": "b", "title": "B"}, + {"key": "s", "title": "Spawner"}, + {"key": "w", "title": "Waiter"}, + {"key": "s2", "title": "Spawner2"}, + {"key": "w2", "title": "Waiter2"} + ], + "edges": [ + {"from_key": "a", "to_key": "b", "type": "replies-to", "thread_id": "th-1"}, + {"from_key": "w", "to_key": "s", "type": "waits-for", "gate": "any-children", "spawner_key": "s"}, + {"from_key": "w2", "to_key": "s2", "type": "waits-for"} + ] + }` + planFile := filepath.Join(dir, "golden-plan.json") + if err := os.WriteFile(planFile, []byte(plan), 0o600); err != nil { + t.Fatalf("write plan: %v", err) + } + result := bdCreateGraph(t, bd, dir, planFile) + + aID, bID := result.IDs["a"], result.IDs["b"] + sID, wID := result.IDs["s"], result.IDs["w"] + s2ID, w2ID := result.IDs["s2"], result.IDs["w2"] + for key, id := range map[string]string{"a": aID, "b": bID, "s": sID, "w": wID, "s2": s2ID, "w2": w2ID} { + if id == "" { + t.Fatalf("missing resolved id for key %q in %+v", key, result.IDs) + } + } + + // HIGH-1: thread_id must round-trip from plan input to stored row. + threadRow := queryEdgeRow(t, beadsDir, "gp", aID, bID) + if threadRow.threadID != "th-1" { + t.Errorf("replies-to thread_id = %q, want %q", threadRow.threadID, "th-1") + } + + // HIGH-2 positive: a waits-for edge with a named spawner_key must stamp + // metadata.spawner_id to the resolved spawner issue ID. + spawnRow := queryEdgeRow(t, beadsDir, "gp", wID, sID) + var spawnMeta map[string]any + if err := json.Unmarshal([]byte(spawnRow.metadata), &spawnMeta); err != nil { + t.Fatalf("parse spawner edge metadata %q: %v", spawnRow.metadata, err) + } + if spawnMeta["gate"] != "any-children" { + t.Errorf("spawner edge gate = %v, want any-children", spawnMeta["gate"]) + } + if spawnMeta["spawner_id"] != sID { + t.Errorf("spawner edge spawner_id = %v, want %q", spawnMeta["spawner_id"], sID) + } + + // HIGH-2 negative: a waits-for edge with no named spawner must keep + // gate-only metadata and must NOT acquire a spawner_id (the bug: it was + // previously stamped unconditionally from the resolved target). + noSpawnRow := queryEdgeRow(t, beadsDir, "gp", w2ID, s2ID) + var noSpawnMeta map[string]any + if err := json.Unmarshal([]byte(noSpawnRow.metadata), &noSpawnMeta); err != nil { + t.Fatalf("parse no-spawner edge metadata %q: %v", noSpawnRow.metadata, err) + } + if _, present := noSpawnMeta["spawner_id"]; present { + t.Errorf("no-spawner edge metadata = %q, must not contain spawner_id", noSpawnRow.metadata) + } +} diff --git a/cmd/bd/if_revision_gc_matcher_embedded_test.go b/cmd/bd/if_revision_gc_matcher_embedded_test.go new file mode 100644 index 000000000..4ef28c612 --- /dev/null +++ b/cmd/bd/if_revision_gc_matcher_embedded_test.go @@ -0,0 +1,194 @@ +//go:build cgo + +package main + +import ( + "bytes" + "encoding/json" + "os" + "strconv" + "testing" +) + +// This file is a faithful, line-for-line port of the DECODE half of gc's +// (gascity origin/main) internal/beads/bdstore_conditional.go — specifically +// bdConditionalErrorBody, hasDiscriminator, parseBdConditionalErrorBody, and +// decodeBdConditionalBodies. It exists because bd and gc are separate repos +// with no shared Go package: gc's matcher parses bd's CLI JSON error output +// by convention, not by a compiled contract, so the only way to pin that +// contract from bd's side is to copy gc's own decode logic and run it against +// bd's real output. This is the "faithful copy of its decode" alternative the +// 2026-10 Opus review of f8c7ecf01 asked for, in lieu of vendoring the gc +// module. If gc's decode logic changes, this port and +// TestEmbeddedGCConditionalMatcherDecode below must be updated to match — the +// contract is the string/shape, not this file. +// +// Keep this in sync with gc's internal/beads/bdstore_conditional.go. + +type gcBdConditionalErrorBody struct { + Error string `json:"error"` + Code string `json:"code"` + ExpectedRevision *int64 `json:"expected_revision"` + CurrentRevision *int64 `json:"current_revision"` +} + +func (b gcBdConditionalErrorBody) hasDiscriminator() bool { + return b.Code != "" || b.ExpectedRevision != nil || b.CurrentRevision != nil +} + +func gcParseBdConditionalErrorBody(out []byte, errText string) (gcBdConditionalErrorBody, bool) { + sources := [][]byte{out} + if errText != "" { + sources = append(sources, []byte(errText)) + } + var ( + fallback gcBdConditionalErrorBody + haveAny bool + ) + for _, src := range sources { + for _, body := range gcDecodeBdConditionalBodies(src) { + if body.hasDiscriminator() { + return body, true + } + if !haveAny { + fallback, haveAny = body, true + } + } + } + return fallback, haveAny +} + +func gcDecodeBdConditionalBodies(src []byte) []gcBdConditionalErrorBody { + var bodies []gcBdConditionalErrorBody + for i := 0; i < len(src); { + brace := bytes.IndexByte(src[i:], '{') + if brace < 0 { + break + } + i += brace + dec := json.NewDecoder(bytes.NewReader(src[i:])) + var env struct { + Data *gcBdConditionalErrorBody `json:"data"` + gcBdConditionalErrorBody + } + if dec.Decode(&env) != nil { + i++ + continue + } + if env.Data != nil { + bodies = append(bodies, *env.Data) + } else { + bodies = append(bodies, env.gcBdConditionalErrorBody) + } + i += int(dec.InputOffset()) + } + return bodies +} + +// gcClassifyAsPrecondition replicates classifyConditionalWriteResult's +// authoritative-code branch: a recognized machine body code dominates +// everything else, including the message heuristics gc falls back to when bd +// omits a code. This is the path the BLOCKER fix activates — the fallback +// phrase-matching ("precondition failed" / "revision mismatch") is +// deliberately NOT exercised here, since the fix's whole point is that gc no +// longer needs it. +func gcClassifyAsPrecondition(out []byte, errText string) (ok bool, expected, current int64, haveExpected, haveCurrent bool) { + body, bodyOK := gcParseBdConditionalErrorBody(out, errText) + if !bodyOK || body.Code != "precondition_failed" { + return false, 0, 0, false, false + } + if body.ExpectedRevision != nil { + expected, haveExpected = *body.ExpectedRevision, true + } + if body.CurrentRevision != nil { + current, haveCurrent = *body.CurrentRevision, true + } + return true, expected, current, haveExpected, haveCurrent +} + +// TestEmbeddedGCConditionalMatcherDecode runs the ported gc decode (above) +// against a real --if-revision mismatch from the built bd, for every verb gc's +// BdStore.{Update,Close,Delete}IfMatch (and bd's own assign/reopen guards) +// cover, pinning the 2026-10 Opus-review BLOCKER fix end-to-end: gc's own +// classifier logic, not just bd's JSON shape in isolation, must recognize the +// refusal as a precondition with the caller's expected revision and bd's +// current one. The TestEmbedded name in an *_embedded_test.go file is what +// puts it in a CI lane: .github/scripts/embedded-test-shard.sh discovers +// tests by exactly that pair, and under any other name it skips everywhere. +func TestEmbeddedGCConditionalMatcherDecode(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") + } + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "igc") + env := crossModeEnv{mode: "embedded", bd: bd, dir: dir, env: bdEnv(dir)} + + cases := []struct { + name string + closeFirst bool // start from a closed issue rather than a fresh open one + args func(id string) []string + }{ + {"update", false, func(id string) []string { + return []string{"update", id, "--if-revision", "", "--priority", "3", "--json"} + }}, + {"close", false, func(id string) []string { + return []string{"close", id, "--if-revision", "", "--json"} + }}, + {"reopen", true, func(id string) []string { + return []string{"reopen", id, "--if-revision", "", "--json"} + }}, + // The guard is judged before reopen's already-open no-op, so a stale + // token on an open issue is still a refusal (exit 13 and the same + // body), never an "already open" success that stops fencing. + {"reopen_open", false, func(id string) []string { + return []string{"reopen", id, "--if-revision", "", "--json"} + }}, + {"delete", false, func(id string) []string { + return []string{"delete", id, "--if-revision", "", "--force", "--json"} + }}, + {"assign", false, func(id string) []string { + return []string{"assign", id, "bob", "--if-revision", "", "--json"} + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Each case gets its own issue so the cases can run (and be + // re-run individually with `go test -run`) independent of each + // other's order — a guard mismatch never writes, but the two + // reopen rows each need a known starting status. + issue := bdCreate(t, bd, dir, "GC matcher target: "+tc.name, "--type", "task") + if tc.closeFirst { + bdClose(t, bd, dir, issue.ID) + } + rev := bdShowRevision(t, bd, dir, issue.ID) + expected := rev + 1_000_000 // any value distinct from rev works as the "stale" argument + args := tc.args(issue.ID) + for i, a := range args { + if a == "" { + args[i] = strconv.FormatInt(expected, 10) + } + } + stdout, stderr, code := env.run(t, args...) + if code != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitGuardMismatch, stdout, stderr) + } + // gc's runner captures bd's combined output as the subprocess + // error text; bd's own io split (stdout vs stderr) is not + // something gc's matcher relies on, so feeding it stderr (where + // bd actually writes the JSON error) as both "out" and the error + // string is a faithful stand-in for that runner contract. + ok, gotExpected, gotCurrent, haveExpected, haveCurrent := gcClassifyAsPrecondition([]byte(stderr), stderr) + if !ok { + t.Fatalf("gc's matcher did not classify this as precondition_failed\nstderr:\n%s", stderr) + } + if !haveExpected || gotExpected != expected { + t.Errorf("gc decoded expected_revision = %v, want %d", gotExpected, expected) + } + if !haveCurrent { + t.Errorf("gc decoded no current_revision") + } else { + t.Logf("gc decoded current_revision = %d", gotCurrent) + } + }) + } +} diff --git a/cmd/bd/if_revision_proxied_integration_test.go b/cmd/bd/if_revision_proxied_integration_test.go new file mode 100644 index 000000000..24e20ab8d --- /dev/null +++ b/cmd/bd/if_revision_proxied_integration_test.go @@ -0,0 +1,290 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strconv" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +// if_revision_proxied_integration_test.go is the server-path (uow/proxied) +// twin of #7203's if_revision_embedded_test.go (37acca96d): that file only +// exercises --if-revision through buildEmbeddedBD's direct, non-proxied +// route. These tests exercise the same CLI guard through *_proxied_server.go's +// uow-backed preflight/apply path, against a real shared proxied dolt-server, +// to pin that gascity's code:"precondition_failed" + numeric +// expected_revision/current_revision body is identical across both legs, not +// just the embedded one -- including on `bd reopen`, which #7203 did not add +// --if-revision to at all (see reopen.go). +// +// Like every other *_proxied_integration_test.go in this package, this +// requires BEADS_TEST_PROXIED_SERVER=1 and a reachable Dolt container; it +// skips otherwise (see requireProxiedServerEnv). The TestProxiedServer name +// prefix is load-bearing: .github/scripts/proxied-test-shard.sh discovers +// that lane's tests by name, and it is the only lane that sets the env. + +// proxiedPreconditionBody mirrors #7203's own ifRevisionFailureBody +// (if_revision.go): numeric expected_revision/current_revision only, no +// decimal-string twins -- TestEmbeddedGCConditionalMatcherDecode already +// confirmed gc's matcher decodes this shape exactly (encoding/json decodes a +// JSON number straight into an int64 struct field with no float64 +// intermediate, so there is no precision loss to work around here). +type proxiedPreconditionBody struct { + Code string `json:"code"` + ExpectedRevision *int64 `json:"expected_revision"` + CurrentRevision *int64 `json:"current_revision"` +} + +func assertProxiedPreconditionBody(t *testing.T, stderr string, wantExpected int64) { + t.Helper() + obj := lastJSONObjectLine(stderr) + if obj == "" { + t.Fatalf("no JSON object line on stderr:\n%s", stderr) + } + var body proxiedPreconditionBody + if err := json.Unmarshal([]byte(obj), &body); err != nil { + t.Fatalf("parse error body: %v\nraw: %s", err, obj) + } + if body.Code != ifRevisionCodePreconditionFailed { + t.Errorf("code = %q, want %q\nraw: %s", body.Code, ifRevisionCodePreconditionFailed, obj) + } + if body.ExpectedRevision == nil || *body.ExpectedRevision != wantExpected { + t.Errorf("expected_revision = %v, want %d (JSON number, not string)\nraw: %s", body.ExpectedRevision, wantExpected, obj) + } + if body.CurrentRevision == nil { + t.Errorf("current_revision is absent, want a value\nraw: %s", obj) + } +} + +func currentRevisionOfProxied(t *testing.T, bd, dir, id string) int64 { + t.Helper() + details := bdProxiedShowDetailsFirst(t, bd, dir, id) + rev, ok := details["revision"].(string) + if !ok || rev == "" { + t.Fatalf("bd show %s --json has no non-empty revision field: %+v", id, details) + } + v, err := strconv.ParseInt(rev, 10, 64) + if err != nil { + t.Fatalf("bd show %s --json returned an unparseable revision %q: %v", id, rev, err) + } + return v +} + +func staleRevisionFor(rev int64) int64 { + stale := int64(999999999) + if stale == rev { + stale = 999999998 + } + return stale +} + +// TestProxiedServerIfRevisionGuardUpdate pins bd update --if-revision on the +// proxied-server leg: a stale token refuses with exit 13 and a +// precondition_failed JSON body naming numeric revisions, writing nothing; +// the matching token applies. +func TestProxiedServerIfRevisionGuardUpdate(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + proj := newSharedProxiedProject(t, bd, "piu") + env := crossModeEnv{mode: "proxied", bd: bd, dir: proj.dir, env: bdProxiedEnv(proj.dir)} + + issue := bdProxiedCreate(t, bd, proj.dir, "Guarded proxied update", "--type", "task") + rev := currentRevisionOfProxied(t, bd, proj.dir, issue.ID) + + t.Run("mismatch_refuses_and_writes_nothing", func(t *testing.T) { + stale := staleRevisionFor(rev) + stdout, stderr, code := env.run(t, "update", issue.ID, "--if-revision", strconv.FormatInt(stale, 10), + "--priority", "3", "--json") + if code != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitGuardMismatch, stdout, stderr) + } + assertProxiedPreconditionBody(t, stderr, stale) + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Priority == 3 { + t.Errorf("stale --if-revision wrote the row: priority = %d", got.Priority) + } + }) + + t.Run("match_applies", func(t *testing.T) { + env.run(t, "update", issue.ID, "--if-revision", strconv.FormatInt(rev, 10), "--priority", "3") + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Priority != 3 { + t.Fatalf("matching --if-revision did not apply: priority = %d", got.Priority) + } + }) +} + +// TestProxiedServerIfRevisionGuardClose mirrors #7203's embedded close +// coverage against the proxied-server leg. +func TestProxiedServerIfRevisionGuardClose(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + proj := newSharedProxiedProject(t, bd, "pic") + env := crossModeEnv{mode: "proxied", bd: bd, dir: proj.dir, env: bdProxiedEnv(proj.dir)} + + issue := bdProxiedCreate(t, bd, proj.dir, "Guarded proxied close", "--type", "task") + rev := currentRevisionOfProxied(t, bd, proj.dir, issue.ID) + + t.Run("mismatch_refuses_and_leaves_open", func(t *testing.T) { + stale := staleRevisionFor(rev) + stdout, stderr, code := env.run(t, "close", issue.ID, "--if-revision", strconv.FormatInt(stale, 10), "--json") + if code != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitGuardMismatch, stdout, stderr) + } + assertProxiedPreconditionBody(t, stderr, stale) + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Status != types.StatusOpen { + t.Errorf("stale --if-revision close changed status: %s", got.Status) + } + }) + + t.Run("match_closes", func(t *testing.T) { + env.run(t, "close", issue.ID, "--if-revision", strconv.FormatInt(rev, 10)) + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Status != types.StatusClosed { + t.Fatalf("matching --if-revision did not close: status = %s", got.Status) + } + }) +} + +// TestProxiedServerIfRevisionGuardReopen covers `bd reopen --if-revision` on +// the proxied-server leg: #7203 did not add --if-revision to reopen at all, so +// unlike the other four verbs there is no #7203 embedded-leg sibling to +// mirror here; the direct route's coverage is +// TestEmbeddedIfRevisionReopenGuardDirect and +// TestEmbeddedGCConditionalMatcherDecode. +// +// The already_open_* subtests pin the bee-ghosttrack maintainer-review +// blocker: a stale --if-revision guard on an already-open issue must still +// report exit 13 with a precondition_failed body, not the silent +// already-open no-op. See if_revision_reopen_embedded_test.go for the +// direct-route twin of this same gap. +func TestProxiedServerIfRevisionGuardReopen(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + proj := newSharedProxiedProject(t, bd, "pir") + env := crossModeEnv{mode: "proxied", bd: bd, dir: proj.dir, env: bdProxiedEnv(proj.dir)} + + alreadyOpen := bdProxiedCreate(t, bd, proj.dir, "Guarded proxied reopen (already open)", "--type", "task") + openRev := currentRevisionOfProxied(t, bd, proj.dir, alreadyOpen.ID) + + t.Run("already_open_mismatch_refuses", func(t *testing.T) { + stale := staleRevisionFor(openRev) + stdout, stderr, code := env.run(t, "reopen", alreadyOpen.ID, "--if-revision", strconv.FormatInt(stale, 10), "--json") + if code != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitGuardMismatch, stdout, stderr) + } + assertProxiedPreconditionBody(t, stderr, stale) + got := bdProxiedShow(t, bd, proj.dir, alreadyOpen.ID) + if got.Status != types.StatusOpen { + t.Errorf("stale --if-revision reopen of an already-open issue changed status: %s", got.Status) + } + if gotRev := currentRevisionOfProxied(t, bd, proj.dir, alreadyOpen.ID); gotRev != openRev { + t.Errorf("stale --if-revision reopen of an already-open issue advanced the revision: %d, want unchanged %d", gotRev, openRev) + } + }) + + t.Run("already_open_match_is_noop", func(t *testing.T) { + stdout, _, code := env.run(t, "reopen", alreadyOpen.ID, "--if-revision", strconv.FormatInt(openRev, 10)) + if code != 0 { + t.Fatalf("matching --if-revision reopen of an already-open issue should succeed as a no-op, exit = %d\nstdout:\n%s", code, stdout) + } + got := bdProxiedShow(t, bd, proj.dir, alreadyOpen.ID) + if got.Status != types.StatusOpen { + t.Errorf("matching --if-revision reopen of an already-open issue changed status: %s", got.Status) + } + }) + + issue := bdProxiedCreate(t, bd, proj.dir, "Guarded proxied reopen", "--type", "task") + bdProxiedClose(t, bd, proj.dir, issue.ID) + rev := currentRevisionOfProxied(t, bd, proj.dir, issue.ID) + + t.Run("mismatch_refuses_and_leaves_closed", func(t *testing.T) { + stale := staleRevisionFor(rev) + stdout, stderr, code := env.run(t, "reopen", issue.ID, "--if-revision", strconv.FormatInt(stale, 10), "--json") + if code != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitGuardMismatch, stdout, stderr) + } + assertProxiedPreconditionBody(t, stderr, stale) + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Status != types.StatusClosed { + t.Errorf("stale --if-revision reopen changed status: %s", got.Status) + } + }) + + t.Run("match_reopens", func(t *testing.T) { + env.run(t, "reopen", issue.ID, "--if-revision", strconv.FormatInt(rev, 10)) + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Status != types.StatusOpen { + t.Fatalf("matching --if-revision did not reopen: status = %s", got.Status) + } + }) +} + +// TestProxiedServerIfRevisionGuardDelete mirrors #7203's embedded delete +// coverage against the proxied-server leg. +func TestProxiedServerIfRevisionGuardDelete(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + proj := newSharedProxiedProject(t, bd, "pid") + env := crossModeEnv{mode: "proxied", bd: bd, dir: proj.dir, env: bdProxiedEnv(proj.dir)} + + issue := bdProxiedCreate(t, bd, proj.dir, "Guarded proxied delete", "--type", "task") + rev := currentRevisionOfProxied(t, bd, proj.dir, issue.ID) + + t.Run("mismatch_refuses_and_leaves_issue", func(t *testing.T) { + stale := staleRevisionFor(rev) + stdout, stderr, code := env.run(t, "delete", issue.ID, "--if-revision", strconv.FormatInt(stale, 10), "--force", "--json") + if code != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitGuardMismatch, stdout, stderr) + } + assertProxiedPreconditionBody(t, stderr, stale) + bdProxiedShow(t, bd, proj.dir, issue.ID) + }) + + t.Run("match_deletes", func(t *testing.T) { + stdout, stderr, code := env.run(t, "delete", issue.ID, "--if-revision", strconv.FormatInt(rev, 10), "--force") + if code != 0 { + t.Fatalf("matching --if-revision delete failed: exit %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + if _, _, code := env.run(t, "show", issue.ID); code == 0 { + t.Errorf("issue %s still resolves after matching --if-revision delete", issue.ID) + } + }) +} + +// TestProxiedServerIfRevisionGuardAssign mirrors #7203's embedded assign +// coverage against the proxied-server leg. +func TestProxiedServerIfRevisionGuardAssign(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + proj := newSharedProxiedProject(t, bd, "pia") + env := crossModeEnv{mode: "proxied", bd: bd, dir: proj.dir, env: bdProxiedEnv(proj.dir)} + + issue := bdProxiedCreate(t, bd, proj.dir, "Guarded proxied assign", "--type", "task") + rev := currentRevisionOfProxied(t, bd, proj.dir, issue.ID) + + t.Run("mismatch_refuses_and_leaves_unassigned", func(t *testing.T) { + stale := staleRevisionFor(rev) + stdout, stderr, code := env.run(t, "assign", issue.ID, "alice", "--if-revision", strconv.FormatInt(stale, 10), "--json") + if code != ExitGuardMismatch { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitGuardMismatch, stdout, stderr) + } + assertProxiedPreconditionBody(t, stderr, stale) + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Assignee != "" { + t.Errorf("stale --if-revision assign wrote the row: assignee = %q", got.Assignee) + } + }) + + t.Run("match_assigns", func(t *testing.T) { + env.run(t, "assign", issue.ID, "alice", "--if-revision", strconv.FormatInt(rev, 10)) + got := bdProxiedShow(t, bd, proj.dir, issue.ID) + if got.Assignee != "alice" { + t.Fatalf("matching --if-revision did not assign: assignee = %q", got.Assignee) + } + }) +} diff --git a/cmd/bd/if_revision_reopen_embedded_test.go b/cmd/bd/if_revision_reopen_embedded_test.go new file mode 100644 index 000000000..016cc2bae --- /dev/null +++ b/cmd/bd/if_revision_reopen_embedded_test.go @@ -0,0 +1,99 @@ +//go:build cgo + +package main + +import ( + "os" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +// if_revision_reopen_embedded_test.go pins the bee-ghosttrack maintainer-review +// blocker on `bd reopen --if-revision`'s direct (non-proxied) route: reopen.go +// used to run its "issue.Status == types.StatusOpen" already-open short-circuit +// unconditionally, BEFORE ops.Reopen ever got a chance to evaluate +// ExpectedVersion (ExecuteReopen -> CheckVersionInTx). That meant a stale +// --if-revision guard against an already-open issue silently returned the +// "already open" no-op (exit 0) instead of the precondition_failed refusal +// (exit 13) every other guarded verb gives for a stale token -- see +// TestEmbeddedGCConditionalMatcherDecode's reopen_open row for the same +// refusal pinned from the gc-matcher angle. +// +// TestProxiedServerIfRevisionGuardReopen +// (if_revision_proxied_integration_test.go) is this file's proxied-server-leg +// twin. The TestEmbedded name is what puts this test in a CI lane +// (.github/scripts/embedded-test-shard.sh); under any other name it skips +// everywhere. +func TestEmbeddedIfRevisionReopenGuardDirect(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") + } + t.Parallel() + + bd := buildEmbeddedBD(t) + dir, _, _ := bdInit(t, bd, "--prefix", "irr") + + t.Run("already_open_mismatch_refuses", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Guarded reopen (already open)", "--type", "task") + rev := bdShowRevision(t, bd, dir, issue.ID) + stale := rev + 1_000_000 + + out, code := bdRunFailCode(t, bd, dir, "reopen", issue.ID, "--if-revision", revStr(stale), "--json") + if code != ExitGuardMismatch { + t.Fatalf("stale --if-revision reopen of an already-open issue exit = %d, want %d\n%s", code, ExitGuardMismatch, out) + } + if got := bdShow(t, bd, dir, issue.ID); got.Status != types.StatusOpen { + t.Errorf("stale --if-revision reopen of an already-open issue changed status: %s", got.Status) + } + if got := bdShowRevision(t, bd, dir, issue.ID); got != rev { + t.Errorf("stale --if-revision reopen of an already-open issue advanced the revision: %d, want unchanged %d", got, rev) + } + }) + + t.Run("already_open_match_is_noop", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Guarded reopen (already open, matching)", "--type", "task") + rev := bdShowRevision(t, bd, dir, issue.ID) + + out := bdRunOK(t, bd, dir, "reopen", issue.ID, "--if-revision", revStr(rev)) + if !strings.Contains(out, issue.ID+" is already open") { + t.Errorf("matching --if-revision reopen of an already-open issue lacks the already-open no-op line:\n%s", out) + } + if got := bdShow(t, bd, dir, issue.ID); got.Status != types.StatusOpen { + t.Errorf("matching --if-revision reopen of an already-open issue changed status: %s\noutput:\n%s", got.Status, out) + } + if got := bdShowRevision(t, bd, dir, issue.ID); got != rev { + t.Errorf("matching --if-revision reopen of an already-open issue advanced the revision: %d, want unchanged %d", got, rev) + } + }) + + t.Run("closed_mismatch_refuses", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Guarded reopen (closed, mismatch)", "--type", "task") + bdClose(t, bd, dir, issue.ID) + rev := bdShowRevision(t, bd, dir, issue.ID) + stale := rev + 1_000_000 + + out, code := bdRunFailCode(t, bd, dir, "reopen", issue.ID, "--if-revision", revStr(stale), "--json") + if code != ExitGuardMismatch { + t.Fatalf("stale --if-revision reopen of a closed issue exit = %d, want %d\n%s", code, ExitGuardMismatch, out) + } + if got := bdShow(t, bd, dir, issue.ID); got.Status != types.StatusClosed { + t.Errorf("stale --if-revision reopen of a closed issue changed status: %s", got.Status) + } + if got := bdShowRevision(t, bd, dir, issue.ID); got != rev { + t.Errorf("stale --if-revision reopen of a closed issue advanced the revision: %d, want unchanged %d", got, rev) + } + }) + + t.Run("closed_match_reopens", func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Guarded reopen (closed, matching)", "--type", "task") + bdClose(t, bd, dir, issue.ID) + rev := bdShowRevision(t, bd, dir, issue.ID) + + bdRunOK(t, bd, dir, "reopen", issue.ID, "--if-revision", revStr(rev)) + if got := bdShow(t, bd, dir, issue.ID); got.Status != types.StatusOpen { + t.Fatalf("matching --if-revision reopen of a closed issue did not reopen: status = %s", got.Status) + } + }) +} diff --git a/cmd/bd/proxied_lookup_failure_test.go b/cmd/bd/proxied_lookup_failure_test.go index 5aa7d1e9f..35b8dfd4d 100644 --- a/cmd/bd/proxied_lookup_failure_test.go +++ b/cmd/bd/proxied_lookup_failure_test.go @@ -239,7 +239,7 @@ var proxiedLookupCommands = []struct { { name: "reopen", run: func(ctx context.Context) error { - return runReopenProxiedServer(&cobra.Command{}, ctx, []string{stubMissingID}) + return runReopenProxiedServer(&cobra.Command{}, ctx, []string{stubMissingID}, nil) }, wantNotFound: "Issue " + stubMissingID + " not found\nHint: " + showNotFoundHint(stubMissingID), wantHardErr: "Error resolving bd-missing: connection reset by peer", diff --git a/cmd/bd/reopen.go b/cmd/bd/reopen.go index 700800b57..6bdb3f7cd 100644 --- a/cmd/bd/reopen.go +++ b/cmd/bd/reopen.go @@ -17,7 +17,11 @@ var reopenCmd = &cobra.Command{ GroupID: "issues", Short: "Reopen one or more closed issues", Long: `Reopen closed issues by setting status to 'open' and clearing the closed_at timestamp. -This is more explicit than 'bd update --status open' and emits a Reopened event.`, +This is more explicit than 'bd update --status open' and emits a Reopened event. + +Exit codes: 1 for general failures; 13 when the failure is a stale +--if-revision guard (the precondition no longer held, nothing was written — +another actor won the race, so retrying the same guard is pointless).`, Args: cobra.MinimumNArgs(1), SilenceUsage: true, SilenceErrors: true, @@ -31,8 +35,20 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. } }() + // beads#4682: an independent OCC precondition on the single issue it + // names, so (unlike the batch of ids this command otherwise accepts) + // it requires exactly one target — same rule update/close/delete + // enforce via requireSingleIfRevisionID. + ifRevision, err := parseIfRevisionFlag(cmd) + if err != nil { + return err + } + if err := requireSingleIfRevisionID(ifRevision, args); err != nil { + return err + } + if usesProxiedServer() { - return runReopenProxiedServer(cmd, rootCtx, args) + return runReopenProxiedServer(cmd, rootCtx, args, ifRevision) } reason, _ := cmd.Flags().GetString("reason") @@ -61,7 +77,13 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. issueStore := result.Store issue := result.Issue - if issue.Status == types.StatusOpen { + // An active --if-revision guard must be evaluated before this + // already-open short-circuit: ops.Reopen below checks + // ExpectedVersion first (ExecuteReopen -> CheckVersionInTx), so a + // stale revision on an already-open issue still reports exit 13 + // instead of silently returning the "already open" no-op here. + // Without --if-revision, today's pre-check stands unchanged. + if ifRevision == nil && issue.Status == types.StatusOpen { fmt.Fprintln(os.Stderr, reopenNoOpMessage(fullID, types.StatusOpen)) result.Close() continue @@ -74,15 +96,26 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. continue } reopened, err := ops.Reopen(opsCtx, issueops.ReopenRequest{ - Actor: actor, - IssueID: fullID, - Reason: reason, + Actor: actor, + IssueID: fullID, + Reason: reason, + ExpectedVersion: ifRevision, // Names the issue for the reason `bd close`'s does, and keeps // the entry identical across backends: the proxied route // already writes "bd: reopen ". Provenance: "bd: reopen " + fullID, }) if err != nil { + // Only a guarded reopen reports through the conditional-write + // envelope: the classifier maps storage.ErrNotFound to + // precondition_failed, which an unguarded reopen racing a + // delete must not claim. + if ifRevision != nil { + if reported, ok := reportIfRevisionFailure("reopening", fullID, err, ifRevision); ok { + result.Close() + return reported + } + } fmt.Fprintf(os.Stderr, "Error reopening %s: %v\n", fullID, err) hasError = true result.Close() @@ -170,6 +203,10 @@ func reopenStatusOf(post, pre *types.Issue) types.Status { func init() { reopenCmd.Flags().StringP("reason", "r", "", "Reason for reopening") + // beads#4682: not part of #7203's original four verbs (update/close/ + // assign/delete); reopen gets the same guard since it is the same kind + // of single-id lifecycle write. + reopenCmd.Flags().String("if-revision", "", ifRevisionFlagHelp) reopenCmd.ValidArgsFunction = issueIDCompletion rootCmd.AddCommand(reopenCmd) } diff --git a/cmd/bd/reopen_proxied_server.go b/cmd/bd/reopen_proxied_server.go index b57dbaf8b..a9fadd638 100644 --- a/cmd/bd/reopen_proxied_server.go +++ b/cmd/bd/reopen_proxied_server.go @@ -40,7 +40,7 @@ type reopenProxiedTarget struct { // ONE CALL PER ID, so one transaction and one history entry per id, where this // route used to run every id in one unit of work under a hand-composed // "bd: reopen a, b" message. -func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { +func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []string, ifRevision *int64) error { if len(args) == 0 { return HandleErrorRespectJSON("no issue ID provided") } @@ -66,14 +66,22 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri reopenedIssues := []*types.Issue{} for _, target := range targets { result, err := lifecycle.Reopen(ctx, issueops.ReopenRequest{ - Actor: actor, - IssueID: target.id, - Reason: reason, + Actor: actor, + IssueID: target.id, + Reason: reason, + ExpectedVersion: ifRevision, // The label the direct route spells, so one reopen reads the same // in `bd dolt log` whichever route served it. Provenance: "bd: reopen " + target.id, }) if err != nil { + // Guarded only, as on the direct route: an unguarded reopen that + // loses a race with a delete is a lookup failure, not a refusal. + if ifRevision != nil { + if reported, ok := reportIfRevisionFailure("reopening", target.id, err, ifRevision); ok { + return reported + } + } reportIssueLookupFailure("reopening", target.id, err) hasError = true continue diff --git a/internal/storage/dolt/batch_apply_contract_test.go b/internal/storage/dolt/batch_apply_contract_test.go index afb3347ea..7c32d9a37 100644 --- a/internal/storage/dolt/batch_apply_contract_test.go +++ b/internal/storage/dolt/batch_apply_contract_test.go @@ -175,6 +175,11 @@ func TestBatchApplyContract(t *testing.T) { defer cancel() conformance.RunBatchApplyNormalizesTheWaitsForGate(t, ctx, fixture) }) + t.Run("StampsSpawnerIDOnlyWhenNamed", func(t *testing.T) { + ctx, cancel := testContext(t) + defer cancel() + conformance.RunBatchApplyStampsSpawnerIDOnlyWhenNamed(t, ctx, fixture) + }) t.Run("SplicesAForwardMetadataRef", func(t *testing.T) { ctx, cancel := testContext(t) defer cancel() diff --git a/internal/storage/embeddeddolt/batch_apply_contract_test.go b/internal/storage/embeddeddolt/batch_apply_contract_test.go index 439bc1584..3ed6724a9 100644 --- a/internal/storage/embeddeddolt/batch_apply_contract_test.go +++ b/internal/storage/embeddeddolt/batch_apply_contract_test.go @@ -113,6 +113,9 @@ func TestBatchApplyContract(t *testing.T) { t.Run("NormalizesTheWaitsForGate", func(t *testing.T) { conformance.RunBatchApplyNormalizesTheWaitsForGate(t, ctx, fixture) }) + t.Run("StampsSpawnerIDOnlyWhenNamed", func(t *testing.T) { + conformance.RunBatchApplyStampsSpawnerIDOnlyWhenNamed(t, ctx, fixture) + }) t.Run("SplicesAForwardMetadataRef", func(t *testing.T) { conformance.RunBatchApplySplicesAForwardMetadataRef(t, ctx, fixture) }) diff --git a/internal/storage/issueops/batch_apply.go b/internal/storage/issueops/batch_apply.go index 59dec2a1c..bd6a251d1 100644 --- a/internal/storage/issueops/batch_apply.go +++ b/internal/storage/issueops/batch_apply.go @@ -370,11 +370,20 @@ func (r *applyBatchRun) applyDepAdd(ctx context.Context, tx *sql.Tx, index int, } sourceTable, _, eventTable, depTable := WispTableRouting(sourceWisp) + metadata := item.Metadata + if item.HasSpawner { + metadata, err = StampWaitsForSpawnerID(item.Type, item.Metadata, target) + if err != nil { + return itemErr(fmt.Errorf("%w: %v", publicops.ErrValidation, err)) + } + } + dep := &types.Dependency{ IssueID: source, DependsOnID: target, Type: item.Type, - Metadata: item.Metadata, + Metadata: metadata, + ThreadID: item.ThreadID, } eventWritten, err := AddDependencyInTx(ctx, tx, dep, r.plan.Actor, AddDependencyOpts{ SourceTable: sourceTable, @@ -411,6 +420,43 @@ func (r *applyBatchRun) applyDepAdd(ctx context.Context, tx *sql.Tx, index int, return nil } +// StampWaitsForSpawnerID fills a waits-for edge's metadata with the spawner id +// this item resolved, AFTER every id this request mints exists. +// +// A GRAPH PLAN'S SPAWNER IS ALWAYS THE EDGE'S OWN TARGET — the caller cannot +// spell a waits-for item any other way, since the planner above this role +// forces spawner_key/spawner_id to match to_key/to_id before the request ever +// reaches a transaction. So the resolved target this item just computed IS the +// spawner id, known or not at the time the caller built the request: a +// plan-local Ref.Key names a row this very request is minting, and its id does +// not exist until the create item ahead of this one in Items runs. Stamping it +// here, after resolve, is what lets a waits-for edge name a same-batch spawner +// by key at all — item.Metadata alone has no way to carry an id nothing had +// minted yet. +// +// metadata.spawner_id is otherwise redundant with dependencies.depends_on_id +// (NewGraphEdgeDependency's doc states gate evaluation reads the column, never +// the blob) and this keeps it from drifting from that column regardless of +// what a caller's Metadata happened to say. +func StampWaitsForSpawnerID(depType types.DependencyType, metadata, target string) (string, error) { + if depType != types.DepWaitsFor { + return metadata, nil + } + meta := types.WaitsForMeta{} + trimmed := strings.TrimSpace(metadata) + if trimmed != "" { + if err := json.Unmarshal([]byte(trimmed), &meta); err != nil { + return "", fmt.Errorf("waits-for metadata is not a well-formed gate object: %w", err) + } + } + meta.SpawnerID = target + raw, err := json.Marshal(meta) + if err != nil { + return "", fmt.Errorf("serializing waits-for metadata: %w", err) + } + return string(raw), nil +} + // spliceMetadataRefs writes the resolved ids into the metadata of the create // items that asked for them, AFTER every id in the request exists. // diff --git a/internal/storage/uow/batch_applier.go b/internal/storage/uow/batch_applier.go index aba391947..9c41e1ae6 100644 --- a/internal/storage/uow/batch_applier.go +++ b/internal/storage/uow/batch_applier.go @@ -462,11 +462,19 @@ func (r *uowApplyRun) applyDepAdd(ctx context.Context, index int, item *publicop if err != nil { return itemErr(err) } + metadata := item.Metadata + if item.HasSpawner { + metadata, err = storageissueops.StampWaitsForSpawnerID(item.Type, item.Metadata, target) + if err != nil { + return itemErr(fmt.Errorf("%w: %v", publicops.ErrValidation, err)) + } + } dep := &types.Dependency{ IssueID: source, DependsOnID: target, Type: item.Type, - Metadata: item.Metadata, + Metadata: metadata, + ThreadID: item.ThreadID, } if _, err := r.uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, r.plan.Actor, domain.BulkAddDepsOpts{ SkipPerEdgeCycleCheck: r.plan.SkipPerEdgeCycleCheck, diff --git a/internal/storage/uow/batch_apply_contract_test.go b/internal/storage/uow/batch_apply_contract_test.go index 255a7c879..d49656b44 100644 --- a/internal/storage/uow/batch_apply_contract_test.go +++ b/internal/storage/uow/batch_apply_contract_test.go @@ -115,6 +115,9 @@ func TestBatchApplyContract(t *testing.T) { t.Run("NormalizesTheWaitsForGate", func(t *testing.T) { conformance.RunBatchApplyNormalizesTheWaitsForGate(t, ctx, fixture) }) + t.Run("StampsSpawnerIDOnlyWhenNamed", func(t *testing.T) { + conformance.RunBatchApplyStampsSpawnerIDOnlyWhenNamed(t, ctx, fixture) + }) t.Run("SplicesAForwardMetadataRef", func(t *testing.T) { conformance.RunBatchApplySplicesAForwardMetadataRef(t, ctx, fixture) }) diff --git a/issueops/batchapplier.go b/issueops/batchapplier.go index 8eff362fb..39889926e 100644 --- a/issueops/batchapplier.go +++ b/issueops/batchapplier.go @@ -219,6 +219,27 @@ type DepAddItem struct { // members — a spawner, an also-blocks flag — a two-field typed member could // not express. One spelling, and it is this one. Metadata string + // HasSpawner marks a DepWaitsFor edge whose caller explicitly named a + // spawner (bd create --graph's edges[].spawner_key/spawner_id, which the + // CLI's own plan validator already forces to equal this edge's own + // Target). Only then does the role stamp Metadata's spawner_id from the + // resolved Target, once every id in the batch exists (see + // StampWaitsForSpawnerID) — a plan-local spawner key cannot be resolved + // any earlier than that. + // + // AN EDGE WITH NO NAMED SPAWNER MUST KEEP ITS GATE-ONLY METADATA. Stamping + // one in regardless of this flag — the 2026-10 Opus-review HIGH-2 finding + // — produces metadata an unspawnered edge's caller never asked for, which + // is a stored row a later re-apply of the same plan (e.g. by gc) will see + // disagree with what it sent, causing a spurious rewrite and version + // churn the role must not manufacture on its own. Ignored for every other + // Type. + HasSpawner bool + // ThreadID carries conversation-threading metadata (e.g. a replies-to + // edge's originating thread) onto the created dependency row. Empty means + // the edge carries none; it is a plain column, not part of Metadata's + // type-specific blob. + ThreadID string } // ApplyItem is ONE item of a batch: a kind plus exactly one member matching it.