diff --git a/.github/scripts/embedded-storage-test-shards.txt b/.github/scripts/embedded-storage-test-shards.txt index 7e9f2991d..8e103b3e0 100644 --- a/.github/scripts/embedded-storage-test-shards.txt +++ b/.github/scripts/embedded-storage-test-shards.txt @@ -152,6 +152,7 @@ 40 3 TestCrossRecordInvariantContract 40 3 TestDepRekeyMarkerStillInIgnoredSeries 40 3 TestDoltCommitResponseLossIsIndeterminate +40 3 TestEmbeddedDependencyEditorRefusesADottedChildGatedOnItsOwnParent 40 3 TestEmbeddedDoltStoreIssueLifecycleBuildsOperations 40 3 TestEmbeddedDoltStoreIssueLifecycleRejectsNilStore 40 3 TestEmbeddedOpenReadOnly_FreshDatabaseNoWrites diff --git a/.github/scripts/proxied-cmd-test-shards.txt b/.github/scripts/proxied-cmd-test-shards.txt index 42a1fc999..72e73e898 100644 --- a/.github/scripts/proxied-cmd-test-shards.txt +++ b/.github/scripts/proxied-cmd-test-shards.txt @@ -392,6 +392,7 @@ 34 20 TestProxiedServerWispGC 34 20 TestServerModeSharedServeGlobalReportsTheServedDatabase +34 21 TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent 34 21 TestProxiedServerConfig 34 21 TestProxiedServerExternalPolicyDirectParity 34 21 TestProxiedServerMoleculeFrontDoorDirectServerProxyParity diff --git a/CHANGELOG.md b/CHANGELOG.md index 230391fdc..5477be6ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -263,6 +263,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `POST /v0/beads/issues/{id}:claim` (`issueops.Claimer`) still claims a template that a `PATCH` with `claim: true` refuses. Close's guards move to the role in their own change (#7425). +- The dotted-id hierarchy refusal (a child such as `bd-abc.1` may not carry an + explicit edge to its own ancestor, other than the parent-child edge to its + immediate parent) moved from `cmd/bd` into the library as + `issueops.CheckDottedChildDependency` / `*issueops.DottedChildDependencyError` + (unwraps to `ErrValidation`). Every `DependencyEditor` (dolt, embedded, + unit of work, HTTP) and every `BatchApplier` dep_add item now enforces it, so + an HTTP `dependencies:add`, a `batch:apply` edge and `bd create --graph`'s own + edges are refused like `bd dep add` (HTTP: 400 `invalid_argument`). `bd dep + add`, `bd dep --blocks`, `bd link` and `bd dep add --file` print the same + messages as before, and a `bd batch` script's `dep add` line, which neither + backend checked, is now refused with that message and rolls the whole batch + back. The refusal is decided from the two ids, ahead of every check that + reads the stored graph, so for a child whose parent-child edge is already + stored (a `bd create --parent` child) an HTTP caller now gets that 400 where + it used to get 409 `dependency_cycle` (a blocking type) or + `dependency_exists` (any other type). - **PRs based on `hotfix/**` branches now run full CI, not just cross-version historical smokes and triage labeling.** `pr.yml`, `pr-risk.yml`, `conformance.yml`, `cross-version-smoke.yml` and diff --git a/backend/conformance/batch_apply_contract.go b/backend/conformance/batch_apply_contract.go index c2ac269d9..f6480e47a 100644 --- a/backend/conformance/batch_apply_contract.go +++ b/backend/conformance/batch_apply_contract.go @@ -2657,3 +2657,80 @@ func RunBatchApplyCloseItemsAnswerToTheCloseGuards(t *testing.T, ctx context.Con } } } + +// RunBatchApplyRefusesADottedChildGatedOnItsOwnParent pins the dotted-id +// hierarchy rule (publicops.CheckDottedChildDependency) on a dep_add item: an +// edge from a dotted-id child to its own ancestor is refused with an +// *ItemError naming the edge, and the whole request rolls back. The rule is +// applied to the RESOLVED ids, so a key bound to a dotted child this request +// creates — the `bd create --graph` shape — is refused like a stored id. +// +// POSITIVE HALF: the parent-child edge to the immediate dotted parent lands. +// +// WITH THE HIERARCHY STORED: once that edge exists (the shape `bd create +// --parent` leaves), a blocking edge on the same pair is still this validation +// refusal, not the hierarchy conflict the stored edge would raise (which does +// not match ErrValidation) — the rule reads only the resolved ids, so it +// answers first — and the stored edge survives. +func RunBatchApplyRefusesADottedChildGatedOnItsOwnParent(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + parent := fixture.IssuePrefix + "-dotted" + child := parent + ".1" + minted := parent + ".2" + batchApplySeedIssue(t, ctx, fixture, parent, types.StatusOpen) + batchApplySeedIssue(t, ctx, fixture, child, types.StatusOpen) + + for _, refused := range []struct { + name string + items []publicops.ApplyItem + index int + }{ + {"a stored child blocking on its parent", []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: child}, publicops.Ref{ID: parent}, publicops.DepBlocks, ""), + }, 0}, + {"a child this request creates blocking on its parent", []publicops.ApplyItem{ + batchApplyCreate("child", batchApplyIssue(minted, "the new child")), + batchApplyDepAdd(publicops.Ref{Key: "child"}, publicops.Ref{ID: parent}, publicops.DepBlocks, ""), + }, 1}, + } { + _, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + ForceIDPrefix: true, + Items: refused.items, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("%s: error = %v, want ErrValidation", refused.name, err) + continue + } + var itemErr *publicops.ItemError + if !errors.As(err, &itemErr) { + t.Errorf("%s: error = %v, want an *ItemError naming the edge item", refused.name, err) + continue + } + if itemErr.Index != refused.index || itemErr.Kind != publicops.ItemDepAdd { + t.Errorf("%s: ItemError = %#v, want Index %d and Kind %q", refused.name, itemErr, refused.index, publicops.ItemDepAdd) + } + } + assertBatchApplyEdgeCount(t, ctx, fixture, child, parent, 0) + assertBatchApplyRowCount(t, ctx, fixture, "issues", minted, 0) + + batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: child}, publicops.Ref{ID: parent}, publicops.DepParentChild, ""), + }, + }) + assertBatchApplyEdgeCount(t, ctx, fixture, child, parent, 1) + + _, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{ + Actor: "apply-writer", + Items: []publicops.ApplyItem{ + batchApplyDepAdd(publicops.Ref{ID: child}, publicops.Ref{ID: parent}, publicops.DepBlocks, ""), + }, + }) + var itemErr *publicops.ItemError + if !errors.Is(err, publicops.ErrValidation) || !errors.As(err, &itemErr) { + t.Errorf("blocks on a parent whose parent-child edge is stored: error = %v, want an *ItemError matching ErrValidation", err) + } + assertBatchApplyEdgeCount(t, ctx, fixture, child, parent, 1) +} diff --git a/backend/conformance/dependency_editor_contract.go b/backend/conformance/dependency_editor_contract.go index e037e9dbe..4f5b33268 100644 --- a/backend/conformance/dependency_editor_contract.go +++ b/backend/conformance/dependency_editor_contract.go @@ -2631,3 +2631,82 @@ func dependencyEditorHistoryProbe(t *testing.T, ctx context.Context, fixture Dep assertDependencyEditorHistoryDelta(t, ctx, fixture, before, want, why) } } + +// RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent pins +// publicops.CheckDottedChildDependency on the role: an explicit edge from a +// dotted-id child to its own ancestor is refused as a +// *DottedChildDependencyError (ErrValidation) on every leg, and nothing is +// written. (It is decided before any per-edge probe, so the probe-skipped +// spelling, which the wire does not publish, adds nothing here.) It used to be +// enforced only by the CLI ahead of the role, so an HTTP or embedded caller +// could gate bd-abc.1 on bd-abc. +// +// POSITIVE HALF: the hierarchy itself — a parent-child edge to the IMMEDIATE +// dotted parent — is allowed, and so is an edge between siblings. A body that +// refused every edge touching a dotted id would satisfy the refusals alone. +// +// WITH THE HIERARCHY STORED: once that parent-child edge exists (the shape +// `bd create --parent` leaves), a blocking edge on the same pair is still this +// refusal, not the type or hierarchy conflict the stored edge would raise — the +// rule reads nothing, so it answers first — and the stored edge survives. +func RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + parent := fixture.IssuePrefix + "-dotted" + child := parent + ".1" + grandchild := child + ".2" + sibling := parent + ".3" + for _, id := range []string{parent, child, grandchild, sibling} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + + for _, refused := range []struct { + name string + edge publicops.DependencyEdge + }{ + {"child blocks on its parent", publicops.DependencyEdge{IssueID: child, DependsOnID: parent, Type: publicops.DepBlocks}}, + {"grandchild blocks on its grandparent", publicops.DependencyEdge{IssueID: grandchild, DependsOnID: parent, Type: publicops.DepBlocks}}, + {"grandchild parent-child to its grandparent", publicops.DependencyEdge{IssueID: grandchild, DependsOnID: parent, Type: publicops.DepParentChild}}, + {"child relates to its parent", publicops.DependencyEdge{IssueID: child, DependsOnID: parent, Type: publicops.DepRelated}}, + } { + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{refused.edge}, + }) + var dotted *publicops.DottedChildDependencyError + if !errors.As(err, &dotted) { + t.Errorf("%s: error = %v, want *DottedChildDependencyError", refused.name, err) + continue + } + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("%s: error = %v, want it to match ErrValidation", refused.name, err) + } + if dotted.IssueID != refused.edge.IssueID || dotted.DependsOnID != refused.edge.DependsOnID { + t.Errorf("%s: refusal names %s -> %s, want %s -> %s", refused.name, + dotted.IssueID, dotted.DependsOnID, refused.edge.IssueID, refused.edge.DependsOnID) + } + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, child, grandchild) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: grandchild, DependsOnID: child, Type: publicops.DepParentChild}, + {IssueID: sibling, DependsOnID: child, Type: publicops.DepBlocks}, + }, + }); err != nil { + t.Fatalf("the immediate parent-child edge and a sibling edge: %v", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", grandchild, child, string(publicops.DepParentChild), 1) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", sibling, child, 1) + + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: grandchild, DependsOnID: child, Type: publicops.DepBlocks}}, + }) + var dotted *publicops.DottedChildDependencyError + if !errors.As(err, &dotted) || !errors.Is(err, publicops.ErrValidation) { + t.Errorf("blocks on a parent whose parent-child edge is stored: error = %v, want *DottedChildDependencyError matching ErrValidation", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", grandchild, child, string(publicops.DepParentChild), 1) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", grandchild, child, 1) +} diff --git a/backend/conformance/role_bundle_cases.go b/backend/conformance/role_bundle_cases.go index 27f0d762f..0555b19a5 100644 --- a/backend/conformance/role_bundle_cases.go +++ b/backend/conformance/role_bundle_cases.go @@ -61,6 +61,7 @@ var roleContractCases = []roleContract{ RunBatchApplyUpdateItemsRefuseATemplate, RunBatchApplySplicesTheMetadataOfATemplateItCreates, RunBatchApplyCloseItemsAnswerToTheCloseGuards, + RunBatchApplyRefusesADottedChildGatedOnItsOwnParent, ), roleCases("BatchCloser", "BatchCloser()", oncePerRole, @@ -301,6 +302,7 @@ var roleContractCases = []roleContract{ RunDependencyEditorAcceptsADiamond, RunDependencyEditorGateScopeFollowsTheEdgeType, RunDependencyEditorAcceptsBlockingAcrossIssueTypes, + RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent, ), // The accessor named here is not an accessor at all, alone among these diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index d808cbd5d..7d1742cef 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -676,7 +676,6 @@ go_test( "dep_test.go", "dep_warning_test.go", "dependency_hierarchy_embedded_test.go", - "dependency_hierarchy_test.go", "diff_embedded_test.go", "directory_flag_test.go", "doctor_backend_guard_test.go", diff --git a/cmd/bd/batch.go b/cmd/bd/batch.go index 01c7898bb..99e8b76e1 100644 --- a/cmd/bd/batch.go +++ b/cmd/bd/batch.go @@ -15,6 +15,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" ) // Scope note: @@ -417,27 +418,14 @@ func runBatchOp(ctx context.Context, tx storage.Transaction, op batchOp) (batchO return result, nil case "dep.add": - if len(op.args) < 2 { - return result, fmt.Errorf("dep add requires ") - } - from, to := op.args[0], op.args[1] - depType := "blocks" - if len(op.args) >= 3 { - depType = op.args[2] - } - dt := types.DependencyType(depType) - if !dt.IsValid() { - return result, fmt.Errorf("dep add: invalid dependency type %q", depType) - } - dep := &types.Dependency{ - IssueID: from, - DependsOnID: to, - Type: dt, + dep, err := batchDepAddEdge(op.args) + if err != nil { + return result, err } if err := tx.AddDependency(ctx, dep, actorName); err != nil { return result, err } - result.Target = fmt.Sprintf("%s->%s", from, to) + result.Target = fmt.Sprintf("%s->%s", dep.IssueID, dep.DependsOnID) return result, nil case "dep.remove": @@ -454,6 +442,38 @@ func runBatchOp(ctx context.Context, tx storage.Transaction, op batchOp) (batchO return result, fmt.Errorf("internal: unhandled batch op %q", op.cmd) } +// batchDepAddEdge builds the edge a `dep add [type]` line +// asks for. Both backends' dispatch switches call it, so the default type, the +// arity and type errors, and the dotted-id hierarchy rule cannot drift between +// them. +// Neither backend writes the edge through the DependencyEditor role that +// enforces that rule (storage.Transaction.AddDependency and the unit of work's +// AddDependencies verb do not), so batch asks the role's rule directly, the +// way bd link does: a script line `dep add bd-abc.1 bd-abc` is refused, and +// rolls the batch back, exactly as `bd dep add bd-abc.1 bd-abc` is. +func batchDepAddEdge(args []string) (*types.Dependency, error) { + if len(args) < 2 { + return nil, fmt.Errorf("dep add requires ") + } + from, to := args[0], args[1] + depType := "blocks" + if len(args) >= 3 { + depType = args[2] + } + dt := types.DependencyType(depType) + if !dt.IsValid() { + return nil, fmt.Errorf("dep add: invalid dependency type %q", depType) + } + if err := publicops.CheckDottedChildDependency(from, to, dt); err != nil { + return nil, err + } + return &types.Dependency{ + IssueID: from, + DependsOnID: to, + Type: dt, + }, nil +} + // parseUpdateKVs walks a slice of "key=value" tokens and builds the updates // map accepted by storage.Transaction.UpdateIssue. Only a small, documented // subset of fields is allowed — anything else is a hard error so typos in diff --git a/cmd/bd/batch_parity_test.go b/cmd/bd/batch_parity_test.go index f150c845b..d50c4d171 100644 --- a/cmd/bd/batch_parity_test.go +++ b/cmd/bd/batch_parity_test.go @@ -259,6 +259,77 @@ func assertBatchParity(t *testing.T, classic, proxied batchParityOutcome) { } } +// TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent pins the +// dotted-id hierarchy rule on a batched `dep add`. Neither backend writes that +// edge through the DependencyEditor role that enforces the rule, so batch asks +// the rule itself (batchDepAddEdge). Both backends must refuse bd-abc.1 -> +// bd-abc with the sentence `bd dep add` prints, name the line, and roll the +// whole batch back, while the one edge the rule allows — parent-child to the +// immediate parent — still lands. +func TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + + type outcome struct { + refusedCode int + refusalReported bool + rolledBack bool + edgesAfterRefusal int + allowedCode int + edgesAfterAllowed int + } + outcomes := make(map[string]outcome, 2) + + for _, env := range newCrossModeEnvs(t, bd, "bdc", "bdp") { + var got outcome + + parent := env.create(t, "Dotted parent") + // An explicit dotted id stores no parent-child edge (only --parent + // does), so every edge counted below is one a batch wrote. + child := env.create(t, "Dotted child", "--id", parent+".1", "--priority", "2") + + // Line 1 is a valid write the refusal on line 2 must take back with it. + script := fmt.Sprintf("update %s priority=1\ndep add %s %s\n", child, child, parent) + stdout, stderr, code := env.runStdin(t, script, "batch") + // The failing line is named the way any failing line is, around the + // sentence `bd dep add` prints for the same edge. + refusal := fmt.Sprintf("line 2 (dep add %s %s): cannot add dependency: %s is already a child of %s.", + child, parent, child, parent) + got.refusedCode = code + got.refusalReported = strings.Contains(stdout+stderr, refusal) + got.rolledBack = env.show(t, child).Priority == 2 + got.edgesAfterRefusal = len(env.depList(t, child)) + if got.refusedCode == 0 || !got.refusalReported { + t.Errorf("[%s] batch exit=%d, want non-zero and %q\nstdout:\n%s\nstderr:\n%s", + env.mode, code, refusal, stdout, stderr) + } + + stdout, stderr, code = env.runStdin(t, fmt.Sprintf("dep add %s %s parent-child\n", child, parent), "batch") + got.allowedCode = code + if code != 0 { + t.Fatalf("[%s] batch parent-child dep add failed with exit %d\nstdout:\n%s\nstderr:\n%s", env.mode, code, stdout, stderr) + } + got.edgesAfterAllowed = len(env.depList(t, child)) + + outcomes[env.mode] = got + + if !got.rolledBack { + t.Errorf("[%s] the refused line did not roll back line 1's priority write", env.mode) + } + if got.edgesAfterRefusal != 0 { + t.Errorf("[%s] the refused batch left %d edges on the child, want 0", env.mode, got.edgesAfterRefusal) + } + if got.edgesAfterAllowed != 1 { + t.Errorf("[%s] batch parent-child dep add: %d edges on the child, want 1", env.mode, got.edgesAfterAllowed) + } + } + + if outcomes["classic"] != outcomes["proxied"] { + t.Errorf("cross-mode divergence:\nclassic=%+v\nproxied=%+v", outcomes["classic"], outcomes["proxied"]) + } +} + // depList reads the dependency records of one issue as a flat array, the shape // `bd dep list --json` documents. func (e crossModeEnv) depList(t *testing.T, id string) []map[string]any { diff --git a/cmd/bd/batch_proxied_server.go b/cmd/bd/batch_proxied_server.go index 99ccb890e..cb666214d 100644 --- a/cmd/bd/batch_proxied_server.go +++ b/cmd/bd/batch_proxied_server.go @@ -161,22 +161,9 @@ func runBatchOpUOW(ctx context.Context, uw uow.UnitOfWork, op batchOp) (batchOpR return result, nil case "dep.add": - if len(op.args) < 2 { - return result, fmt.Errorf("dep add requires ") - } - from, to := op.args[0], op.args[1] - depType := "blocks" - if len(op.args) >= 3 { - depType = op.args[2] - } - dt := types.DependencyType(depType) - if !dt.IsValid() { - return result, fmt.Errorf("dep add: invalid dependency type %q", depType) - } - dep := &types.Dependency{ - IssueID: from, - DependsOnID: to, - Type: dt, + dep, err := batchDepAddEdge(op.args) + if err != nil { + return result, err } // AddDependencies (not the single-edge AddDependency) because it lands // each edge in the plane its own SOURCE lives in, which is the routing @@ -198,7 +185,7 @@ func runBatchOpUOW(ctx context.Context, uw uow.UnitOfWork, op batchOp) (batchOpR if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actorName, domain.BulkAddDepsOpts{}); err != nil { return result, err } - result.Target = fmt.Sprintf("%s->%s", from, to) + result.Target = fmt.Sprintf("%s->%s", dep.IssueID, dep.DependsOnID) return result, nil case "dep.remove": diff --git a/cmd/bd/batch_test.go b/cmd/bd/batch_test.go index 894c29010..834bd49f9 100644 --- a/cmd/bd/batch_test.go +++ b/cmd/bd/batch_test.go @@ -1,9 +1,13 @@ package main import ( + "errors" "reflect" "strings" "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" ) func TestTokenizeBatchLine(t *testing.T) { @@ -261,6 +265,91 @@ func TestParseUpdateKVs(t *testing.T) { } } +// TestBatchDepAddEdge pins the edge a `dep add` line builds on both backends, +// and that the line asks the dotted-id hierarchy rule before either backend +// writes: the refusal is the role's own typed error, so a batch prints the +// sentence `bd dep add` prints and rolls back on it. +func TestBatchDepAddEdge(t *testing.T) { + tooLong := strings.Repeat("x", types.MaxDependencyTypeLen+1) + tests := []struct { + name string + args []string + want *types.Dependency + wantErr string + wantDotted bool + }{ + { + name: "default type is blocks", + args: []string{"bd-1", "bd-2"}, + want: &types.Dependency{IssueID: "bd-1", DependsOnID: "bd-2", Type: types.DepBlocks}, + }, + { + name: "explicit type", + args: []string{"bd-1", "bd-2", "related"}, + want: &types.Dependency{IssueID: "bd-1", DependsOnID: "bd-2", Type: types.DepRelated}, + }, + { + name: "missing to-id", + args: []string{"bd-1"}, + wantErr: "dep add requires ", + }, + { + name: "invalid type", + args: []string{"bd-1", "bd-2", tooLong}, + wantErr: `dep add: invalid dependency type "` + tooLong + `"`, + }, + { + name: "dotted child gated on its own parent", + args: []string{"bd-abc.1", "bd-abc"}, + wantDotted: true, + }, + { + name: "any explicit type up the tree, not only blocking ones", + args: []string{"bd-abc.1", "bd-abc", "related"}, + wantDotted: true, + }, + { + name: "parent-child past the immediate parent", + args: []string{"bd-abc.1.2", "bd-abc", "parent-child"}, + wantDotted: true, + }, + { + name: "parent-child to the immediate parent is the hierarchy itself", + args: []string{"bd-abc.1", "bd-abc", "parent-child"}, + want: &types.Dependency{IssueID: "bd-abc.1", DependsOnID: "bd-abc", Type: types.DepParentChild}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := batchDepAddEdge(tt.args) + switch { + case tt.wantDotted: + var dotted *publicops.DottedChildDependencyError + if !errors.As(err, &dotted) { + t.Fatalf("batchDepAddEdge(%q) = %+v, %v; want *DottedChildDependencyError", tt.args, got, err) + } + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("refusal %v does not match ErrValidation", err) + } + if dotted.IssueID != tt.args[0] || dotted.DependsOnID != tt.args[1] { + t.Errorf("refusal names %s -> %s, want %s -> %s", dotted.IssueID, dotted.DependsOnID, tt.args[0], tt.args[1]) + } + case tt.wantErr != "": + if err == nil || err.Error() != tt.wantErr { + t.Fatalf("batchDepAddEdge(%q) err = %v, want %q", tt.args, err, tt.wantErr) + } + default: + if err != nil { + t.Fatalf("batchDepAddEdge(%q): %v", tt.args, err) + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("batchDepAddEdge(%q) = %+v, want %+v", tt.args, got, tt.want) + } + } + }) + } +} + func TestBatchCmd_Registered(t *testing.T) { // Ensure 'bd batch' is wired into rootCmd with the correct group. cmd, _, err := rootCmd.Find([]string{"batch"}) diff --git a/cmd/bd/dep.go b/cmd/bd/dep.go index e77e1e1c8..06d7ffe49 100644 --- a/cmd/bd/dep.go +++ b/cmd/bd/dep.go @@ -213,41 +213,6 @@ func resolveUnresolvedDepTarget(sourceID, dependsOnArg string, resolveErr error) return "", fmt.Errorf("resolving dependency ID %s: %v", dependsOnArg, resolveErr) } -// isChildOf returns true if childID is a hierarchical child of parentID. -// For example, "bd-abc.1" is a child of "bd-abc", and "bd-abc.1.2" is a child of "bd-abc.1". -func isChildOf(childID, parentID string) bool { - _, isAncestor := hierarchicalParentRelation(childID, parentID) - return isAncestor -} - -func hierarchicalParentRelation(childID, targetID string) (immediateParent string, isAncestor bool) { - // A child ID has the format "parentID.N" or "parentID.N.M" etc. - // Use ParseHierarchicalID to get the actual parent - _, actualParentID, depth := types.ParseHierarchicalID(childID) - if depth == 0 { - return "", false // Not a hierarchical ID - } - // Check if the immediate parent matches - if actualParentID == targetID { - return actualParentID, true - } - // Also check if targetID is an ancestor (e.g., "bd-abc" is an ancestor of "bd-abc.1.2") - return actualParentID, strings.HasPrefix(childID, targetID+".") -} - -// isDisallowedHierarchicalDependency reports whether an explicit dependency -// conflicts with hierarchy encoded in a dotted issue ID. The one allowed match -// is a parent-child edge to the immediate dotted-ID parent; blocking and other -// edge types to any parent/ancestor, plus parent-child edges to higher ancestors, -// remain rejected. -func isDisallowedHierarchicalDependency(fromID, toID string, depType types.DependencyType) bool { - immediateParent, isAncestor := hierarchicalParentRelation(fromID, toID) - if !isAncestor { - return false - } - return depType != types.DepParentChild || toID != immediateParent -} - var depCmd = &cobra.Command{ Use: "dep [issue-id]", GroupID: "deps", @@ -312,10 +277,6 @@ Examples: } defer toCleanup() - if isDisallowedHierarchicalDependency(fromID, toID, types.DepBlocks) { - return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", fromID, toID) - } - opsCtx, err := issueOpsContext(ctx) if err != nil { return HandleErrorRespectJSON("%v", err) @@ -498,9 +459,8 @@ Examples: } dt := canonicalDependencyType(types.DependencyType(depType)) - if isDisallowedHierarchicalDependency(fromID, toID, dt) { - return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", fromID, toID) - } + // The dotted-id hierarchy refusal is the role's + // (issueops.CheckDottedChildDependency), raised by AddDependencies below. if err := validateDependencyType(dt); err != nil { return HandleErrorRespectJSON("%v", err) @@ -827,7 +787,9 @@ func validateBulkDepEdges(ctx context.Context, edges []bulkDepEdge) ([]bulkDepEd current.DependsOnID = toID } - if isDisallowedHierarchicalDependency(current.IssueID, current.DependsOnID, current.Type) { + // The role refuses this edge too; asking the library rule here only lets + // the bulk report name every offending line before anything is written. + if issueops.IsDottedChildDependency(current.IssueID, current.DependsOnID, current.Type) { errs = append(errs, fmt.Sprintf("line %d: cannot add dependency: %s is already a child of %s", edge.Line, current.IssueID, current.DependsOnID)) resolved = append(resolved, current) continue diff --git a/cmd/bd/dep_proxied_server.go b/cmd/bd/dep_proxied_server.go index aee6b0306..86e10a1dd 100644 --- a/cmd/bd/dep_proxied_server.go +++ b/cmd/bd/dep_proxied_server.go @@ -177,10 +177,6 @@ func runDepBlocksProxiedServer(cmd *cobra.Command, ctx context.Context, blockerI return HandleErrorRespectJSON("%v", err) } - if isDisallowedHierarchicalDependency(blockedID, blockerID, types.DepBlocks) { - return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", blockedID, blockerID) - } - noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check") edge := issueops.DependencyEdge{IssueID: blockedID, DependsOnID: blockerID, Type: types.DepBlocks} @@ -247,9 +243,6 @@ func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri toID = dependsOnArg dt := canonicalDependencyType(types.DependencyType(depType)) - if isDisallowedHierarchicalDependency(fromID, toID, dt) { - return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", fromID, toID) - } if err := validateDependencyType(dt); err != nil { return HandleErrorRespectJSON("%v", err) @@ -299,7 +292,7 @@ func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, default depEdges := make([]issueops.DependencyEdge, 0, len(edges)) for _, edge := range edges { - if isDisallowedHierarchicalDependency(edge.IssueID, edge.DependsOnID, edge.Type) { + if issueops.IsDottedChildDependency(edge.IssueID, edge.DependsOnID, edge.Type) { return HandleErrorRespectJSON("line %d: cannot add dependency: %s is already a child of %s", edge.Line, edge.IssueID, edge.DependsOnID) } if strings.HasPrefix(edge.DependsOnID, "external:") { diff --git a/cmd/bd/dep_test.go b/cmd/bd/dep_test.go index 188e1309e..1f8e23db8 100644 --- a/cmd/bd/dep_test.go +++ b/cmd/bd/dep_test.go @@ -1080,88 +1080,6 @@ func TestTreeNodeJSONIncludesEdgeFromParent(t *testing.T) { // These tests serve as regression tests ensuring the storage layer // continues to provide user-friendly error messages. -func TestIsChildOf(t *testing.T) { - tests := []struct { - name string - childID string - parentID string - want bool - }{ - // Positive cases: should be detected as child - { - name: "direct child", - childID: "bd-abc.1", - parentID: "bd-abc", - want: true, - }, - { - name: "grandchild", - childID: "bd-abc.1.2", - parentID: "bd-abc", - want: true, - }, - { - name: "nested grandchild direct parent", - childID: "bd-abc.1.2", - parentID: "bd-abc.1", - want: true, - }, - { - name: "deeply nested child", - childID: "bd-abc.1.2.3", - parentID: "bd-abc", - want: true, - }, - - // Negative cases: should NOT be detected as child - { - name: "same ID", - childID: "bd-abc", - parentID: "bd-abc", - want: false, - }, - { - name: "not a child - unrelated IDs", - childID: "bd-xyz", - parentID: "bd-abc", - want: false, - }, - { - name: "not a child - sibling", - childID: "bd-abc.2", - parentID: "bd-abc.1", - want: false, - }, - { - name: "reversed - parent is not child of child", - childID: "bd-abc", - parentID: "bd-abc.1", - want: false, - }, - { - name: "prefix but not hierarchical", - childID: "bd-abcd", - parentID: "bd-abc", - want: false, - }, - { - name: "not hierarchical ID", - childID: "bd-abc", - parentID: "bd-xyz", - want: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := isChildOf(tt.childID, tt.parentID) - if got != tt.want { - t.Errorf("isChildOf(%q, %q) = %v, want %v", tt.childID, tt.parentID, got, tt.want) - } - }) - } -} - // TestDepRoutedTargetOpensReadOnly is the regression guard for the dep/link // target-resolution invariant: a cross-rig dependency target is resolved by ID // only, so resolveIDWithRouting must open the routed foreign store read-only, diff --git a/cmd/bd/dependency_hierarchy_test.go b/cmd/bd/dependency_hierarchy_test.go deleted file mode 100644 index c50be2e29..000000000 --- a/cmd/bd/dependency_hierarchy_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "testing" - - "github.com/steveyegge/beads/internal/types" -) - -func TestIsDisallowedHierarchicalDependency(t *testing.T) { - tests := []struct { - name string - fromID string - toID string - depType types.DependencyType - want bool - }{ - { - name: "immediate parent-child allowed", - fromID: "bd-root.1.2", - toID: "bd-root.1", - depType: types.DepParentChild, - want: false, - }, - { - name: "immediate parent blocks rejected", - fromID: "bd-root.1.2", - toID: "bd-root.1", - depType: types.DepBlocks, - want: true, - }, - { - name: "grandparent parent-child rejected", - fromID: "bd-root.1.2", - toID: "bd-root", - depType: types.DepParentChild, - want: true, - }, - { - name: "unrelated target allowed", - fromID: "bd-root.1.2", - toID: "bd-other", - depType: types.DepBlocks, - want: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := isDisallowedHierarchicalDependency(tt.fromID, tt.toID, tt.depType) - if got != tt.want { - t.Fatalf("isDisallowedHierarchicalDependency(%q, %q, %q) = %v, want %v", tt.fromID, tt.toID, tt.depType, got, tt.want) - } - }) - } -} diff --git a/cmd/bd/graph_apply.go b/cmd/bd/graph_apply.go index 9a52f1415..407dae867 100644 --- a/cmd/bd/graph_apply.go +++ b/cmd/bd/graph_apply.go @@ -143,7 +143,7 @@ type GraphApplyDryRunRow struct { ParentID string `json:"parent_id,omitempty"` } -const graphApplyDryRunTransactionValidationNote = "dry-run validates the graph structure only; live create may still reject parent-child blocking paths after resolving stored dependencies" +const graphApplyDryRunTransactionValidationNote = "dry-run validates the graph structure only; live create may still reject parent-child blocking paths after resolving stored dependencies, or an edge that gates a dotted-id child on its own ancestor" // Known-field sets list the JSON keys recognized on each plan struct; unknown // keys warn about schema typos. Derived from json tags so they can't drift. (GH#3367) diff --git a/cmd/bd/link.go b/cmd/bd/link.go index a05be924b..2ad45f829 100644 --- a/cmd/bd/link.go +++ b/cmd/bd/link.go @@ -8,6 +8,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/issueops" ) var linkCmd = &cobra.Command{ @@ -63,8 +64,10 @@ Examples: defer toCleanup() dt := types.DependencyType(depType) - if isDisallowedHierarchicalDependency(fromID, toID, dt) { - return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", fromID, toID) + // bd link writes through the store's own dependency verb rather than + // the DependencyEditor role, so it asks the role's rule directly. + if err := issueops.CheckDottedChildDependency(fromID, toID, dt); err != nil { + return HandleErrorRespectJSON("%v", err) } if !dt.IsValid() { diff --git a/cmd/bd/link_proxied_server.go b/cmd/bd/link_proxied_server.go index aef888968..c3a4c05af 100644 --- a/cmd/bd/link_proxied_server.go +++ b/cmd/bd/link_proxied_server.go @@ -10,6 +10,7 @@ import ( "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/issueops" ) func runLinkProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { @@ -18,8 +19,8 @@ func runLinkProxiedServer(cmd *cobra.Command, ctx context.Context, args []string depType, _ := cmd.Flags().GetString("type") dt := types.DependencyType(depType) - if isDisallowedHierarchicalDependency(id1, id2, dt) { - return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", id1, id2) + if err := issueops.CheckDottedChildDependency(id1, id2, dt); err != nil { + return HandleErrorRespectJSON("%v", err) } if !dt.IsValid() { diff --git a/internal/httpapi/batch_apply_test.go b/internal/httpapi/batch_apply_test.go index 824775f21..3c2c9c5c2 100644 --- a/internal/httpapi/batch_apply_test.go +++ b/internal/httpapi/batch_apply_test.go @@ -889,6 +889,19 @@ func TestApplyBatchMapsTheRolesTypedRefusalsOntoTheDocumentedCodes(t *testing.T) wantStatus: http.StatusNotFound, wantCode: "not_found", }, + { + // The dotted-id hierarchy rule is request validation (it unwraps to + // ErrValidation), never the hierarchy CONFLICT's dependency_cycle: + // it is decided from the two resolved ids, ahead of every check that + // reads the stored graph, so even a child whose parent-child edge IS + // stored gets this 400, with no hierarchy members to describe. + name: "a dotted child gated on its own parent", + err: itemErr(0, issueops.ItemDepAdd, "", "bd-1.1", + &issueops.DottedChildDependencyError{IssueID: "bd-1.1", DependsOnID: "bd-1", Type: issueops.DepBlocks}), + wantStatus: http.StatusBadRequest, + wantCode: "invalid_argument", + wantParam: "items", + }, { name: "the workspace's own validation", err: itemErr(0, issueops.ItemCreate, "", "", storage.ErrValidation), diff --git a/internal/httpapi/dependency_edit_test.go b/internal/httpapi/dependency_edit_test.go index 6761969ac..96be92261 100644 --- a/internal/httpapi/dependency_edit_test.go +++ b/internal/httpapi/dependency_edit_test.go @@ -564,6 +564,20 @@ func TestAddDependenciesMapsTheGraphsTypedRefusals(t *testing.T) { wantCode: CodeInvalidArgument, wantMembers: map[string]any{"param": "edges[0].depends_on_id"}, }, + { + // The dotted-id hierarchy rule (issueops.CheckDottedChildDependency) + // is the role's validation, so it is the 400 below and never the + // hierarchy conflict's dependency_cycle members. + name: "a dotted child gated on its own parent is a 400 on edges", + body: oneEdge, + err: &issueops.DottedChildDependencyError{ + IssueID: "bd-1.1", DependsOnID: "bd-1", Type: issueops.DepBlocks, + }, + wantStatus: http.StatusBadRequest, + wantCode: CodeInvalidArgument, + wantMembers: map[string]any{"param": "edges"}, + absentMembers: []string{"issue_id", "blocker_id", "blocker_is_ancestor"}, + }, { name: "the role's own validation refusal is a 400 on edges", body: oneEdge, diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index f62181bf3..7465f20b6 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -4277,6 +4277,9 @@ paths: or a payload its `kind` does not name, a `create` with no `title`, a duplicate `key`, a `Ref` with neither `key` nor `id` or with both, a `dep_add` with an unstorable `type` or pointing a row at ITSELF, a + `dep_add` from a dotted-id child to one of its own ancestors + (anything but the parent-child edge to its IMMEDIATE parent, judged + once the item's refs resolve and carrying `param` `items`), a `waits-for` gate outside its two values, an item a workspace's own validation refuses, and an edge endpoint that names nothing this database can see. An explicit `create.id` that already names a @@ -4396,7 +4399,9 @@ paths: and `blocker_is_ancestor`. They may come from the per-edge probe or from the END GATE, which is the one place an edge that is legal on its own and illegal in the graph this request built is caught. - Neither has a force bypass. + Neither has a force bypass. A `dep_add` from a dotted-id child to an + ancestor its own id names is neither: it is a `400` + `invalid_argument`, as on that operation. `already_exists` is a `create` item whose EXPLICIT `id` already @@ -5598,13 +5603,19 @@ paths: is empty after trimming, longer than 256 bytes or carrying control characters, an empty or over-long `edges` array, a blank or over-long endpoint id, an unstorable `type`, an edge that points an - issue at ITSELF, or an edge endpoint that names nothing this - database can see. Nothing is written in any of these cases. + issue at ITSELF, an edge from a dotted-id child to one of its own + ancestors (anything but the parent-child edge to its IMMEDIATE + parent), or an edge endpoint that names nothing this database can + see. Nothing is written in any of these cases. A self-dependency is a `400` rather than a `409` because it is request-intrinsic: it is invalid whatever the graph holds, so it is - a refusal of a VALUE and not a statement about state. An endpoint + a refusal of a VALUE and not a statement about state. The dotted-id + child's edge is a `400` for the same reason, carrying `param` + `edges`: the two ids decide it before the graph is read, so even a + child whose parent-child edge is already stored gets this `400`, + never the `409` hierarchy refusal or `dependency_exists`. An endpoint that names nothing is a `400` rather than a `404` for `POST /v0/beads/issues:batchCreate`'s reason: the refusal is about the request BODY, and there is no id in the path to have missed. @@ -5636,6 +5647,11 @@ paths: Neither has a force bypass. The recovery for both is to rethink the edge, which is why they are one status and not a retry. + + + An edge from a dotted-id child to an ancestor its own id names is + neither: it is a `400` `invalid_argument`, decided from the two ids + before the graph is read. x-bd-codes: [dependency_cycle, dependency_exists] content: application/problem+json: diff --git a/internal/httpclient/dependencyeditor.go b/internal/httpclient/dependencyeditor.go index a94a38d89..dd1c53222 100644 --- a/internal/httpclient/dependencyeditor.go +++ b/internal/httpclient/dependencyeditor.go @@ -135,5 +135,9 @@ func checkEdge(i int, edge issueops.DependencyEdge) error { case edge.IssueID == edge.DependsOnID: return fmt.Errorf("%s: %w", edge.IssueID, issueops.ErrSelfDependency) } - return nil + // The dotted-id hierarchy rule, for the self-dependency check's reason: the + // server refuses it as a 400 that arrives here as a bare ErrValidation, + // while the role promises the typed *DottedChildDependencyError. It is the + // library's own check, not a restatement. + return issueops.CheckDottedChildDependency(edge.IssueID, edge.DependsOnID, edge.Type) } diff --git a/internal/httpclient/served_batch_apply_test.go b/internal/httpclient/served_batch_apply_test.go index 1117c51b8..e7aa98872 100644 --- a/internal/httpclient/served_batch_apply_test.go +++ b/internal/httpclient/served_batch_apply_test.go @@ -265,6 +265,10 @@ func TestServedBatchApplyCloseItemsAnswerToTheCloseGuards(t *testing.T) { conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, t.Context(), newServedBatchApplyFixture(t, "hbacg")) } +func TestServedBatchApplyRefusesADottedChildGatedOnItsOwnParent(t *testing.T) { + conformance.RunBatchApplyRefusesADottedChildGatedOnItsOwnParent(t, t.Context(), newServedBatchApplyFixture(t, "hbadot")) +} + // TestServedBatchApplyStampsSpawnerIDOnlyWhenNamed wires the dep_add // HasSpawner/ThreadID lineage conformance case onto the http leg (S5): a // served default Config always advertises CapBatchApplyDepAddLineage (it is diff --git a/internal/httpclient/served_memories_deps_test.go b/internal/httpclient/served_memories_deps_test.go index 014f38ce3..5550f0b4b 100644 --- a/internal/httpclient/served_memories_deps_test.go +++ b/internal/httpclient/served_memories_deps_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/httpapi/apigen" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/issueops" ) @@ -389,6 +390,10 @@ func TestServedDependencyEditorAcceptsBlockingAcrossIssueTypes(t *testing.T) { conformance.RunDependencyEditorAcceptsBlockingAcrossIssueTypes(t, t.Context(), newServedDependencyEditorFixture(t, "hd32")) } +func TestServedDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t *testing.T) { + conformance.RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t, t.Context(), newServedDependencyEditorFixture(t, "hddot")) +} + func TestServedDependencyEditorGateScopeFollowsTheEdgeType(t *testing.T) { conformance.RunDependencyEditorGateScopeFollowsTheEdgeType(t, t.Context(), newServedDependencyEditorFixture(t, "hd33")) } @@ -433,3 +438,37 @@ func TestServedDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp(t *test func TestServedDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion(t *testing.T) { conformance.RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion(t, t.Context(), newServedDependencyEditorFixture(t, "hd41")) } + +// TestServedServerRefusesADottedChildGatedOnItsOwnParent sends the edge on the +// raw wire, past the client's own CheckDottedChildDependency, so what refuses +// it is the SERVER's role — the leg a non-bd HTTP caller (gc, curl) reaches. +// Before the rule moved into issueops only the CLI refused it, and this edge +// landed. +func TestServedServerRefusesADottedChildGatedOnItsOwnParent(t *testing.T) { + env := newServedEnv(t, "hddotw") + parent := env.prefix + "-dotted" + child := parent + ".1" + for _, id := range []string{parent, child} { + if err := env.createIssue(t.Context(), &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}, "seed"); err != nil { + t.Fatalf("seed %s: %v", id, err) + } + } + w, err := env.subject.roleWire("DependencyEditor") + if err != nil { + t.Fatalf("roleWire: %v", err) + } + _, err = w.AddDependencies(t.Context(), apigen.AddDependenciesRequest{ + Actor: "writer", + Edges: []apigen.DependencyEdge{{IssueId: child, DependsOnId: parent, Type: "blocks"}}, + }) + if !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("raw-wire child -> parent blocks: error = %v, want the server's ErrValidation refusal", err) + } + var n int + if err := env.queryScalar(t.Context(), "SELECT COUNT(*) FROM dependencies WHERE issue_id = ?", []any{child}, &n); err != nil { + t.Fatalf("count edges: %v", err) + } + if n != 0 { + t.Fatalf("%d edge(s) from %s landed; the server must refuse a dotted child gated on its own parent", n, child) + } +} diff --git a/internal/storage/dolt/batch_apply_contract_test.go b/internal/storage/dolt/batch_apply_contract_test.go index 8ead3a15b..5d009ca38 100644 --- a/internal/storage/dolt/batch_apply_contract_test.go +++ b/internal/storage/dolt/batch_apply_contract_test.go @@ -270,6 +270,11 @@ func TestBatchApplyContract(t *testing.T) { defer cancel() conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, ctx, fixture) }) + t.Run("RefusesADottedChildGatedOnItsOwnParent", func(t *testing.T) { + ctx, cancel := testContext(t) + defer cancel() + conformance.RunBatchApplyRefusesADottedChildGatedOnItsOwnParent(t, ctx, fixture) + }) } // newDoltBatchApplyFixture composes the frozen role kit with this backend's diff --git a/internal/storage/dolt/dependency_editor_contract_test.go b/internal/storage/dolt/dependency_editor_contract_test.go index f5fac1515..57167a4a4 100644 --- a/internal/storage/dolt/dependency_editor_contract_test.go +++ b/internal/storage/dolt/dependency_editor_contract_test.go @@ -259,6 +259,12 @@ func TestDependencyEditorAcceptsBlockingAcrossIssueTypes(t *testing.T) { conformance.RunDependencyEditorAcceptsBlockingAcrossIssueTypes(t, ctx, fixture) } +func TestDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "dotted") + defer cleanup() + conformance.RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t, ctx, fixture) +} + // newDoltDependencyEditorFixture composes the backend's role fixture kit with // the accessor under test. Every hook but the accessor comes from the kit, so // the seeding and scalar-query plumbing stays identical to the other roles'. diff --git a/internal/storage/embeddeddolt/batch_apply_contract_test.go b/internal/storage/embeddeddolt/batch_apply_contract_test.go index 9280f9acb..6d330a163 100644 --- a/internal/storage/embeddeddolt/batch_apply_contract_test.go +++ b/internal/storage/embeddeddolt/batch_apply_contract_test.go @@ -196,6 +196,9 @@ func TestBatchApplyContract(t *testing.T) { t.Run("CloseItemsAnswerToTheCloseGuards", func(t *testing.T) { conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, ctx, fixture) }) + t.Run("RefusesADottedChildGatedOnItsOwnParent", func(t *testing.T) { + conformance.RunBatchApplyRefusesADottedChildGatedOnItsOwnParent(t, ctx, fixture) + }) } // newEmbeddedBatchApplyFixture composes the frozen role kit with this backend's diff --git a/internal/storage/embeddeddolt/dependency_editor_contract_test.go b/internal/storage/embeddeddolt/dependency_editor_contract_test.go index 88335f2d7..d51e7edd2 100644 --- a/internal/storage/embeddeddolt/dependency_editor_contract_test.go +++ b/internal/storage/embeddeddolt/dependency_editor_contract_test.go @@ -261,6 +261,12 @@ func TestEmbeddedDependencyEditorAcceptsBlockingAcrossIssueTypes(t *testing.T) { conformance.RunDependencyEditorAcceptsBlockingAcrossIssueTypes(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "xtype")) } +func TestEmbeddedDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "dotted")) +} + // newEmbeddedDependencyEditorFixture composes the backend's role fixture kit // with the accessor under test. Every hook but the accessor comes from the kit, // so the seeding and scalar-query plumbing stays identical to the other roles'. diff --git a/internal/storage/issueops/batch_apply.go b/internal/storage/issueops/batch_apply.go index 1621e772e..0459110eb 100644 --- a/internal/storage/issueops/batch_apply.go +++ b/internal/storage/issueops/batch_apply.go @@ -352,6 +352,12 @@ func (r *applyBatchRun) applyDepAdd(ctx context.Context, tx *sql.Tx, index int, // bound to. The planner catches only the syntactically identical pair. return itemErr(fmt.Errorf("%w: %s", publicops.ErrSelfDependency, source)) } + // The dotted-id hierarchy rule DependencyEditor applies, on the RESOLVED + // ids: a key can name a row whose minted id is a dotted child, so the planner + // cannot decide this before the creates ran. + if err := publicops.CheckDottedChildDependency(source, target, item.Type); err != nil { + return itemErr(err) + } // THE CROSS-PLANE REFUSAL IS ABOUT ROWS THIS REQUEST CREATED, and only // those. The two planes hold their edges in different tables, so an edge // between a durable row and a wisp the same batch minted is one the batch diff --git a/internal/storage/issueops/dependency_editor.go b/internal/storage/issueops/dependency_editor.go index ec8cb46b1..d1c7fac46 100644 --- a/internal/storage/issueops/dependency_editor.go +++ b/internal/storage/issueops/dependency_editor.go @@ -21,6 +21,12 @@ import ( // self-edge otherwise trips the cycle check and reports the wrong refusal, and // SkipPerEdgeCycleCheck would skip it entirely. // +// The dotted-id hierarchy rule (publicops.CheckDottedChildDependency) is here +// for the same reason: it is decided from the request alone, and putting it in +// the shared validator is what makes every leg — dolt, embedded, the unit of +// work and the server behind httpapi — refuse a child gated on its own dotted +// parent, not only the CLI that used to check it before calling the role. +// // The type check is that there IS a type — non-empty, within the column's // length. It is deliberately not a membership test: the vocabulary is an open, // workspace-configurable set (see the Dep* constants), so refusing an unlisted @@ -43,6 +49,9 @@ func ValidateAddDependenciesRequest(request publicops.AddDependenciesRequest) er if edge.IssueID == edge.DependsOnID { return fmt.Errorf("%w: %s cannot depend on itself", domain.ErrSelfDependency, edge.IssueID) } + if err := publicops.CheckDottedChildDependency(edge.IssueID, edge.DependsOnID, edge.Type); err != nil { + return err + } } return nil } diff --git a/internal/storage/uow/batch_applier.go b/internal/storage/uow/batch_applier.go index b26025a5c..8562f63b7 100644 --- a/internal/storage/uow/batch_applier.go +++ b/internal/storage/uow/batch_applier.go @@ -461,6 +461,9 @@ func (r *uowApplyRun) applyDepAdd(ctx context.Context, index int, item *publicop if source == target { return itemErr(fmt.Errorf("%w: %s", publicops.ErrSelfDependency, source)) } + if err := publicops.CheckDottedChildDependency(source, target, item.Type); err != nil { + return itemErr(err) + } sourceWisp, sourceMine := r.planes[source] targetWisp, targetMine := r.planes[target] if sourceMine && targetMine && sourceWisp != targetWisp { diff --git a/internal/storage/uow/batch_apply_contract_test.go b/internal/storage/uow/batch_apply_contract_test.go index 2d8b4673d..edfa1af3d 100644 --- a/internal/storage/uow/batch_apply_contract_test.go +++ b/internal/storage/uow/batch_apply_contract_test.go @@ -166,6 +166,9 @@ func TestBatchApplyContract(t *testing.T) { t.Run("CloseItemsAnswerToTheCloseGuards", func(t *testing.T) { conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, ctx, fixture) }) + t.Run("RefusesADottedChildGatedOnItsOwnParent", func(t *testing.T) { + conformance.RunBatchApplyRefusesADottedChildGatedOnItsOwnParent(t, ctx, fixture) + }) } func newUOWBatchApplyFixture(t *testing.T, ctx context.Context, prefix string) conformance.BatchApplyFixture { diff --git a/internal/storage/uow/dependency_editor_contract_test.go b/internal/storage/uow/dependency_editor_contract_test.go index 855ec2521..3d2cc274a 100644 --- a/internal/storage/uow/dependency_editor_contract_test.go +++ b/internal/storage/uow/dependency_editor_contract_test.go @@ -66,6 +66,7 @@ func TestUOWDependencyEditorContract(t *testing.T) { {name: "AcceptsADiamond", run: conformance.RunDependencyEditorAcceptsADiamond}, {name: "GateScopeFollowsTheEdgeType", run: conformance.RunDependencyEditorGateScopeFollowsTheEdgeType}, {name: "AcceptsBlockingAcrossIssueTypes", run: conformance.RunDependencyEditorAcceptsBlockingAcrossIssueTypes}, + {name: "RefusesADottedChildGatedOnItsOwnParent", run: conformance.RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent}, } { t.Run(test.name, func(t *testing.T) { test.run(t, ctx, fixture) diff --git a/issueops/dependencyeditor.go b/issueops/dependencyeditor.go index f9b0683eb..16cfc1b5b 100644 --- a/issueops/dependencyeditor.go +++ b/issueops/dependencyeditor.go @@ -2,6 +2,8 @@ package issueops import ( "context" + "fmt" + "strings" "github.com/steveyegge/beads/internal/types" ) @@ -147,12 +149,20 @@ type RemoveDependencyResult struct { type DependencyEditor interface { // AddDependencies asserts every edge in the request as ONE durable act: // one transaction, one history entry. Any refused edge refuses the whole - // request and writes nothing — a self-dependency (ErrSelfDependency), a - // scheduling cycle (ErrDependencyCycle), a conflicting type on a pair that - // already has an edge (*DependencyTypeConflictError), a blocking edge that - // would gate an issue on its own ancestor or descendant - // (*DependencyHierarchyConflictError), or a SOURCE that does not exist - // (ErrDependencySourceNotFound). + // request and writes nothing — a self-dependency (ErrSelfDependency), an + // explicit edge from a dotted-id child to its own ancestor + // (*DottedChildDependencyError), a scheduling cycle (ErrDependencyCycle), + // a conflicting type on a pair that already has an edge + // (*DependencyTypeConflictError), a blocking edge that would gate an issue + // on its own ancestor or descendant (*DependencyHierarchyConflictError), + // or a SOURCE that does not exist (ErrDependencySourceNotFound). + // + // The dotted-child refusal is decided from the request alone, before any + // read, so it takes precedence over every refusal that reads stored rows: + // a child whose parent-child edge to that parent is already stored (the + // `bd create --parent` shape) is refused with *DottedChildDependencyError, + // which matches ErrValidation, not with the hierarchy or type conflict the + // stored edge would otherwise raise. // // A target's existence is checked only where the backend can see it. A // target may legitimately be an "external:" reference or an issue in @@ -188,3 +198,72 @@ type DependencyEditor interface { // missing edge is Removed false with a nil error, not ErrNotFound. RemoveDependency(ctx context.Context, req RemoveDependencyRequest) (RemoveDependencyResult, error) } + +// DottedChildDependencyError refuses an explicit edge from a dotted-id child to +// its own ancestor. The id already says "bd-abc.1 is under bd-abc": a child +// inherits its parent's completion through the hierarchy, so a blocking (or any +// other) explicit edge back up the tree either duplicates that structure or, for +// a blocking type, deadlocks it — the parent cannot close before the child, and +// the child would wait on the parent. +// +// The one edge it allows is the hierarchy itself: a parent-child edge to the +// IMMEDIATE dotted parent. A parent-child edge to a higher ancestor is refused +// too, because it would contradict the parent the id names. +// +// It unwraps to ErrValidation: the refusal is decidable from the two ids and +// the type alone, with no read, so it is a property of the request. +// +// The message is the sentence `bd dep add` already printed, kept verbatim, so +// it says "deadlock" whatever the type; Type is carried for callers that +// inspect the refusal and is not rendered. +type DottedChildDependencyError struct { + IssueID string + DependsOnID string + Type DependencyType +} + +func (e *DottedChildDependencyError) Error() string { + return fmt.Sprintf("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", + e.IssueID, e.DependsOnID) +} + +// Unwrap classifies the refusal as request validation. +func (e *DottedChildDependencyError) Unwrap() error { return ErrValidation } + +// IsDottedChildDependency reports whether an edge from issueID to dependsOnID +// of type depType is the dotted-id hierarchy conflict CheckDottedChildDependency +// refuses. It is exported for callers that phrase the refusal themselves (a +// bulk report naming the offending line); every role enforces it through +// CheckDottedChildDependency. +func IsDottedChildDependency(issueID, dependsOnID string, depType DependencyType) bool { + _, immediateParent, depth := types.ParseHierarchicalID(issueID) + if depth == 0 || dependsOnID == "" { + return false + } + if dependsOnID != immediateParent && !strings.HasPrefix(issueID, dependsOnID+".") { + return false + } + return depType != DepParentChild || dependsOnID != immediateParent +} + +// CheckDottedChildDependency is the ONE enforcement of the dotted-id hierarchy +// rule. Every DependencyEditor implementation applies it to each requested edge +// and every BatchApplier applies it to each dep_add item once its refs resolve, +// so `bd dep add`, an HTTP dependencies:add, and a batch apply (including +// `bd create --graph`'s own edges) refuse the same edge the same way. Two CLI +// paths that write an edge through a store verb instead of a role call it +// themselves: `bd link` and `bd batch`'s `dep add`. +// +// Other edge writers do not apply it yet, so they can still store an edge the +// roles refuse. The known ones are `bd relate`; the edges a create writes with +// its issue (`bd create --deps`/`--waits-for`, and Lifecycle.Create's ParentID, +// Dependencies and WaitsFor); `bd duplicate`, `bd supersede` and +// `bd duplicates --auto-merge`'s link and reparenting; and the tracker engine's +// createDependencies. The molecule, template and swarm writers have not been +// audited against it. bd-25s1wh tracks the gap. +func CheckDottedChildDependency(issueID, dependsOnID string, depType DependencyType) error { + if IsDottedChildDependency(issueID, dependsOnID, depType) { + return &DottedChildDependencyError{IssueID: issueID, DependsOnID: dependsOnID, Type: depType} + } + return nil +} diff --git a/issueops/issueops_external_test.go b/issueops/issueops_external_test.go index 4f12dffbc..fd8f81ce2 100644 --- a/issueops/issueops_external_test.go +++ b/issueops/issueops_external_test.go @@ -340,3 +340,58 @@ func (operationsProbe) Close(context.Context, issueops.CloseRequest) (issueops.C func (operationsProbe) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) { return issueops.ReopenResult{}, nil } + +// TestCheckDottedChildDependency pins the dotted-id hierarchy rule every +// DependencyEditor and BatchApplier enforces. It absorbs the CLI's former +// isChildOf / isDisallowedHierarchicalDependency tables. +func TestCheckDottedChildDependency(t *testing.T) { + for _, tt := range []struct { + name string + from string + to string + depType issueops.DependencyType + want bool + }{ + {"direct child blocks on parent", "bd-abc.1", "bd-abc", issueops.DepBlocks, true}, + {"grandchild blocks on grandparent", "bd-abc.1.2", "bd-abc", issueops.DepBlocks, true}, + {"grandchild blocks on immediate parent", "bd-abc.1.2", "bd-abc.1", issueops.DepBlocks, true}, + {"deeply nested child blocks on root", "bd-abc.1.2.3", "bd-abc", issueops.DepBlocks, true}, + {"child relates to parent", "bd-abc.1", "bd-abc", issueops.DepRelated, true}, + {"grandchild parent-child to grandparent", "bd-root.1.2", "bd-root", issueops.DepParentChild, true}, + {"immediate parent-child allowed", "bd-root.1.2", "bd-root.1", issueops.DepParentChild, false}, + {"same id", "bd-abc", "bd-abc", issueops.DepBlocks, false}, + {"unrelated ids", "bd-xyz", "bd-abc", issueops.DepBlocks, false}, + {"unrelated target from a dotted child", "bd-root.1.2", "bd-other", issueops.DepBlocks, false}, + {"sibling", "bd-abc.2", "bd-abc.1", issueops.DepBlocks, false}, + {"parent on its child", "bd-abc", "bd-abc.1", issueops.DepBlocks, false}, + {"prefix but not hierarchical", "bd-abcd", "bd-abc", issueops.DepBlocks, false}, + {"textual prefix of a dotted id is not an ancestor", "bd-abc.10", "bd-abc.1", issueops.DepBlocks, false}, + {"external target", "bd-abc.1", "external:bd-abc", issueops.DepBlocks, false}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := issueops.IsDottedChildDependency(tt.from, tt.to, tt.depType); got != tt.want { + t.Fatalf("IsDottedChildDependency(%q, %q, %q) = %v, want %v", tt.from, tt.to, tt.depType, got, tt.want) + } + err := issueops.CheckDottedChildDependency(tt.from, tt.to, tt.depType) + if !tt.want { + if err != nil { + t.Fatalf("CheckDottedChildDependency = %v, want nil", err) + } + return + } + var dotted *issueops.DottedChildDependencyError + if !errors.As(err, &dotted) || !errors.Is(err, issueops.ErrValidation) { + t.Fatalf("CheckDottedChildDependency = %v, want *DottedChildDependencyError matching ErrValidation", err) + } + if dotted.IssueID != tt.from || dotted.DependsOnID != tt.to || dotted.Type != tt.depType { + t.Fatalf("refusal = %#v, want the edge it refused", dotted) + } + // The CLI prints this sentence verbatim, so it is behaviour. + want := "cannot add dependency: " + tt.from + " is already a child of " + tt.to + + ". Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock" + if err.Error() != want { + t.Fatalf("message = %q, want %q", err.Error(), want) + } + }) + } +}