beads/cmd/bd/graph_apply_test.go
Julian Knutsen 1137aeb70d
ci(bazel): embedded-Dolt tier 20/5 → 50/15 duration-balanced Bazel shards (F1) (#7156)
* ci(bazel): embedded-Dolt tier 20/5 -> 40/14 duration-balanced shards (F1)

Give the Bazel-only bazel-embedded job its own duration-balanced manifest
blocks for //cmd/bd:bd_embedded_test (20 -> 40 shards) and
//internal/storage/embeddeddolt:embeddeddolt_embedded_test (5 -> 14
shards), decoupled from PR Risk's/main.yml's legacy frozen 20/5-shard
fork/push jobs, mirroring F2's bd_proxied_test precedent.

- Measured every TestEmbedded* / embeddeddolt test's wall time in
  isolation; split 21 cmd-tier and 1 storage-tier single top-level test
  over 180s into disjoint sub-tests (3 irreducible exceptions left:
  TestEmbeddedUpdateConcurrent 475s, TestEmbeddedCloseConcurrent 308s,
  TestLargeBatchApplyStatementCounts712_Embedded 261s).
- New scripts/ci/gen_embedded_{cmd,storage}_shard_manifest.py +
  _embedded_shard_manifest_lib.py generate/check duration-balanced
  manifest blocks (LPT packing, incremental --write/--repack, exact-once
  --check), chosen at N=40/M=14 where the heaviest shard reaches the
  irreducible-test floor.
- Fixed 18 stale legacy 20-shard cmd manifest entries (and 1 storage
  entry) left over from earlier test splits, which would have hard-failed
  every shard of PR Risk's real test-embedded-cmd jobs on their next run.
- New scripts/embedded_shard_count_test.go policy tests tie the
  Bazel-only block's shard count to bazel.yml's check_shard_coverage.py
  argument and catch generator staleness; generalized
  TestBazelRetiredLanesCheckListedTestsRan's live-shard-count dispatch
  from bd_proxied_test-only to a map covering both embedded targets;
  removed TestBazelEmbeddedJobMirrorsEmbeddedTier's now-invalid
  BUILD.bazel-shard-count-equals-PR-Risk-matrix assertion.
- Verified: go test ./scripts/..., bazel test //scripts:scripts_test,
  actionlint, make ci-pr-policy, make bazel-sync-check all pass; full
  local bazel test of both targets at 40/14 shards passes 2/2; mutation
  testing confirms each new/changed policy test fails exactly when it
  should.

See ~/beads-bazel-plan/f1/impl-report.md for full detail.

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

* fix(embedded-dolt): skip 712-item statement-count assertion under -race (F1)

TestLargeBatchApplyStatementCounts712_Embedded genuinely costs ~260-300s
under -race (confirmed by solo re-measurement: 298.60s) -- 14014 real SQL
statement round-trips through the race-instrumented in-process Dolt engine,
not an artifact and not splittable (one indivisible ApplyBatchInTx
transaction). It was the storage tier's single-test floor for CI shard
packing.

Apply the exact precedent TestLargeBatchApplyWallClock_Embedded already set
for its 1000-item shape: skip this assertion under raceEnabled (the cost is
race-instrumentation overhead on the Dolt engine's own internal
goroutine/lock machinery, not this test's own logic) and extend nightly.yml's
"Embedded Dolt batch-apply suite (non-race)" step's -run regex so the full
pinned 14014-statement baseline still runs, non-race, every night. Verified
directly: under -race the assertion now skips in 0.00s; without -race it
still runs and asserts Total=14015 (within the existing +/-2 tolerance) in
36.76s.

Updates scripts/ci_workflow_test.go's
TestNightlyFullTestRunsEmbeddedDoltBatchApplySuite to match the extended
regex.

Storage tier's new single-test ceiling under the per-PR -race lane drops
from ~260.7s to 152.38s (TestBatchApplyContract).

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

* ci(bazel): correct cmd-tier long-pole durations, re-pack embedded manifolds (F1)

Investigated coordinator item 2 (single-test long poles): TestEmbeddedUpdateConcurrent
(recorded 475.39s) and TestEmbeddedCloseConcurrent (recorded 308.06s), plus
the two other >180s cmd-tier entries from the same capture
(TestEmbeddedInitA 196.94s, TestEmbeddedEpicCloseEligibleReason 192.47s).

Root cause: NOT host contention, NOT backoff/retry sleeps (bdRunWithFlockRetry
contributes negligibly), NOT race-instrumented-subprocess overhead alone.
These numbers were captured via `bazel --nohome_rc test --config=embedded`
with the then-current 20-shard legacy manifest (~10-11 tests/shard) and
`-test.parallel=4`. Go's t.Parallel() starts each parallel test's elapsed
clock when its function is invoked, before the Parallel() call blocks it
waiting for a free one-of-4 slot -- so a test queued behind several other
heavy shard-mates has that queueing wait baked into its own recorded
`--- PASS: TestX (Ys)` time. This is shard-composition-dependent scheduling
delay, not a cost intrinsic to the test.

Confirmed two ways in an isolated clone (not this worktree, per the
no-plain-go-test-from-a-beads-checkout rule):
- Solo (no rivals at all): 151.83s / 106.48s / 63.58s / 66.08s.
- All four together with the real -race -test.parallel=4 flags and exactly
  4 tests requested (so nobody queues -- parallel slots == test count):
  141.34s / 113.80s / 69.79s / 74.63s.
Both agree closely and both are far below the capture-time numbers.

F1's LPT packer already isolates the heaviest tests into shards with few or
no other heavy rivals (TestEmbeddedUpdateConcurrent lands alone in its own
40-shard-block shard), so under the new manifest these tests see little to
no queueing delay in real CI. None of the four needed splitting, parallel
subtests, or raceEnabled-scaled N: once correctly measured, none exceeds the
180s single-test guideline (new corrected weights: 155.0 / 115.0 / 72.0 /
77.0s). Corrected scripts/ci/embedded_cmd_test_durations.json accordingly
(with a doc-comment explaining the methodology and both confirmations) and
re-packed the 40-shard Bazel-only block (--repack --write); --check passes
(exact-once coverage of all 241 discovered tests). The frozen legacy 20-shard
block is untouched and independently re-verified exact-once by simulating
embedded-test-shard.sh across all 20 shards (241/241 tests, no
duplicates/misses/errors).

New cmd-tier single-test ceiling: 179.47s (TestEmbeddedCloseAlreadyClosed,
likely itself somewhat inflated by the same mechanism but already under the
180s line as recorded, so no action needed).

Also updates scripts/ci/embedded_storage_test_durations.json: the prior
commit's raceEnabled-skip for TestLargeBatchApplyStatementCounts712_Embedded
means it now costs ~0s in the per-PR -race lane bazel-embedded actually
packs for (not its real ~260-300s non-race cost, which nightly.yml still
exercises) -- weight set to 1.0 with a doc comment tying it to the skip in
large_batch_apply_measure_test.go. Re-packed the 14-shard Bazel-only block
accordingly; --check passes (exact-once coverage of all 387 discovered
tests, excluding TestMain/TestConformance per that file's existing
convention). The frozen legacy 5-shard block is untouched and independently
re-verified exact-once via embedded-storage-test-shard.sh simulation
(388/388 tests, no duplicates/misses/errors).

Verification: go test ./scripts/... (includes the nightly.yml policy test),
make ci-pr-policy, make bazel-sync-check, actionlint all pass. Real local
`bazel --nohome_rc test --config=embedded //cmd/bd:bd_embedded_test
//internal/storage/embeddeddolt:embeddeddolt_embedded_test`
(--local_test_jobs=8, both targets together, on a shared/noisy sandbox host)
passes both targets; per-shard wall time from each shard's test.xml: cmd/bd
max 218.9s (shard 23/40, min 20.6s), storage max 251.1s (shard 5/14, min
0.98s) -- down from the prior oversubscribed sweep's 783.41s / 351.94s and
well under the single-test-floor-based ~475s projection this slice started
from. Projected tier lane time (max of the two targets, real dedicated CI
runners should do at least this well): ~251s, under the 5-minute target.

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

* test(embedded): un-vacuous TestEmbeddedDepB edges, split epic-close test, trim concurrency stress N (F1 review)

Coordinator review follow-ups on the F1 embedded-Dolt resharding slice:

- TestEmbeddedDepB (one of TestEmbeddedDep's two CI-speed split halves) was
  asserting its tree_* subtests against an edgeless graph, passing
  vacuously; restores the same parent-child/blocks edges TestEmbeddedDepA
  builds so those subtests exercise real multi-node traversal (review S2).
- TestEmbeddedEpicCloseEligibleReason split into
  TestEmbeddedEpicCloseEligibleReasonFlag/...Output for CI shard balance,
  matching the project's established single-concern split pattern.
- TestEmbeddedUpdateConcurrent/TestEmbeddedCloseConcurrent's
  issuesPerWorker reduced 5->2: under real concurrent-shard-load
  measurement these were genuine (not queueing-artifact) serialized-write
  costs; 2 preserves every invariant the test checks (duplicate-ID
  detection across all workers, one non-decreasing-list-count check per
  worker) at a fraction of the serialized work.
- large712ShapeName: the 712-shape's race skip and its zero-match guard now
  share one named constant instead of two independent literal shape-name
  strings, so a future rename of the shape can't silently skip the pinned
  statement-count assertion under race (review N2).
- Comment-only fixes (review N5) in files referencing test names since
  renamed/split by this slice's earlier work: close_proxied_integration_test.go,
  graph_apply_test.go, storage_class_proxied_integration_test.go,
  tests/regression/discovery_test.go, plus doc-comment path cleanups (N1:
  drop unverified ~/beads-bazel-plan paths/bead ids in favor of the
  committed duration JSON files and engdocs/TESTING.md).

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

* ci(bazel): re-derive embedded-Dolt durations under concurrent load; cap cmd shards at Bazel's 50-shard limit (F1 round 2)

Coordinator review required re-deriving every per-test duration weight from
a single, consistent, CI-realistic measurement (all shards running
concurrently, -test.parallel=4, race-enabled) instead of the prior pass's
mix of crowded-shard captures and solo/4-together spot-corrections, and
required measuring per-shard wall time via BEP testAttemptDuration rather
than a shard's outer test.xml <testsuites time> (which can include a
different, already-finished shard-mate's setup/teardown).

- scripts/ci/embedded_cmd_test_durations.json (242 tests) and
  scripts/ci/embedded_storage_test_durations.json (387 tests) rewritten in
  full from one consistent sweep. Every entry is now a fresh measurement;
  none is a carried-over capture-time value or an unverified estimate. Both
  files' _comment blocks retract the earlier "queueing delay baked into a
  test's own reported elapsed time" theory (testing.go's (*T).Parallel does
  not add wait time to a blocked test's own clock) and document the real
  methodology.
- Only one cmd-tier test remains over 200s (TestEmbeddedListFiltering,
  239.70s), already under the ~240s ceiling; no further top-level splits
  were needed this round.
- New finding: Bazel hard-caps shard_count at 50 per sh_test-like rule
  ("Having more than 50 shards is indicative of poor test organization";
  a native analysis-time limit, not configurable). The previous 88-shard
  plan for //cmd/bd:bd_embedded_test (chosen as the LPT-packed floor before
  this limit was discovered) is reverted to 50, Bazel's real ceiling.
  Repacking the fresh weights at 50 shards gives a heaviest shard of
  409.6s -- above the single-test floor of 239.7s, because 50 bins is not
  enough headroom over the suite's ~20145 measured test-seconds to flatten
  every bin to that floor. This makes the <=5 min lane target unreachable
  for the cmd tier via resharding alone within Bazel's native per-rule
  limit; see ~/beads-bazel-plan/f1/impl-report.md section 3c for the full
  writeup and the two remaining levers (suite-wide speedups or a
  multi-Bazel-rule split), neither attempted in this slice.
- internal/storage/embeddeddolt gets 15 Bazel-only shards (unaffected by
  the 50-shard cap): LPT-packed heaviest shard 225.3s, within target.
- cmd/bd/BUILD.bazel, internal/storage/embeddeddolt/BUILD.bazel,
  .github/workflows/bazel.yml, engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md,
  scripts/embedded_shard_count_test.go, scripts/pr_risk_bazel_coverage_test.go,
  scripts/ci/gen_embedded_cmd_shard_manifest.py updated to the corrected
  50/15 shard counts (and, for the generator, N3: --write without an
  explicit total_shards now errors instead of silently regenerating the
  frozen legacy 20-shard block).
- .github/scripts/embedded-{cmd,storage}-test-shards.txt: re-packed
  Bazel-only blocks at 50/15; frozen legacy 20/5 blocks untouched except for
  N5 fixes to stale entries left by this slice's earlier test splits
  (TestShardScriptsListOnlyRealTests catches this class of bug; both
  legacy blocks reconfirmed exact-once).
- .github/workflows/nightly.yml / scripts/ci_workflow_test.go (N4): the
  embedded-dolt batch-apply nightly step now runs with `if: ${{
  !cancelled() }}` and its own explicit `-timeout 20m`, independent of the
  job-level timeout, with both halves now asserted by
  TestNightlyFullTestRunsEmbeddedDoltBatchApplySuite.

Verified: gofmt -l clean, go vet ./scripts/... clean, go test ./scripts/...
green, both generators' --check pass at 50/15 (and legacy 20/5 remain
exact-once via the frozen-block invariant).

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

* test(ci): rename embedded manifest staleness tests out of the ^TestEmbedded skip

The allowlisted go-test leg runs with -skip ^TestEmbedded, so tests named
TestEmbedded*ShardManifestGeneratorNotStale never ran there and the leg
failed with "matched no test that ran".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-03 21:30:03 -07:00

1009 lines
37 KiB
Go

package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"reflect"
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// TestDocsGraphPlanExampleValidates pins the --graph doc supplement's example
// to the validator: the canonical example must stay a plan `bd create --graph`
// actually accepts (review caught it shipping with event fields on a task
// node and edges duplicating parent_key). The embedded supplement is the
// source of truth; the docs drift gate keeps the generated CLI reference
// byte-equal to it.
func TestDocsGraphPlanExampleValidates(t *testing.T) {
const fence = "```json\n"
start := strings.Index(createGraphPlanSupplement, fence)
if start < 0 {
t.Fatal("example JSON block not found in create_graph_plan.md supplement")
}
rest := createGraphPlanSupplement[start+len(fence):]
end := strings.Index(rest, "```")
if end < 0 {
t.Fatal("example JSON block not terminated")
}
planJSON := []byte(rest[:end])
if unknown := detectUnknownGraphFields(planJSON); len(unknown) > 0 {
t.Errorf("documented example uses unknown fields: %v", unknown)
}
var plan GraphApplyPlan
if err := json.Unmarshal(planJSON, &plan); err != nil {
t.Fatalf("documented example is not valid plan JSON: %v", err)
}
if err := validateGraphApplyPlan(&plan, nil, nil, GraphApplyOptions{}); err != nil {
t.Errorf("documented example rejected by validator: %v", err)
}
if _, err := validateGraphApplyStorageClasses(&plan, GraphApplyOptions{}, false); err != nil {
t.Errorf("documented example rejected by storage-class validation: %v", err)
}
}
func TestValidateGraphApplyPlanAcceptsCustomTypes(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "root", Title: "Workflow", Type: "task"},
{Key: "spec", Title: "Step spec", Type: "spec"},
},
}
if err := validateGraphApplyPlan(plan, []string{"spec"}, nil, GraphApplyOptions{}); err != nil {
t.Fatalf("expected custom type %q to validate, got %v", "spec", err)
}
}
func TestValidateGraphApplyPlanRejectsTypeWhenCustomTypesAbsent(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "spec", Title: "Step spec", Type: "spec"},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected custom type to fail when nil customTypes")
}
want := `node "spec": invalid issue type: spec`
if err.Error() != want {
t.Fatalf("error = %q, want %q", err.Error(), want)
}
}
func TestValidateGraphApplyPlanRejectsInvalidTypes(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "root", Title: "Root", Type: "definitely-not-a-type"},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected error for invalid type")
}
want := `node "root": invalid issue type: definitely-not-a-type`
if err.Error() != want {
t.Fatalf("error = %q, want %q", err.Error(), want)
}
}
func TestValidateGraphApplyPlanAcceptsBuiltInTypes(t *testing.T) {
for _, typ := range []string{"task", "bug", "feature", "epic", "chore", "decision"} {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "n1", Title: "Node", Type: typ},
},
}
if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil {
t.Errorf("type %q rejected: %v", typ, err)
}
}
}
func TestValidateGraphApplyPlanAcceptsEmptyType(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "n1", Title: "Node", Type: ""},
},
}
if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil {
t.Fatalf("empty type rejected: %v", err)
}
}
// TestValidateGraphApplyPlanAcceptsNewFields verifies that estimate,
// external_ref, parent (alias), and deps are accepted without error. (GH#4064)
func TestValidateGraphApplyPlanAcceptsNewFields(t *testing.T) {
est := 120
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{
Key: "epic",
Title: "Epic node",
Type: "epic",
Estimate: &est,
ExternalRef: "gh-42",
},
{
Key: "child",
Title: "Child node",
Parent: "epic",
Deps: []GraphApplyNodeDep{
{Target: "epic", Type: "blocks"},
},
},
},
}
if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil {
t.Fatalf("unexpected validation error: %v", err)
}
}
// TestValidateGraphApplyPlanRejectsNegativeEstimate verifies that a negative
// estimate (via the alias) is caught at validation time — even when
// estimated_minutes is also set and would win the alias fold, so the bad
// value can't be silently discarded by the precedence. (GH#4064)
func TestValidateGraphApplyPlanRejectsNegativeEstimate(t *testing.T) {
neg := -5
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "n", Title: "Node", Estimate: &neg},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected error for negative estimate")
}
if !strings.Contains(err.Error(), "estimate cannot be negative") {
t.Fatalf("unexpected error: %v", err)
}
canonical := 10
plan.Nodes[0].EstimatedMinutes = &canonical
err = validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected error for negative estimate alongside estimated_minutes")
}
if !strings.Contains(err.Error(), "estimate cannot be negative") {
t.Fatalf("unexpected error: %v", err)
}
}
// TestValidateGraphApplyPlanRejectsEmptyDepTarget verifies that a dep with an
// empty target is caught at validation time. (GH#4064)
func TestValidateGraphApplyPlanRejectsEmptyDepTarget(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "n", Title: "Node", Deps: []GraphApplyNodeDep{{Target: ""}}},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected error for empty dep target")
}
if !strings.Contains(err.Error(), "empty target") {
t.Fatalf("unexpected error: %v", err)
}
}
// TestValidateGraphApplyPlanParentAliasResolvesCorrectly verifies that the
// "parent" field works as an alias for "parent_key" in validation. (GH#4064)
func TestValidateGraphApplyPlanParentAliasResolvesCorrectly(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "root", Title: "Root"},
{Key: "child", Title: "Child", Parent: "root"},
},
}
if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil {
t.Fatalf("parent alias should resolve: %v", err)
}
}
// TestValidateGraphApplyPlanParentAliasRejectsUnknownKey verifies that the
// "parent" field rejects unknown keys just like "parent_key". (GH#4064)
func TestValidateGraphApplyPlanParentAliasRejectsUnknownKey(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "child", Title: "Child", Parent: "nonexistent"},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected error for unknown parent key via alias")
}
if !strings.Contains(err.Error(), "parent key") {
t.Fatalf("unexpected error: %v", err)
}
}
// TestEmitGraphApplyDryRun_ParentAlias verifies that the "parent" alias
// is counted and displayed in dry-run output. (GH#4064)
func TestEmitGraphApplyDryRun_ParentAlias(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "root", Title: "Root", Type: "epic"},
{Key: "c1", Title: "Child 1", Parent: "root"},
},
}
out := captureStdout(t, func() error {
emitGraphApplyDryRun(plan, GraphApplyOptions{})
return nil
})
if !strings.Contains(out, "1 parent-child link(s)") {
t.Errorf("dry-run should count parent alias as parent-child link:\n%s", out)
}
if !strings.Contains(out, "parent_key=root") {
t.Errorf("dry-run should display resolved parent_key from alias:\n%s", out)
}
}
// TestDetectUnknownGraphFields_ReporterRepro reproduces the schema-mismatch
// pattern from GH#3367: the user passes 'parent' (a string) and 'blocks' (an
// array) directly on nodes, expecting them to wire hierarchy/dependencies.
// json.Unmarshal silently drops them. detectUnknownGraphFields must surface
// both fields, scoped to the offending nodes.
func TestDetectUnknownGraphFields_ReporterRepro(t *testing.T) {
// After GH#4064, "parent" is a recognized alias for "parent_key".
// Only "blocks" (an array, not an edge or dep) remains unknown.
planJSON := []byte(`{
"nodes": [
{"key": "root", "type": "epic", "title": "Root epic", "priority": 2},
{"key": "child1", "type": "task", "title": "Child task 1", "parent": "root", "priority": 2, "blocks": ["child2"]},
{"key": "child2", "type": "task", "title": "Child task 2", "parent": "root", "priority": 2}
]
}`)
got := detectUnknownGraphFields(planJSON)
want := map[string][]string{
`node["child1"]`: {"blocks"},
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("detectUnknownGraphFields:\n got=%#v\nwant=%#v", got, want)
}
}
// TestDetectUnknownGraphFields_KnownSchemaIsClean verifies that a plan using
// only the documented schema (parent_key, edges array) reports no unknowns.
// Guards against the schema lists drifting from the GraphApplyPlan/Node/Edge
// json tags.
func TestDetectUnknownGraphFields_KnownSchemaIsClean(t *testing.T) {
planJSON := []byte(`{
"commit_message": "test",
"nodes": [
{"key": "root", "title": "Root", "type": "epic", "priority": 2,
"description": "d", "assignee": "alice", "assign_after_create": false,
"estimate": 60, "labels": ["a"], "metadata": {"k": "v"},
"metadata_refs": {"r": "root"}, "external_ref": "gh-1",
"deps": [{"target": "child", "type": "blocks"}]},
{"key": "child", "title": "Child", "parent_key": "root",
"parent_id": "ext-1", "parent": "root"}
],
"edges": [
{"from_key": "child", "to_key": "root", "type": "blocks"},
{"from_id": "ext-1", "to_id": "ext-2", "type": "related"}
]
}`)
if got := detectUnknownGraphFields(planJSON); len(got) != 0 {
t.Fatalf("expected no unknown fields for canonical schema, got %#v", got)
}
}
// TestDetectUnknownGraphFields_PlanAndEdgeLevel verifies coverage at the plan
// top level and edge level, not just node level.
func TestDetectUnknownGraphFields_PlanAndEdgeLevel(t *testing.T) {
planJSON := []byte(`{
"version": "1.0",
"nodes": [{"key": "n", "title": "n"}],
"edges": [{"from_key": "n", "to_key": "n", "weight": 5}]
}`)
got := detectUnknownGraphFields(planJSON)
if !reflect.DeepEqual(got["plan"], []string{"version"}) {
t.Errorf("plan-level unknowns: got=%v want=[version]", got["plan"])
}
if !reflect.DeepEqual(got["edge[0]"], []string{"weight"}) {
t.Errorf("edge-level unknowns: got=%v want=[weight]", got["edge[0]"])
}
}
// TestDetectUnknownGraphFields_BadJSON returns empty rather than panicking
// when the plan can't be parsed at the top level. Callers run the strict
// json.Unmarshal afterwards and surface the parse error there.
func TestDetectUnknownGraphFields_BadJSON(t *testing.T) {
if got := detectUnknownGraphFields([]byte(`{not json`)); len(got) != 0 {
t.Fatalf("expected empty map for bad JSON, got %#v", got)
}
}
// TestWarnUnknownGraphFields_HintsForReporterFields asserts that the hint
// text for the two highest-friction fields ('parent', 'blocks' from GH#3367)
// is emitted and points the user at the canonical schema field.
func TestWarnUnknownGraphFields_HintsForReporterFields(t *testing.T) {
// After GH#4064, "parent" is a recognized field. Only "blocks" triggers a hint.
var buf bytes.Buffer
hinted := warnUnknownGraphFields(&buf, map[string][]string{
`node["c1"]`: {"blocks", "body"},
})
out := buf.String()
if !strings.Contains(out, `unknown field(s): [blocks body]`) {
t.Errorf("warning missing field list: %q", out)
}
if !strings.Contains(out, "deps") {
t.Errorf("expected 'blocks' hint to mention deps: %q", out)
}
if !strings.Contains(out, "description") {
t.Errorf("expected 'body' hint to mention description: %q", out)
}
got := append([]string(nil), hinted...)
sort.Strings(got)
want := []string{"blocks", "body"}
if !reflect.DeepEqual(got, want) {
t.Errorf("hinted fields: got=%v want=%v", got, want)
}
}
// TestWarnUnknownGraphFields_NoUnknownsIsSilent verifies the warning function
// emits nothing when the input map is empty (the common path for well-formed
// plans).
func TestWarnUnknownGraphFields_NoUnknownsIsSilent(t *testing.T) {
var buf bytes.Buffer
warnUnknownGraphFields(&buf, nil)
if buf.Len() != 0 {
t.Fatalf("expected silent on empty input, wrote: %q", buf.String())
}
}
// TestEmitGraphApplyDryRun_Counts verifies the dry-run preview reports the
// node count, edge count, and parent-link count without performing any
// writes. Captures stdout (the dry-run path writes to stdout, with warnings
// going to stderr from the upstream caller).
func TestEmitGraphApplyDryRun_Counts(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "root", Title: "Root", Type: "epic"},
{Key: "c1", Title: "Child 1", ParentKey: "root"},
{Key: "c2", Title: "Child 2", ParentKey: "root"},
},
Edges: []GraphApplyEdge{
{FromKey: "c1", ToKey: "c2", Type: "blocks"},
},
}
out := captureStdout(t, func() error {
emitGraphApplyDryRun(plan, GraphApplyOptions{})
return nil
})
if !strings.Contains(out, "would create 3 issue(s) and 1 edge(s) (2 parent-child link(s))") {
t.Errorf("dry-run summary missing or wrong:\n%s", out)
}
for _, want := range []string{"root", "c1", "c2", "parent_key=root", "live create may still reject parent-child blocking paths"} {
if !strings.Contains(out, want) {
t.Errorf("dry-run missing %q in output:\n%s", want, out)
}
}
}
func TestGraphApplyOptionsValidateRejectsEphemeralNoHistory(t *testing.T) {
err := (GraphApplyOptions{Ephemeral: true, NoHistory: true}).Validate()
if err == nil {
t.Fatal("expected mutually exclusive graph options to be rejected")
}
if got, want := err.Error(), "ephemeral and no_history are mutually exclusive"; got != want {
t.Fatalf("error = %q, want %q", got, want)
}
}
func TestValidateGraphApplyPlanRejectsLocalBlockingCycle(t *testing.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: "blocks"},
{FromKey: "b", ToKey: "c", Type: "conditional-blocks"},
{FromKey: "c", ToKey: "a", Type: "blocks"},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected local graph cycle to be rejected")
}
if got, want := err.Error(), "graph contains a blocking dependency cycle"; !strings.Contains(got, want) {
t.Fatalf("error = %q, want to contain %q", got, want)
}
}
func TestValidateGraphApplyPlanReportsDeterministicCycleNode(t *testing.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: "b", ToKey: "c", Type: "blocks"},
{FromKey: "c", ToKey: "a", Type: "blocks"},
{FromKey: "a", ToKey: "b", Type: "blocks"},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected local graph cycle to be rejected")
}
if got, want := err.Error(), `graph contains a blocking dependency cycle involving node "a"`; got != want {
t.Fatalf("error = %q, want %q", got, want)
}
}
func TestValidateGraphApplyPlanAllowsNonBlockingLocalCycle(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "a", Title: "A", Type: "task"},
{Key: "b", Title: "B", Type: "task"},
},
Edges: []GraphApplyEdge{
{FromKey: "a", ToKey: "b", Type: "related"},
{FromKey: "b", ToKey: "a", Type: "related"},
},
}
if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil {
t.Fatalf("non-blocking cycle rejected: %v", err)
}
}
func TestValidateGraphApplyPlanRejectsImplicitParentChildReverseBlockingCycle(t *testing.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: "blocks"},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil {
t.Fatal("expected implicit parent-child plus reverse blocking edge to be rejected")
}
if got, want := err.Error(), "blocking dependency cycle"; !strings.Contains(got, want) {
t.Fatalf("error = %q, want to contain %q", got, want)
}
}
func TestValidateGraphApplyPlanIgnoresIDOverridesForLocalCycleValidation(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "a", Title: "A", Type: "task"},
{Key: "b", Title: "B", Type: "task"},
},
Edges: []GraphApplyEdge{
{FromKey: "a", FromID: "bd-existing", ToKey: "b", Type: "blocks"},
{FromKey: "b", ToKey: "a", Type: "blocks"},
},
}
if err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{}); err != nil {
t.Fatalf("ID override edge should not be treated as a local key cycle: %v", err)
}
}
func TestGraphApplyEdgeIsLocalCycleRelevantOnlyForLocalBlockingEdges(t *testing.T) {
tests := []struct {
name string
edge GraphApplyEdge
typ string
want bool
}{
{name: "local default blocks", edge: GraphApplyEdge{FromKey: "a", ToKey: "b"}, want: true},
{name: "local conditional blocks", edge: GraphApplyEdge{FromKey: "a", ToKey: "b"}, typ: "conditional-blocks", want: true},
{name: "local nonblocking", edge: GraphApplyEdge{FromKey: "a", ToKey: "b"}, typ: "related"},
{name: "existing id target", edge: GraphApplyEdge{FromKey: "a", ToID: "bd-123"}, want: false},
{name: "explicit id overrides key", edge: GraphApplyEdge{FromKey: "a", FromID: "bd-1", ToKey: "b"}, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := graphApplyEdgeIsLocalCycleRelevant(tt.edge, graphApplyDependencyType(tt.typ))
if got != tt.want {
t.Fatalf("localCycleRelevant = %v, want %v", got, tt.want)
}
})
}
}
func TestGraphApplyParentDepPairs(t *testing.T) {
nodes := []GraphApplyNode{
{Key: "root", Title: "Root"},
{Key: "child", Title: "Child", ParentKey: "root"},
{Key: "external-child", Title: "External child", ParentID: "bd-parent"},
}
keyToID := map[string]string{
"root": "bd-root",
"child": "bd-child",
"external-child": "bd-external-child",
}
pairs := graphApplyParentDepPairs(nodes, keyToID)
for _, pair := range []struct {
child string
parent string
}{
{"bd-child", "bd-root"},
{"bd-external-child", "bd-parent"},
} {
if !pairs[graphApplyDepPairKey(pair.child, pair.parent)] {
t.Fatalf("missing parent dep pair %s -> %s", pair.child, pair.parent)
}
}
if pairs[graphApplyDepPairKey("bd-root", "bd-child")] {
t.Fatal("unexpected reverse parent dep pair")
}
}
// TestEmitGraphApplyDryRun_JSON verifies that the dry-run path emits valid
// JSON with the expected structure when jsonOutput is set. This exercises the
// code path that `bd create --graph --dry-run --json` takes, confirming the
// GraphApplyDryRun struct serializes correctly and that no persistence occurs
// (emitGraphApplyDryRun only formats output — it never touches the store).
// Regression coverage for GH#3893.
func TestEmitGraphApplyDryRun_JSON(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "root", Title: "Root epic", Type: "epic"},
{Key: "c1", Title: "First child", ParentKey: "root"},
{Key: "c2", Title: "Second child", ParentKey: "root"},
},
Edges: []GraphApplyEdge{
{FromKey: "c1", ToKey: "c2", Type: "blocks"},
},
}
oldJSON := jsonOutput
jsonOutput = true
defer func() { jsonOutput = oldJSON }()
out := captureStdout(t, func() error {
emitGraphApplyDryRun(plan, GraphApplyOptions{})
return nil
})
var result GraphApplyDryRun
if err := json.Unmarshal([]byte(out), &result); err != nil {
t.Fatalf("dry-run JSON output is not valid JSON: %v\nraw: %s", err, out)
}
if !result.DryRun {
t.Error("expected dry_run=true in JSON output")
}
if result.NodeCount != 3 {
t.Errorf("node_count = %d, want 3", result.NodeCount)
}
if result.EdgeCount != 1 {
t.Errorf("edge_count = %d, want 1", result.EdgeCount)
}
if result.ParentDeps != 2 {
t.Errorf("parent_deps = %d, want 2", result.ParentDeps)
}
if len(result.Nodes) != 3 {
t.Fatalf("nodes length = %d, want 3", len(result.Nodes))
}
// Verify node details are populated correctly.
rootRow := result.Nodes[0]
if rootRow.Key != "root" || rootRow.Title != "Root epic" || rootRow.Type != "epic" {
t.Errorf("root node row = %+v, want key=root title=Root epic type=epic", rootRow)
}
c1Row := result.Nodes[1]
if c1Row.ParentKey != "root" {
t.Errorf("c1 parent_key = %q, want %q", c1Row.ParentKey, "root")
}
// Default priority is P2.
if rootRow.Priority != 2 {
t.Errorf("root priority = %d, want 2 (default)", rootRow.Priority)
}
}
// TestCreateIssuesFromGraph_DryRunDoesNotPersist verifies that
// createIssuesFromGraph with dryRun=true produces dry-run output and does NOT
// call executeGraphApply. Since store is nil (no database initialized), any
// attempt to persist would panic; a successful dry-run completion proves the
// guard is effective. Regression test for GH#3893.
func TestCreateIssuesFromGraph_DryRunDoesNotPersist(t *testing.T) {
// Ensure store is nil — any persistence attempt would panic.
oldStore := store
store = nil
defer func() { store = oldStore }()
oldJSON := jsonOutput
jsonOutput = true
defer func() { jsonOutput = oldJSON }()
planJSON := `{
"nodes": [
{"key": "a", "title": "Task A", "type": "task"},
{"key": "b", "title": "Task B", "type": "task", "parent_key": "a"}
],
"edges": [
{"from_key": "b", "to_key": "a", "type": "blocks"}
]
}`
planFile := t.TempDir() + "/plan.json"
if err := os.WriteFile(planFile, []byte(planJSON), 0o600); err != nil {
t.Fatalf("write plan file: %v", err)
}
out := captureStdout(t, func() error {
createIssuesFromGraph(planFile, true, GraphApplyOptions{})
return nil
})
var result GraphApplyDryRun
if err := json.Unmarshal([]byte(out), &result); err != nil {
t.Fatalf("output is not valid dry-run JSON: %v\nraw: %s", err, out)
}
if !result.DryRun {
t.Error("expected dry_run=true")
}
if result.NodeCount != 2 {
t.Errorf("node_count = %d, want 2", result.NodeCount)
}
// The fixture combines b's parent_key="a" with an explicit b--blocks-->a
// edge. The dry-run preview counts these independently and does not dedupe
// the overlapping relationship, so edge_count and parent_deps are each 1.
// Pin both to catch any regression that starts merging or dropping them.
if result.EdgeCount != 1 {
t.Errorf("edge_count = %d, want 1", result.EdgeCount)
}
if result.ParentDeps != 1 {
t.Errorf("parent_deps = %d, want 1", result.ParentDeps)
}
}
// singleNodePlanErr validates a one-node plan built by mutate and returns the
// validation error (nil when the plan is accepted).
func singleNodePlanErr(customStatuses []string, mutate func(*GraphApplyNode)) error {
node := GraphApplyNode{Key: "a", Title: "A"}
mutate(&node)
plan := &GraphApplyPlan{Nodes: []GraphApplyNode{node}}
return validateGraphApplyPlan(plan, nil, customStatuses, GraphApplyOptions{})
}
func TestValidateGraphApplyPlanNodeFieldRules(t *testing.T) {
neg := -5
on := true
cases := []struct {
name string
customStatuses []string
mutate func(*GraphApplyNode)
wantErr string
}{
{name: "invalid status", mutate: func(n *GraphApplyNode) { n.Status = "bogus" }, wantErr: "invalid status"},
{name: "alias type accepted like bd create", mutate: func(n *GraphApplyNode) { n.Type = "feat" }},
{name: "builtin status accepted", mutate: func(n *GraphApplyNode) { n.Status = "in_progress" }},
{name: "custom status accepted", customStatuses: []string{"triage"}, mutate: func(n *GraphApplyNode) { n.Status = "triage" }},
{name: "custom status rejected without config", mutate: func(n *GraphApplyNode) { n.Status = "triage" }, wantErr: "invalid status"},
{name: "negative estimate", mutate: func(n *GraphApplyNode) { n.EstimatedMinutes = &neg }, wantErr: "estimated_minutes"},
{name: "priority out of range", mutate: func(n *GraphApplyNode) { p := 9; n.Priority = &p }, wantErr: "priority must be between 0 and 4"},
{name: "priority bounds accepted", mutate: func(n *GraphApplyNode) { p := 0; n.Priority = &p }},
{name: "invalid wisp_type", mutate: func(n *GraphApplyNode) { n.WispType = "bogus" }, wantErr: "invalid wisp_type"},
{name: "valid wisp_type", mutate: func(n *GraphApplyNode) { n.WispType = "heartbeat" }},
{name: "invalid mol_type", mutate: func(n *GraphApplyNode) { n.MolType = "bogus" }, wantErr: "invalid mol_type"},
{name: "valid mol_type", mutate: func(n *GraphApplyNode) { n.MolType = "swarm" }},
{name: "event fields require event type", mutate: func(n *GraphApplyNode) { n.EventKind = "agent.started" }, wantErr: "require type"},
{name: "event fields on event node", mutate: func(n *GraphApplyNode) {
n.Type = "event"
n.EventKind = "agent.started"
n.Actor = "x"
n.Target = "y"
n.Payload = "{}"
}},
{name: "node-level ephemeral+no_history conflict", mutate: func(n *GraphApplyNode) { n.Ephemeral = &on; n.NoHistory = &on }, wantErr: "mutually exclusive"},
{name: "bad explicit id format", mutate: func(n *GraphApplyNode) { n.ID = "nohyphen" }, wantErr: "invalid ID format"},
{name: "valid explicit id", mutate: func(n *GraphApplyNode) { n.ID = "bd-a1b2c3" }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := singleNodePlanErr(tc.customStatuses, tc.mutate)
if tc.wantErr == "" {
if err != nil {
t.Fatalf("expected plan to validate, got %v", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %v", tc.wantErr, err)
}
})
}
}
func TestValidateGraphApplyPlanRejectsDuplicateExplicitIDs(t *testing.T) {
plan := &GraphApplyPlan{
Nodes: []GraphApplyNode{
{Key: "a", Title: "A", ID: "bd-a1b2c3"},
{Key: "b", Title: "B", ID: "bd-a1b2c3"},
},
}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if err == nil || !strings.Contains(err.Error(), "duplicate explicit id") {
t.Fatalf("expected duplicate explicit id error, got %v", err)
}
}
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"},
{Key: "spawner", Title: "Spawner"},
}
cases := []struct {
name string
edge GraphApplyEdge
wantErr string
}{
{name: "gate requires waits-for", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "blocks", Gate: "all-children"}, wantErr: "require type"},
{name: "gate defaults-to-blocks edge rejected", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Gate: "all-children"}, wantErr: "require type"},
{name: "invalid gate value", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", Gate: "bogus"}, wantErr: "invalid gate"},
{name: "spawner_key and spawner_id conflict", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", SpawnerKey: "spawner", SpawnerID: "bd-x"}, wantErr: "cannot specify both"},
{name: "unknown spawner_key", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", SpawnerKey: "ghost"}, wantErr: "spawner key"},
{name: "spawner_key must match to_key", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", SpawnerKey: "gate"}, wantErr: "must match to_key"},
{name: "spawner_key with ambiguous to_id rejected", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", ToID: "bd-ext1", Type: "waits-for", SpawnerKey: "spawner"}, wantErr: "cannot be combined with to_id"},
{name: "spawner_id must match to_id", edge: GraphApplyEdge{FromKey: "gate", ToID: "bd-ext1", Type: "waits-for", SpawnerID: "bd-other"}, wantErr: "must match to_id"},
{name: "matching spawner_id accepted", edge: GraphApplyEdge{FromKey: "gate", ToID: "bd-ext1", Type: "waits-for", SpawnerID: "bd-ext1"}},
{name: "valid gated waits-for edge", edge: GraphApplyEdge{FromKey: "gate", ToKey: "spawner", Type: "waits-for", Gate: "any-children", SpawnerKey: "spawner"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
plan := &GraphApplyPlan{Nodes: twoNodes, Edges: []GraphApplyEdge{tc.edge}}
err := validateGraphApplyPlan(plan, nil, nil, GraphApplyOptions{})
if tc.wantErr == "" {
if err != nil {
t.Fatalf("expected plan to validate, got %v", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %v", tc.wantErr, err)
}
})
}
}
func TestGraphApplyEdgeDependencyGateMetadata(t *testing.T) {
resolve := map[string]string{"spawner": "bd-spawn1"}
t.Run("gate and spawner_key resolve into waits-for metadata", func(t *testing.T) {
dep, err := types.NewGraphEdgeDependency("bd-from", "bd-to", types.DepWaitsFor, "any-children", "spawner", "", "", resolve)
if err != nil {
t.Fatalf("NewGraphEdgeDependency: %v", err)
}
var meta types.WaitsForMeta
if err := json.Unmarshal([]byte(dep.Metadata), &meta); err != nil {
t.Fatalf("metadata not valid WaitsForMeta JSON: %v", err)
}
if meta.Gate != types.WaitsForAnyChildren || meta.SpawnerID != "bd-spawn1" {
t.Errorf("meta = %+v, want any-children gate with resolved spawner", meta)
}
})
t.Run("gate defaults to all-children when spawner is set", func(t *testing.T) {
dep, err := types.NewGraphEdgeDependency("bd-from", "bd-to", types.DepWaitsFor, "", "", "bd-ext1", "", resolve)
if err != nil {
t.Fatalf("NewGraphEdgeDependency: %v", err)
}
var meta types.WaitsForMeta
if err := json.Unmarshal([]byte(dep.Metadata), &meta); err != nil {
t.Fatalf("metadata not valid WaitsForMeta JSON: %v", err)
}
if meta.Gate != types.WaitsForAllChildren || meta.SpawnerID != "bd-ext1" {
t.Errorf("meta = %+v, want all-children default with explicit spawner", meta)
}
})
t.Run("plain edge carries no metadata and passes thread_id", func(t *testing.T) {
dep, err := types.NewGraphEdgeDependency("bd-from", "bd-to", types.DepRepliesTo, "", "", "", "thread-9", resolve)
if err != nil {
t.Fatalf("NewGraphEdgeDependency: %v", err)
}
if dep.Metadata != "" {
t.Errorf("Metadata = %q, want empty for ungated edge", dep.Metadata)
}
if dep.ThreadID != "thread-9" {
t.Errorf("ThreadID = %q, want thread-9", dep.ThreadID)
}
})
t.Run("ungated waits-for edge still gets all-children metadata", func(t *testing.T) {
// '{}' metadata must never be stored for waits-for deps: the gate SQL
// reads $.gate and NULL poisons its NOT(... AND ...) predicate,
// unblocking the gate as soon as the first child closes.
dep, err := types.NewGraphEdgeDependency("bd-from", "bd-to", types.DepWaitsFor, "", "", "", "", resolve)
if err != nil {
t.Fatalf("NewGraphEdgeDependency: %v", err)
}
var meta types.WaitsForMeta
if err := json.Unmarshal([]byte(dep.Metadata), &meta); err != nil {
t.Fatalf("metadata not valid WaitsForMeta JSON (%q): %v", dep.Metadata, err)
}
if meta.Gate != types.WaitsForAllChildren {
t.Errorf("gate = %q, want all-children default for ungated waits-for edge", meta.Gate)
}
})
t.Run("unresolved spawner_key errors instead of writing empty spawner", func(t *testing.T) {
if _, err := types.NewGraphEdgeDependency("bd-from", "bd-to", types.DepWaitsFor, "", "ghost", "", "", resolve); err == nil {
t.Fatal("expected error for unresolved spawner key")
}
})
}
// TestDetectUnknownGraphFields_CaseInsensitive: encoding/json binds
// case-variant keys to the matching field, so they must not be reported as
// silently dropped — only genuinely unknown names are.
func TestDetectUnknownGraphFields_CaseInsensitive(t *testing.T) {
planJSON := []byte(`{
"nodes": [{"key": "n", "title": "N", "Pinned": true, "Bogus": 1}]
}`)
got := detectUnknownGraphFields(planJSON)
if !reflect.DeepEqual(got, map[string][]string{`node["n"]`: {"Bogus"}}) {
t.Fatalf("case-variant known field misreported: %#v", got)
}
}
func TestValidateGraphApplyStorageClasses(t *testing.T) {
on := true
plan := &GraphApplyPlan{Nodes: []GraphApplyNode{
{Key: "a", Title: "A"},
{Key: "b", Title: "B", NoHistory: &on},
}}
t.Run("effective flag+node conflict caught at validation time", func(t *testing.T) {
_, err := validateGraphApplyStorageClasses(plan, GraphApplyOptions{Ephemeral: true}, false)
if err == nil || !strings.Contains(err.Error(), "mutually exclusive") {
t.Fatalf("expected effective ephemeral+no_history conflict, got %v", err)
}
})
t.Run("mixed storage classes rejected only when uniformity is required", func(t *testing.T) {
if _, err := validateGraphApplyStorageClasses(plan, GraphApplyOptions{}, false); err != nil {
t.Fatalf("embedded mode allows mixed plans, got %v", err)
}
_, err := validateGraphApplyStorageClasses(plan, GraphApplyOptions{}, true)
if err == nil || !strings.Contains(err.Error(), "uniform") {
t.Fatalf("expected uniformity error in proxied mode, got %v", err)
}
})
t.Run("resolved useWisp reported from node 0", func(t *testing.T) {
useWisp, err := validateGraphApplyStorageClasses(&GraphApplyPlan{Nodes: []GraphApplyNode{
{Key: "a", Title: "A", NoHistory: &on},
{Key: "b", Title: "B", NoHistory: &on},
}}, GraphApplyOptions{}, true)
if err != nil {
t.Fatalf("uniform wisp plan rejected: %v", err)
}
if !useWisp {
t.Error("useWisp = false, want true for no_history plan")
}
})
}
func TestValidateGraphApplyExplicitIDPrefixes(t *testing.T) {
plan := &GraphApplyPlan{Nodes: []GraphApplyNode{
{Key: "gen", Title: "Generated"},
{Key: "pinnedID", Title: "Pinned", ID: "zz-a1b2c3"},
}}
if err := validateGraphApplyExplicitIDPrefixes(plan, "bd", "", false); err == nil {
t.Fatal("expected foreign-prefix explicit id to be rejected")
} else if !strings.Contains(err.Error(), `node "pinnedID"`) {
t.Fatalf("error should name the node, got %v", err)
}
if err := validateGraphApplyExplicitIDPrefixes(plan, "zz", "", false); err != nil {
t.Fatalf("matching prefix rejected: %v", err)
}
if err := validateGraphApplyExplicitIDPrefixes(plan, "bd", "zz", false); err != nil {
t.Fatalf("allowed_prefixes rejected: %v", err)
}
if err := validateGraphApplyExplicitIDPrefixes(plan, "bd", "", true); err != nil {
t.Fatalf("--force rejected: %v", err)
}
}
// TestGraphApplyNodeCoversCreateIssueParams pins full issue-model parity
// between single-issue `bd create` and graph plans: every createIssueParams
// field must be addressable from a GraphApplyNode or listed here with a
// reason. This keeps the schema gap from silently reopening as create grows.
//
// Limitation: the check is name-based — it proves a same-named GraphApplyNode
// field exists, not that graphApplyNodeIssue actually wires it into its
// createIssueParams literal. A new field added everywhere but omitted from
// that literal would still pass here and materialize as a zero value; the
// value round-trip in TestEmbeddedCreateGraphAndBulk/graph_create_journey
// (renamed from graph_full_fields by bd-okxx4, #5291) is the wiring backstop.
func TestGraphApplyNodeCoversCreateIssueParams(t *testing.T) {
renamed := map[string]string{
"IssueType": "Type",
"InitialStatus": "Status",
}
excluded := map[string]string{
"CreatedBy": "always the ambient actor identity; plans do not impersonate creators",
}
nodeType := reflect.TypeOf(GraphApplyNode{})
paramsType := reflect.TypeOf(createIssueParams{})
for i := 0; i < paramsType.NumField(); i++ {
name := paramsType.Field(i).Name
if _, ok := excluded[name]; ok {
continue
}
if alias, ok := renamed[name]; ok {
name = alias
}
if _, ok := nodeType.FieldByName(name); !ok {
t.Errorf("createIssueParams field %q is not addressable from graph plans; add it to GraphApplyNode (or the exclusion list with a reason)", name)
}
}
}