beads/cmd/bd/graph_apply_execution_unit_test.go
Julian Knutsen cb32a384d5
fix(storage-class): reject durable class on wisp plane; emit storage_class in CLI bundle (#5164)
* fix(storage-class): reject durable class + wisp-plane; emit storage_class in CLI bundle

Post-merge review remediation for PR #5149 (mol-pr-post-merge-review-v1).

Finding A (codex, MAJOR): an explicit durable --storage-class combined with
--ephemeral/--no-history (or an unversioned/versioned graph node marked
ephemeral/no_history) was silently collapsed into an effective-ephemeral
record instead of being rejected. The durable request is impossible to honor
on a wisp-plane row, so gate the contradiction on the *explicit* flag/field
(so flag>config precedence and config-default behavior are preserved) and
Normalize() only after the check. types.Validate stays the storage-layer
backstop.

Finding B (claude, MAJOR): AllMigrationsSQL recorded 0060 as applied but the
Dolt CLI silently skips its prepared ALTER TABLE, so a fresh bundle omitted
issues/wisps.storage_class while still stamping the migration version --
silent schema divergence. Add a direct-DDL override in cli_migrations.go
(same precedent as 0023/0027/0054/0055) and gate it both ways: string-shape
in the default suite plus a dolt-binary column-shape assertion that proves
the bundle now creates storage_class VARCHAR(16) nullable on both tables.

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

* fix(storage-class): config-derived durable class yields to explicit wisp-plane flag

Post-merge review remediation for PR #5149, iteration 2
(mol-pr-post-merge-review-v1), addressing the remaining major from the
follow-up PR #5164 review.

Finding (codex+claude, MAJOR): iteration 1 gated the durable-class/wisp-plane
conflict on the *explicit* flag so flag>config precedence was preserved, but a
per-type config default (storage-class.<type>=unversioned) was still carried
into validation for an explicit --ephemeral/--no-history create (or an
effective-ephemeral graph node), reached the storage-layer types.Validate
backstop, and blocked the create -- contradicting the documented "flag > config"
behavior.

Extract a shared reconcileStorageClassPlane helper used by both cmd/bd/create.go
and cmd/bd/graph_apply.go that tracks whether the resolved class came from an
explicit flag/field or only from config: an explicit durable class on a wisp
plane is still rejected verbatim (durable intent preserved, not silently
collapsed), while a config-derived durable class yields -- cleared before
Normalize()/Validate -- to the explicit wisp-plane flag (Protocol v0.1 C1.3).
versioned still normalizes to the unset marker (C2.4) only after the check.

Regression coverage:
- TestReconcileStorageClassPlane: the full explicit-vs-config x wisp-plane
  decision matrix (pure).
- TestGraphApplyNodeStorageClassConfigDefaultYieldsToWispPlane: config-derived
  unversioned yields for plan/node ephemeral and plan no_history (pure).
- Embedded CLI subtests: storage-class.task=unversioned + --ephemeral routes to
  the wisp plane, and + --no-history creates a durable wisp row without the
  config class leaking to the at-rest cell.

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

---------

Co-authored-by: Eddie the Engineer <ci@beads.test>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-27 08:56:38 -07:00

956 lines
30 KiB
Go

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.<type>=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)
}
})
}
}