From 4103d985d13e018ffa151b488d3f6e8a6d8a1b06 Mon Sep 17 00:00:00 2001 From: matt wilkie Date: Thu, 23 Jul 2026 21:33:38 -0700 Subject: [PATCH] fix(create): reject explicit plan ids that already exist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An explicit node id colliding with a stored issue slipped through plan validation (which only caught intra-plan duplicates) into an insert path with upsert semantics — the atomic graph create silently rewrote the existing issue while reporting creation. The upsert behavior is inherited (bd create --id does the same today), but plans mint ids in bulk, so the exposure is much larger here. Add an explicit-ID collision preflight to the shared plan validation: - graphPlanConfig gains an issueExists probe; embedded supplies it from the store (GetIssue spans issues and wisps), proxied from the unit of work's per-table getters — bound to the caller's context, so the live proxied path probes inside the apply transaction and cannot race a concurrent create of the same id. Dry-run validates through the same probe. - Deliberately not overridable by --force: that flag vouches for a foreign prefix, not for destroying existing data. Also: reword the --mol-type rejection to point at the per-node mol_type field (the old text claimed plans don't carry molecule semantics, which the node field contradicts), and document the no-overwrite rule in the --graph plan supplement. Agent-Signature: claude-fable-5-xhigh on behalf of matt wilkie Co-Authored-By: Claude Fable 5 --- cmd/bd/create_input.go | 2 +- cmd/bd/create_proxied_server.go | 48 ++++++++++++++++--- cmd/bd/graph_apply.go | 47 ++++++++++++++++++- cmd/bd/graph_apply_test.go | 49 ++++++++++++++++++++ cmd/bd/help_supplements/create_graph_plan.md | 3 +- 5 files changed, 139 insertions(+), 10 deletions(-) diff --git a/cmd/bd/create_input.go b/cmd/bd/create_input.go index 4bc91f673..990eee72b 100644 --- a/cmd/bd/create_input.go +++ b/cmd/bd/create_input.go @@ -319,7 +319,7 @@ func rejectSingleIssueFlagsForGraph(cmd *cobra.Command) error { } } if cmd.Flags().Changed("mol-type") { - return HandleError("--mol-type is not valid with --graph (graph plans don't carry molecule semantics)") + return HandleError("--mol-type is not valid with --graph (set mol_type per node in the plan instead)") } return nil } diff --git a/cmd/bd/create_proxied_server.go b/cmd/bd/create_proxied_server.go index d10ec58c2..e38a370c0 100644 --- a/cmd/bd/create_proxied_server.go +++ b/cmd/bd/create_proxied_server.go @@ -2,7 +2,9 @@ package main import ( "context" + "database/sql" "encoding/json" + "errors" "fmt" "os" "sort" @@ -11,6 +13,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" @@ -384,11 +387,15 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput return HandleError("open unit of work: %v", err) } cctx, err := dryUW.ConfigUseCase().LoadCreateContext(ctx) - dryUW.Close(ctx) if err != nil { + dryUW.Close(ctx) return HandleError("load create context: %v", err) } - if _, err := validateProxiedGraphPlan(&plan, in, cctx); err != nil { + // Keep the UOW open through validation: the explicit-ID collision + // preflight reads through it. + _, err = validateProxiedGraphPlan(&plan, in, cctx, uowIssueExists(ctx, dryUW)) + dryUW.Close(ctx) + if err != nil { return HandleError("invalid graph plan: %v", err) } if err := emitGraphApplyDryRun(&plan, in.graphApplyOptions()); err != nil { @@ -414,8 +421,10 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput } // validateProxiedGraphPlan enforces a uniform storage class, so its - // resolved useWisp decides which table the whole plan routes to. - useWisp, err := validateProxiedGraphPlan(&plan, in, cctx) + // 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) } @@ -459,9 +468,10 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput // validateProxiedGraphPlan runs full plan validation for proxied-server mode: // shared plan checks, uniform storage class (proxied routes the whole plan to -// one table), and explicit-ID prefix checks against the server's config. The -// returned useWisp is the plan-wide table routing decision. -func validateProxiedGraphPlan(plan *GraphApplyPlan, in createInput, cctx domain.CreateContext) (useWisp bool, err error) { +// one table), explicit-ID prefix checks against the server's config, and the +// explicit-ID collision preflight through the unit of work's issue lookup. +// The returned useWisp is the plan-wide table routing decision. +func validateProxiedGraphPlan(plan *GraphApplyPlan, in createInput, cctx domain.CreateContext, issueExists func(id string) (bool, error)) (useWisp bool, err error) { cfg := graphPlanConfig{ customTypes: resolveProxiedCustomTypes(cctx.CustomTypes), // No YAML fallback for statuses — the server database is authoritative @@ -471,10 +481,34 @@ func validateProxiedGraphPlan(plan *GraphApplyPlan, in createInput, cctx domain. customStatuses: types.CustomStatusNames(cctx.CustomStatuses), dbPrefix: overlayYAMLPrefix(cctx.IssuePrefix), allowedPrefixes: cctx.AllowedPrefixes, + issueExists: issueExists, } return validateFullGraphPlan(plan, cfg, in.graphApplyOptions(), true) } +// uowIssueExists adapts a unit of work's issue lookups to the plan +// validator's explicit-ID collision probe, bound to the caller's context so +// in-transaction validation reads its own transaction. Issues and wisps share +// one ID space but the domain getters are per-table, so probe both. +func uowIssueExists(ctx context.Context, uw uow.UnitOfWork) func(id string) (bool, error) { + isNotFound := func(err error) bool { + return errors.Is(err, storage.ErrNotFound) || errors.Is(err, sql.ErrNoRows) + } + return func(id string) (bool, error) { + if _, err := uw.IssueUseCase().GetIssue(ctx, id); err == nil { + return true, nil + } else if !isNotFound(err) { + return false, err + } + if _, err := uw.IssueUseCase().GetWisp(ctx, id); err == nil { + return true, nil + } else if !isNotFound(err) { + return false, err + } + return false, nil + } +} + // graphApplyNodeIssue path (full issue-model parity with `bd create`). func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) (domain.GraphPlan, error) { opts := in.graphApplyOptions() diff --git a/cmd/bd/graph_apply.go b/cmd/bd/graph_apply.go index 1c0770178..473b51263 100644 --- a/cmd/bd/graph_apply.go +++ b/cmd/bd/graph_apply.go @@ -3,6 +3,7 @@ package main import ( "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -351,6 +352,17 @@ func createIssuesFromGraph(planFile string, dryRun bool, opts GraphApplyOptions) dbPrefix: dbPrefix, allowedPrefixes: allowedPrefixes, } + if store != nil { + cfg.issueExists = func(id string) (bool, error) { + if _, err := store.GetIssue(rootCtx, id); err != nil { + if errors.Is(err, storage.ErrNotFound) { + return false, nil + } + return false, err + } + return true, nil + } + } if _, err := validateFullGraphPlan(&plan, cfg, opts, false); err != nil { return HandleErrorRespectJSON("invalid graph plan: %v", err) } @@ -455,6 +467,10 @@ type graphPlanConfig struct { customStatuses []string dbPrefix string allowedPrefixes string + // issueExists probes whether an ID is already taken by a stored issue (or + // wisp, where the underlying lookup spans both tables). nil skips the + // explicit-ID collision preflight (no store access in the calling context). + issueExists func(id string) (bool, error) } // validateFullGraphPlan runs every plan-level check in one place so the @@ -470,7 +486,36 @@ func validateFullGraphPlan(plan *GraphApplyPlan, cfg graphPlanConfig, opts Graph if err != nil { return false, err } - return useWisp, validateGraphApplyExplicitIDPrefixes(plan, cfg.dbPrefix, cfg.allowedPrefixes, opts.Force) + if err := validateGraphApplyExplicitIDPrefixes(plan, cfg.dbPrefix, cfg.allowedPrefixes, opts.Force); err != nil { + return false, err + } + return useWisp, validateGraphApplyExplicitIDCollisions(plan, cfg.issueExists) +} + +// validateGraphApplyExplicitIDCollisions rejects plan nodes whose explicit id +// already belongs to a stored issue or wisp. The insert path upserts on a +// duplicate ID (matching `bd create --id`), which for an atomic graph create +// would silently rewrite the existing issue while reporting creation — a plan +// must fail fast instead. Deliberately not overridable by --force: that flag +// vouches for a foreign prefix, not for destroying existing data. Best-effort +// by transport: exists is nil where the calling context has no store access. +func validateGraphApplyExplicitIDCollisions(plan *GraphApplyPlan, exists func(id string) (bool, error)) error { + if exists == nil { + return nil + } + for _, node := range plan.Nodes { + if node.ID == "" { + continue + } + taken, err := exists(node.ID) + if err != nil { + return fmt.Errorf("checking explicit id %q (node %q): %w", node.ID, node.Key, err) + } + if taken { + return fmt.Errorf("explicit id %q (node %q) already exists; graph create will not overwrite an existing issue — drop the id to mint a new one, or update the existing issue instead", node.ID, node.Key) + } + } + return nil } func validateGraphApplyPlan(plan *GraphApplyPlan, customTypes, customStatuses []string, opts GraphApplyOptions) error { diff --git a/cmd/bd/graph_apply_test.go b/cmd/bd/graph_apply_test.go index e2063496d..63526e93b 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" + "fmt" "os" "reflect" "sort" @@ -741,6 +742,54 @@ func TestValidateGraphApplyPlanRejectsDuplicateExplicitIDs(t *testing.T) { } } +func TestValidateGraphApplyExplicitIDCollisions(t *testing.T) { + plan := &GraphApplyPlan{ + Nodes: []GraphApplyNode{ + {Key: "a", Title: "A", ID: "bd-taken"}, + {Key: "b", Title: "B"}, + }, + } + + t.Run("nil probe skips", func(t *testing.T) { + if err := validateGraphApplyExplicitIDCollisions(plan, nil); err != nil { + t.Fatalf("nil probe: want nil error, got %v", err) + } + }) + + t.Run("collision rejected with node context", func(t *testing.T) { + err := validateGraphApplyExplicitIDCollisions(plan, func(id string) (bool, error) { + return id == "bd-taken", nil + }) + if err == nil || !strings.Contains(err.Error(), "already exists") || + !strings.Contains(err.Error(), "bd-taken") || !strings.Contains(err.Error(), `"a"`) { + t.Fatalf("expected already-exists error naming id and node, got %v", err) + } + }) + + t.Run("free id passes and probe skips id-less nodes", func(t *testing.T) { + var probed []string + err := validateGraphApplyExplicitIDCollisions(plan, func(id string) (bool, error) { + probed = append(probed, id) + return false, nil + }) + if err != nil { + t.Fatalf("free id: want nil error, got %v", err) + } + if len(probed) != 1 || probed[0] != "bd-taken" { + t.Fatalf("want exactly the explicit id probed, got %v", probed) + } + }) + + t.Run("probe error propagates", func(t *testing.T) { + err := validateGraphApplyExplicitIDCollisions(plan, func(string) (bool, error) { + return false, fmt.Errorf("store offline") + }) + if err == nil || !strings.Contains(err.Error(), "store offline") { + t.Fatalf("expected probe error to propagate, got %v", err) + } + }) +} + func TestValidateGraphApplyPlanEdgeGateRules(t *testing.T) { twoNodes := []GraphApplyNode{ {Key: "gate", Title: "Gate"}, diff --git a/cmd/bd/help_supplements/create_graph_plan.md b/cmd/bd/help_supplements/create_graph_plan.md index b70cc4461..7fbf93155 100644 --- a/cmd/bd/help_supplements/create_graph_plan.md +++ b/cmd/bd/help_supplements/create_graph_plan.md @@ -48,7 +48,8 @@ Node notes: - `key` is a plan-local symbolic name; the result maps each key to the minted issue ID. `id` optionally pins an explicit issue ID instead (must match the - database prefix, like `bd create --id`). + database prefix, like `bd create --id`, and must not already exist — a plan + never overwrites an existing issue). - `parent_key` (a plan node key) or `parent_id` (an existing issue ID) adds a `parent-child` dependency on the created node. - `parent` and `estimate` are accepted aliases for `parent_key` and