beads/cmd/bd/create_atomic.go
Julian Knutsen 3ef94a084a
fix(create): commit issue and dependency edges in one transaction (#4731)
* fix(create): commit issue and dependency edges in one transaction

The sqlite concurrency audit (defect #3, MED) found that `bd create
--deps` commits the new issue in one transaction and then adds each
requested edge in its own transaction with warn-only error handling: a
dep-add hitting SQLITE_BUSY still exits 0 with valid JSON, leaving a
dep-less bead behind that is permanently READY, so an orchestrator
polling `bd ready` dispatches it before its prerequisites exist.
Red-team reproduction against a queued BEGIN IMMEDIATE lock holder
confirmed it empirically: the stock binary silently dropped edges in 6
of 13 forty-edge create races (five rounds committed 33/40, one 30/40,
all exit 0 with warnings only on stderr).

createIssueWithDeps now persists the create and every --parent/--deps/
--waits-for edge in one store transaction; any edge failure is fatal,
names the failing edge, and rolls back the create. Under the same race
the fixed binary went 20/20 rounds with all 40/40 edges committed and
zero warnings. Dolt server mode splits one logical transaction across
two SQL sessions (versioned vs dolt-ignored tables), so cross-tier
edges gained a target precheck on the session that owns the target
table, a cycle check over the merged two-session graph, and a scoped
FK suspension for wisp-source edges whose issue target is still
uncommitted on the other session.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(create-deps): repair regression test backend, close mixed-tier cycle gap, cut complexity

Maintainer review fixes for the create-time dependency atomicity PR.

- TestCreateDepsAtomicity initialized the removed `--backend sqlite`, so
  `go test ./cmd/bd` was red and the orphan-bead regression coverage never
  ran. Switch it to the supported Dolt backend (the subprocess binary is
  built with gms_pure_go embedded Dolt) and give the subprocess a hermetic
  env that strips ambient BEADS_/BD_ config and pins an isolated BEADS_DIR,
  so a shared Dolt server or real workspace cannot leak in.

- A create-time batch like `blocks:<wisp>,depends-on:<regular>` could commit
  a scheduling cycle: the merged two-session cycle check only ran when the
  edge being added was itself cross-tier, so a same-tier closing edge missed
  an earlier uncommitted cross-tier edge on the other session. Track which
  dependency tiers a logical transaction has written and force the merged
  CycleThroughEdges check once both tiers are in play. Add a regression for
  the cross-tier-first, same-tier-closing ordering.

- Extract addParentEdge/addDepSpecEdges/addWaitsForEdge from
  createIssueWithDeps, dropping its cognitive complexity from 27 to 10 while
  preserving atomic create-plus-edges behavior and error messages.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Test User <test@test.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-07-18 07:15:40 -07:00

126 lines
4.4 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
// createDepEdges describes the dependency edges attached to a new issue at
// create time: --parent, --deps, and --waits-for.
type createDepEdges struct {
parentID string
specs []domain.DependencySpec
waitsFor *domain.WaitsForSpec
}
func (e createDepEdges) empty() bool {
return e.parentID == "" && len(e.specs) == 0 && e.waitsFor == nil
}
// createIssueWithDeps persists a new issue together with its create-time
// dependency edges in one transaction. The previous shape — commit the issue
// first, then add each edge in its own transaction with warn-only error
// handling — meant a failed dep-add still exited 0 and left a dep-less,
// permanently-ready bead behind for orchestrators to dispatch prematurely.
// Here any edge failure rolls back the create and is returned as a fatal
// error naming the failing edge.
//
// With no edges requested it delegates to store.CreateIssue so a bare create
// keeps its store-specific routing and commit behavior.
func createIssueWithDeps(ctx context.Context, st storage.DoltStorage, issue *types.Issue, actor string, edges createDepEdges) error {
if edges.empty() {
return st.CreateIssue(ctx, issue, actor)
}
// Store-level CreateIssue routes configured infra types to the wisps
// tables; transaction-level CreateIssue routes on the Ephemeral/NoHistory
// flags only, so resolve the routing up front (mirrors DoltStore and
// sqlkit CreateIssue).
if !issue.Ephemeral && !issue.NoHistory && st.IsInfraTypeCtx(ctx, issue.IssueType) {
issue.Ephemeral = true
}
// Auto-minted IDs are only known after tx.CreateIssue runs, so the Dolt
// commit message can name the issue only when the ID is already reserved
// (explicit --id or a parent-child child ID).
commitMsg := "bd: create"
if issue.ID != "" {
commitMsg = "bd: create " + issue.ID
}
return transactHonoringAutoCommit(ctx, st, commitMsg, func(tx storage.Transaction) error {
if err := tx.CreateIssue(ctx, issue, actor); err != nil {
return err
}
// issue.ID is only reserved after tx.CreateIssue for auto-minted IDs, so
// the edge helpers run after the create.
if err := addParentEdge(ctx, tx, issue.ID, edges.parentID, actor); err != nil {
return err
}
if err := addDepSpecEdges(ctx, tx, issue.ID, edges.specs, actor); err != nil {
return err
}
return addWaitsForEdge(ctx, tx, issue.ID, edges.waitsFor, actor)
})
}
// addParentEdge adds the --parent parent-child edge, if requested.
func addParentEdge(ctx context.Context, tx storage.Transaction, issueID, parentID, actor string) error {
if parentID == "" {
return nil
}
dep := &types.Dependency{
IssueID: issueID,
DependsOnID: parentID,
Type: types.DepParentChild,
}
if err := tx.AddDependency(ctx, dep, actor); err != nil {
return fmt.Errorf("adding parent-child dependency %s -> %s: %w", issueID, parentID, err)
}
return nil
}
// addDepSpecEdges adds the --deps edges, honoring each spec's SwapDirection.
func addDepSpecEdges(ctx context.Context, tx storage.Transaction, issueID string, specs []domain.DependencySpec, actor string) error {
for _, spec := range specs {
dep := &types.Dependency{
IssueID: issueID,
DependsOnID: spec.TargetID,
Type: spec.Type,
Metadata: spec.Metadata,
}
if spec.SwapDirection {
dep.IssueID, dep.DependsOnID = dep.DependsOnID, dep.IssueID
}
if err := tx.AddDependency(ctx, dep, actor); err != nil {
return fmt.Errorf("adding dependency %s -> %s: %w", dep.IssueID, dep.DependsOnID, err)
}
}
return nil
}
// addWaitsForEdge adds the --waits-for spawner-gate edge, if requested.
func addWaitsForEdge(ctx context.Context, tx storage.Transaction, issueID string, waitsFor *domain.WaitsForSpec, actor string) error {
if waitsFor == nil {
return nil
}
metaJSON, err := json.Marshal(types.WaitsForMeta{Gate: waitsFor.Gate})
if err != nil {
return fmt.Errorf("serializing waits-for metadata: %w", err)
}
dep := &types.Dependency{
IssueID: issueID,
DependsOnID: waitsFor.SpawnerID,
Type: types.DepWaitsFor,
Metadata: string(metaJSON),
}
if err := tx.AddDependency(ctx, dep, actor); err != nil {
return fmt.Errorf("adding waits-for dependency %s -> %s: %w", issueID, waitsFor.SpawnerID, err)
}
return nil
}