beads/cmd/bd/update_embedded_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

934 lines
33 KiB
Go

//go:build cgo
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
)
// ===== Shared test helpers (used by both update and close tests) =====
// bdUpdate runs "bd update" with the given args and returns stdout.
// Retries on flock contention.
func bdUpdate(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
fullArgs := append([]string{"update"}, args...)
out, err := bdRunWithFlockRetry(t, bd, dir, fullArgs...)
if err != nil {
t.Fatalf("bd update %s failed: %v\n%s", strings.Join(args, " "), err, out)
}
return string(out)
}
// bdUpdateFail runs "bd update" expecting failure.
func bdUpdateFail(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
fullArgs := append([]string{"update"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected bd update %s to fail, but it succeeded:\n%s", strings.Join(args, " "), out)
}
return string(out)
}
// wantNotesRefusal is the expected notes-overwrite refusal line, shared by the
// embedded and proxied update tests. Spelled as a literal, not via the
// production errNotesOverwriteRefusal: reusing the constructor would make the
// wording self-verifying.
func wantNotesRefusal(id string) string {
return id + ": --notes would replace existing notes; use --force to overwrite (or --append-notes to preserve history)"
}
// bdUpdateCapture runs "bd update" expecting success, returning stdout and
// stderr separately (stdout may be JSON; warnings must not pollute it).
func bdUpdateCapture(t *testing.T, bd, dir string, args ...string) (stdout, stderr string) {
t.Helper()
fullArgs := append([]string{"update"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
outBuf, errBuf, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd update %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, outBuf.String(), errBuf.String())
}
return outBuf.String(), errBuf.String()
}
func bdRunInTimezone(t *testing.T, bd, dir, timezone string, args ...string) string {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = dir
for _, env := range bdEnv(dir) {
if !strings.HasPrefix(env, "TZ=") {
cmd.Env = append(cmd.Env, env)
}
}
cmd.Env = append(cmd.Env, "TZ="+timezone)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd %s failed in %s: %v\n%s", strings.Join(args, " "), timezone, err, out)
}
return string(out)
}
func embeddedCurrentCommit(t *testing.T, beadsDir, database string) string {
t.Helper()
store, err := embeddeddolt.Open(t.Context(), beadsDir, database, "main")
if err != nil {
t.Fatalf("open embedded store: %v", err)
}
defer func() { _ = store.Close() }()
head, err := store.GetCurrentCommit(t.Context())
if err != nil {
t.Fatalf("GetCurrentCommit: %v", err)
}
if head == "" {
t.Fatal("GetCurrentCommit returned empty hash")
}
return head
}
// bdShowJSON runs "bd show <id> --json" and returns the raw JSON output.
func bdShowJSON(t *testing.T, bd, dir, id string) string {
t.Helper()
cmd := exec.Command(bd, "show", id, "--json")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd show %s --json failed: %v\nstdout:\n%s\nstderr:\n%s", id, err, stdout.String(), stderr.String())
}
return stdout.String()
}
// hasLabel checks if a label is present in the issue's labels.
func hasLabel(issue *types.Issue, label string) bool {
for _, l := range issue.Labels {
if l == label {
return true
}
}
return false
}
// parseShowJSON parses the first JSON object from bd show --json output,
// which may be wrapped in an array or have non-JSON lines before it.
func parseShowJSON(t *testing.T, raw string) json.RawMessage {
t.Helper()
start := strings.Index(raw, "{")
if start < 0 {
t.Fatalf("no JSON object in output: %s", raw)
}
dec := json.NewDecoder(strings.NewReader(raw[start:]))
var obj json.RawMessage
if err := dec.Decode(&obj); err != nil {
t.Fatalf("parse JSON object: %v\nraw: %s", err, raw[start:])
}
return obj
}
// showLabels returns labels from bd show --json output (uses IssueDetails which includes labels).
func showLabels(t *testing.T, bd, dir, id string) []string {
t.Helper()
raw := bdShowJSON(t, bd, dir, id)
obj := parseShowJSON(t, raw)
var details struct {
Labels []string `json:"labels"`
}
if err := json.Unmarshal(obj, &details); err != nil {
t.Fatalf("parse labels: %v", err)
}
return details.Labels
}
// showDeps returns dependency IDs from bd show --json output.
func showDeps(t *testing.T, bd, dir, id string) []struct {
ID string `json:"id"`
Type string `json:"dependency_type"`
} {
t.Helper()
raw := bdShowJSON(t, bd, dir, id)
obj := parseShowJSON(t, raw)
var details struct {
Dependencies []struct {
ID string `json:"id"`
Type string `json:"dependency_type"`
} `json:"dependencies"`
}
if err := json.Unmarshal(obj, &details); err != nil {
t.Fatalf("parse deps: %v", err)
}
return details.Dependencies
}
// ===== Update tests =====
func TestEmbeddedUpdateBatchAutoCommitDoesNotAdvanceHead(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt update tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "ub")
issue := bdCreate(t, bd, dir, "Batch update")
before := embeddedCurrentCommit(t, beadsDir, "ub")
cmd := exec.Command(bd, "--dolt-auto-commit", "batch", "update", issue.ID, "--title", "Deferred batch update")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd --dolt-auto-commit batch update failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
after := embeddedCurrentCommit(t, beadsDir, "ub")
if after != before {
t.Fatalf("batch-mode update advanced HEAD; before=%s after=%s", before, after)
}
}
func TestEmbeddedUpdateRoutedStoreCommitsTargetHead(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt update tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "src")
targetDir := filepath.Join(dir, "target-repo")
if err := os.MkdirAll(targetDir, 0750); err != nil {
t.Fatal(err)
}
initGitRepoAt(t, targetDir)
runBDInit(t, bd, targetDir, "--prefix", "tgt")
issue := bdCreate(t, bd, targetDir, "Routed target issue")
route := `{"prefix":"tgt-","path":"target-repo"}` + "\n"
if err := os.WriteFile(filepath.Join(dir, ".beads", "routes.jsonl"), []byte(route), 0644); err != nil {
t.Fatalf("write routes.jsonl: %v", err)
}
targetBeadsDir := filepath.Join(targetDir, ".beads")
before := embeddedCurrentCommit(t, targetBeadsDir, "tgt")
bdUpdate(t, bd, dir, issue.ID, "--title", "Updated through route")
after := embeddedCurrentCommit(t, targetBeadsDir, "tgt")
if after == before {
t.Fatalf("routed update did not advance target HEAD; before=%s after=%s", before, after)
}
targetStore := openStore(t, targetBeadsDir, "tgt")
got, err := targetStore.GetIssue(t.Context(), issue.ID)
if err != nil {
t.Fatalf("GetIssue in target: %v", err)
}
if got.Title != "Updated through route" {
t.Fatalf("target title = %q, want routed update title", got.Title)
}
}
// TestEmbeddedUpdateFields and TestEmbeddedUpdateLifecycle were split from
// TestEmbeddedUpdate (originally ~267s, measured under --config=embedded)
// into 2 top-level tests over disjoint subtest groups, for CI shard balance
// (see scripts/ci/embedded_cmd_test_durations.json and engdocs/TESTING.md). Every original
// subtest is preserved exactly once.
func TestEmbeddedUpdateFields(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "tu")
t.Run("update_direct_flag_mapping", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Multi update", "--type", "task", "--metadata", `{"remove":"me"}`)
out := bdUpdate(t, bd, dir,
"--json", issue.ID,
"--status", "in_progress",
"--assignee", "bob",
"--priority", "1",
"--description", "Updated description",
"--design", "Design notes here",
"--acceptance", "AC text",
"--external-ref", "gh-42",
"--estimate", "60",
"--await-id", "run-123",
"--due", "2099-01-15",
"--set-metadata", "team=platform",
"--set-metadata", "score=99",
"--unset-metadata", "remove",
"--no-history",
)
var updated []*types.Issue
if err := json.Unmarshal([]byte(out), &updated); err != nil {
t.Fatalf("parse direct update response: %v\n%s", err, out)
}
if len(updated) != 1 {
t.Fatalf("direct update returned %d issues, want 1: %s", len(updated), out)
}
got := updated[0]
if got.Status != types.StatusInProgress {
t.Errorf("expected status in_progress, got %s", got.Status)
}
if got.Assignee != "bob" {
t.Errorf("expected assignee bob, got %q", got.Assignee)
}
if got.Priority != 1 {
t.Errorf("expected priority 1, got %d", got.Priority)
}
if got.Description != "Updated description" {
t.Errorf("expected updated description, got %q", got.Description)
}
if got.Design != "Design notes here" {
t.Errorf("expected design notes, got %q", got.Design)
}
if got.AcceptanceCriteria != "AC text" {
t.Errorf("expected acceptance criteria, got %q", got.AcceptanceCriteria)
}
if got.ExternalRef == nil || *got.ExternalRef != "gh-42" {
t.Errorf("expected external_ref gh-42, got %v", got.ExternalRef)
}
if got.EstimatedMinutes == nil || *got.EstimatedMinutes != 60 {
t.Errorf("expected estimated_minutes 60, got %v", got.EstimatedMinutes)
}
if got.AwaitID != "run-123" {
t.Errorf("expected await_id run-123, got %q", got.AwaitID)
}
if got.DueAt == nil || got.DueAt.Format("2006-01-02") != "2099-01-15" {
t.Errorf("expected due_at 2099-01-15, got %v", got.DueAt)
}
if !got.NoHistory {
t.Error("expected no_history true")
}
var metadata map[string]any
if err := json.Unmarshal(got.Metadata, &metadata); err != nil {
t.Fatalf("parse updated metadata %q: %v", got.Metadata, err)
}
if metadata["team"] != "platform" {
t.Errorf("metadata team = %v, want platform", metadata["team"])
}
// --set-metadata infers scalar types (the v1.2.2 contract): 99 lands as a
// JSON number, not the string "99".
if metadata["score"] != float64(99) {
t.Errorf("metadata score = %#v, want the JSON number 99", metadata["score"])
}
if _, ok := metadata["remove"]; ok {
t.Errorf("metadata still contains removed key: %v", metadata)
}
conflict := bdUpdateFail(t, bd, dir, issue.ID,
"--metadata", `{"other":"value"}`,
"--set-metadata", "team=other",
)
if !strings.Contains(conflict, "cannot combine --metadata with --set-metadata or --unset-metadata") {
t.Errorf("expected exact metadata conflict error, got: %s", conflict)
}
out = bdUpdate(t, bd, dir, "--json", issue.ID, "--due", "", "--history")
updated = nil
if err := json.Unmarshal([]byte(out), &updated); err != nil {
t.Fatalf("parse clearing update response: %v\n%s", err, out)
}
if len(updated) != 1 {
t.Fatalf("clearing update returned %d issues, want 1: %s", len(updated), out)
}
if updated[0].DueAt != nil {
t.Errorf("expected due_at nil after clear, got %v", updated[0].DueAt)
}
if updated[0].NoHistory {
t.Error("expected no_history false after --history")
}
})
t.Run("update_type_custom", func(t *testing.T) {
// Register "agent" as a custom type via bd config (GH#3030).
// This writes to Dolt only, NOT to .beads/config.yaml.
cfgCmd := exec.Command(bd, "config", "set", "types.custom", "agent,spike")
cfgCmd.Dir = dir
cfgCmd.Env = bdEnv(dir)
if out, err := cfgCmd.CombinedOutput(); err != nil {
t.Fatalf("bd config set types.custom failed: %v\n%s", err, out)
}
issue := bdCreate(t, bd, dir, "Custom type update", "--type", "task")
// Before the fix (GH#3030), this would fail with "invalid issue type"
// because the CLI-level validation could not read custom types from Dolt.
bdUpdate(t, bd, dir, issue.ID, "--type", "agent")
got := bdShow(t, bd, dir, issue.ID)
if string(got.IssueType) != "agent" {
t.Errorf("expected type agent, got %s", got.IssueType)
}
})
// GH#3902: --external-ref "" must clear to SQL NULL (matching buildCreateIssue's
// pointer semantics), not write an empty string. Otherwise sync/tracker code
// that checks ExternalRef == nil silently misclassifies cleared refs as still
// tracked, and two cleared issues round-trip with different JSON shapes
// (cleared via CLI emits "external_ref":"" while never-set issues omit the field).
t.Run("update_external_ref_clear", func(t *testing.T) {
a := bdCreate(t, bd, dir, "ExtRef clear A", "--type", "task", "--external-ref", "ref-a")
b := bdCreate(t, bd, dir, "ExtRef clear B", "--type", "task", "--external-ref", "ref-b")
bdUpdate(t, bd, dir, a.ID, "--external-ref", "")
// Repeat clear must succeed for a second issue — historical UNIQUE
// constraint repro from the issue report.
bdUpdate(t, bd, dir, b.ID, "--external-ref", "")
gotA := bdShow(t, bd, dir, a.ID)
gotB := bdShow(t, bd, dir, b.ID)
if gotA.ExternalRef != nil {
t.Errorf("expected A.external_ref to be nil after clear, got %q", *gotA.ExternalRef)
}
if gotB.ExternalRef != nil {
t.Errorf("expected B.external_ref to be nil after clear, got %q", *gotB.ExternalRef)
}
// JSON output: cleared ref should be omitted via omitempty, not emitted as "".
rawA := bdShowJSON(t, bd, dir, a.ID)
if strings.Contains(rawA, `"external_ref"`) {
t.Errorf("expected external_ref field to be omitted from JSON after clear, got: %s", rawA)
}
})
t.Run("update_notes_overwrite_requires_force", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes force test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--notes", "replacement notes")
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(out, wantErr) {
t.Errorf("expected output to contain %q, got: %s", wantErr, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_force_warns", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes warning test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
stdout, stderr := bdUpdateCapture(t, bd, dir, issue.ID, "--notes", "replacement notes", "--force")
warning := fmt.Sprintf("warning: %s: --force replaced existing notes (--append-notes preserves history)", issue.ID)
if !strings.Contains(stderr, warning) {
t.Errorf("expected stderr to contain %q, got: %s", warning, stderr)
}
if strings.Contains(stdout, "warning:") {
t.Errorf("warning must not appear on stdout, got: %s", stdout)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "replacement notes" {
t.Errorf("expected notes %q, got %q", "replacement notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_if_assignee_requires_force", func(t *testing.T) {
// --force and --if-assignee are no longer mutually exclusive at the
// flag level (that exclusion was the footgun: it made --force
// unpassable alongside --if-assignee, so a caller pairing --notes
// with --if-assignee could not opt into overwriting existing notes at
// all). Without --force the overwrite is still refused.
issue := bdCreate(t, bd, dir, "Notes plus if-assignee test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--if-assignee", "", "--notes", "replacement notes")
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(out, wantErr) {
t.Errorf("expected output to contain %q, got: %s", wantErr, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_if_assignee_and_force_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes plus if-assignee force test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
bdUpdate(t, bd, dir, issue.ID, "--if-assignee", "", "--notes", "replacement notes", "--force")
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "replacement notes" {
t.Errorf("expected notes %q, got %q", "replacement notes", got.Notes)
}
})
t.Run("update_empty_notes_refused", func(t *testing.T) {
// GH#6021: `--notes ""` is what a dead command substitution collapses
// to, so an unforced wipe must not look like success. The deliberate
// clear has its own verb, --clear-notes.
issue := bdCreate(t, bd, dir, "Notes clear guard test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--notes", "")
if !strings.Contains(out, "--clear-notes") {
t.Errorf("expected refusal naming --clear-notes, got:\n%s", out)
}
// --force opens the overwrite fence, not this guard: the empty value
// stays refused because the bytes still cannot prove intent.
out = bdUpdateFail(t, bd, dir, issue.ID, "--notes", "", "--force")
if !strings.Contains(out, "--clear-notes") {
t.Errorf("expected forced empty-notes refusal naming --clear-notes, got:\n%s", out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_clear_notes_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes deliberate clear test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
// No --force: the fence exempts clears, so the verb alone authorizes
// the erase.
bdUpdate(t, bd, dir, issue.ID, "--clear-notes")
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "" {
t.Errorf("expected notes cleared, got %q", got.Notes)
}
})
t.Run("update_clear_notes_conflicts_with_notes_flags", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes clear conflict test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
for _, extra := range [][]string{
{"--notes", "replacement"},
{"--append-notes", "more"},
} {
args := append([]string{issue.ID, "--clear-notes"}, extra...)
out := bdUpdateFail(t, bd, dir, args...)
if !strings.Contains(out, "none of the others can be") {
t.Errorf("expected mutual-exclusion error for %v, got:\n%s", extra, out)
}
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_defer", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Defer test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2099-01-15")
got := bdShow(t, bd, dir, issue.ID)
if got.DeferUntil == nil {
t.Error("expected defer_until to be set")
}
// GH#3233: --defer should also set status=deferred for consistency with `bd defer`
if string(got.Status) != "deferred" {
t.Errorf("expected status=deferred, got %q", got.Status)
}
})
}
func TestEmbeddedUpdateLifecycle(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "tu")
t.Run("relative_defer_is_persisted_in_UTC", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "UTC defer test", "--type", "task")
bdRunInTimezone(t, bd, dir, "America/Denver", "update", issue.ID, "--defer", "+1h")
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), filepath.Join(beadsDir, "embeddeddolt"), "tu", "main")
if err != nil {
t.Fatalf("open embedded SQL: %v", err)
}
defer func() { _ = cleanup() }()
var future, bounded bool
if err := db.QueryRowContext(t.Context(), `
SELECT defer_until > UTC_TIMESTAMP(),
defer_until <= DATE_ADD(UTC_TIMESTAMP(), INTERVAL 2 HOUR)
FROM issues WHERE id = ?
`, issue.ID).Scan(&future, &bounded); err != nil {
t.Fatalf("query persisted defer_until: %v", err)
}
if !future || !bounded {
t.Fatalf("relative defer UTC bounds = future:%t bounded:%t, want true/true", future, bounded)
}
})
t.Run("show_renders_scheduled_dates_in_local_time", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Local date display test", "--type", "task")
const date = "2099-01-15"
bdRunInTimezone(t, bd, dir, "Pacific/Auckland", "update", issue.ID, "--due", date, "--defer", date)
output := bdRunInTimezone(t, bd, dir, "Pacific/Auckland", "--no-color", "show", issue.ID)
for _, want := range []string{"Due: " + date, "Deferred: " + date} {
if !strings.Contains(output, want) {
t.Errorf("bd show output missing %q:\n%s", want, output)
}
}
})
t.Run("update_defer_respects_explicit_status", func(t *testing.T) {
// GH#3233: explicit --status should win over the implicit deferred set by --defer
issue := bdCreate(t, bd, dir, "Defer+status test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2099-01-15", "--status", "in_progress")
got := bdShow(t, bd, dir, issue.ID)
if string(got.Status) != "in_progress" {
t.Errorf("expected explicit status=in_progress to win, got %q", got.Status)
}
})
t.Run("update_defer_clear", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Defer clear test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2099-01-15")
bdUpdate(t, bd, dir, issue.ID, "--defer", "")
got := bdShow(t, bd, dir, issue.ID)
if got.DeferUntil != nil {
t.Error("expected defer_until to be cleared")
}
// GH#3233: clearing defer on a deferred issue must restore ready visibility
if string(got.Status) != "open" {
t.Errorf("expected status=open after clearing defer, got %q", got.Status)
}
})
t.Run("update_defer_past_date_keeps_status_open", func(t *testing.T) {
// GH#3233: past-date --defer shouldn't flip status to deferred, because
// the warning promises the issue "will appear in bd ready immediately".
issue := bdCreate(t, bd, dir, "Past defer test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2000-01-01")
got := bdShow(t, bd, dir, issue.ID)
if string(got.Status) == "deferred" {
t.Errorf("past --defer should not set status=deferred, got %q", got.Status)
}
})
t.Run("update_defer_clear_preserves_non_deferred_status", func(t *testing.T) {
// GH#3233: clearing defer_until shouldn't clobber a non-deferred status
// that was set independently (e.g. in_progress).
issue := bdCreate(t, bd, dir, "Defer clear keep status test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--status", "in_progress")
bdUpdate(t, bd, dir, issue.ID, "--defer", "")
got := bdShow(t, bd, dir, issue.ID)
if string(got.Status) != "in_progress" {
t.Errorf("expected status=in_progress to be preserved, got %q", got.Status)
}
})
t.Run("update_claim_already_claimed", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Claim fail test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "alice")
out := bdUpdateFail(t, bd, dir, issue.ID, "--claim")
if !strings.Contains(out, "already assigned to") {
t.Errorf("expected 'already assigned to' error, got: %s", out)
}
// The refusal must steer toward the holder, not teach an
// unclaim-then-claim eviction of a live claim (bd-at6rc / wy-zs5s2).
if !strings.Contains(out, "coordinate with the holder") {
t.Errorf("refusal should say coordinate-with-holder, got: %s", out)
}
if strings.Contains(out, "to release it before re-claiming") {
t.Errorf("refusal must not suggest plain unclaim of a foreign claim, got: %s", out)
}
// Nor may it name unclaim or --force at all: copy that names an
// eviction command gets pattern-matched by batch agents into
// `unclaim --force; claim` — a stronger steamroller than the one
// this fix removed (wy-yuclk).
if strings.Contains(out, "unclaim") || strings.Contains(out, "--force") {
t.Errorf("claim refusal must not name an eviction command, got: %s", out)
}
})
// A batch where one claim is lost and another is won must exit non-zero, so
// the lost claim is not hidden from exit-code automation (beads audit
// finding #10). The winner is still committed.
t.Run("update_claim_batch_partial_loss_exits_nonzero", func(t *testing.T) {
lost := bdCreate(t, bd, dir, "Batch lost", "--type", "task")
won := bdCreate(t, bd, dir, "Batch won", "--type", "task")
// Pre-assign `lost` to someone else so the default actor's claim loses.
bdUpdate(t, bd, dir, lost.ID, "--assignee", "alice")
out := bdUpdateFail(t, bd, dir, lost.ID, won.ID, "--claim")
if !strings.Contains(out, "already assigned to") {
t.Errorf("expected 'already assigned to' error in batch output, got: %s", out)
}
// The winning claim still lands despite the batch exiting non-zero.
gotWon := bdShow(t, bd, dir, won.ID)
if gotWon.Status != types.StatusInProgress {
t.Errorf("winning claim %s: status = %s, want in_progress", won.ID, gotWon.Status)
}
// The lost issue is untouched.
gotLost := bdShow(t, bd, dir, lost.ID)
if gotLost.Assignee != "alice" {
t.Errorf("lost issue %s assignee = %q, want alice (unchanged)", lost.ID, gotLost.Assignee)
}
})
t.Run("update_parent_change", func(t *testing.T) {
epic1 := bdCreate(t, bd, dir, "Old parent", "--type", "epic")
epic2 := bdCreate(t, bd, dir, "New parent", "--type", "epic")
child := bdCreate(t, bd, dir, "Reparent child", "--type", "task")
bdUpdate(t, bd, dir, child.ID, "--parent", epic1.ID)
bdUpdate(t, bd, dir, child.ID, "--parent", epic2.ID)
deps := showDeps(t, bd, dir, child.ID)
hasOld, hasNew := false, false
for _, d := range deps {
if d.Type == "parent-child" {
if d.ID == epic1.ID {
hasOld = true
}
if d.ID == epic2.ID {
hasNew = true
}
}
}
if hasOld {
t.Error("expected old parent dep to be removed")
}
if !hasNew {
t.Error("expected new parent dep to exist")
}
})
t.Run("update_persistent", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Persistent test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--ephemeral")
bdUpdate(t, bd, dir, issue.ID, "--persistent")
got := bdShow(t, bd, dir, issue.ID)
if got.Ephemeral {
t.Error("expected ephemeral to be false after --persistent")
}
})
t.Run("update_dolt_commit", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Dolt commit test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--status", "in_progress")
// Verify a Dolt commit exists by querying dolt_log.
dataDir := filepath.Join(beadsDir, "embeddeddolt")
cfg, _ := configfile.Load(beadsDir)
database := ""
if cfg != nil {
database = cfg.GetDoltDatabase()
}
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer cleanup()
var commitCount int
err = db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM dolt_log").Scan(&commitCount)
if err != nil {
t.Fatalf("query dolt_log: %v", err)
}
// At minimum: init schema commit + create commit + update commit
if commitCount < 3 {
t.Errorf("expected at least 3 dolt commits, got %d", commitCount)
}
})
}
// TestEmbeddedUpdateConcurrent exercises create, update, and list operations
// concurrently to verify EmbeddedDoltStore handles concurrent CLI invocations
// without panics, data corruption, or deadlocks.
//
// issuesPerWorker was 5 (F1 review S1): under real CI-like load (several
// Bazel shards running concurrently, -test.parallel=4), this test's 10
// workers x 5 issues x 4 serialized `bd` subprocess invocations each (create,
// 2 updates, list; writes serialize behind the embedded engine's single-
// writer lock) measured ~452s -- the queueing-delay explanation once
// proposed for this and three other outliers was wrong (see
// scripts/ci/embedded_cmd_test_durations.json's header); this is genuine
// CPU-bound work under contention. issuesPerWorker=2 keeps the same
// invariants under test (duplicate-ID detection across all numWorkers
// concurrent processes; each worker's own list-count-is-non-decreasing check
// still exercises its loop body once) while cutting serialized work to 40%.
func TestEmbeddedUpdateConcurrent(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "cu")
const (
numWorkers = 10
issuesPerWorker = 2
)
type workerResult struct {
worker int
ids []string
listCounts []int
err error
}
results := make([]workerResult, numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for w := 0; w < numWorkers; w++ {
go func(worker int) {
defer wg.Done()
r := workerResult{worker: worker}
for i := 0; i < issuesPerWorker; i++ {
// Create an issue.
title := fmt.Sprintf("w%d-issue-%d", worker, i)
out, err := bdRunWithFlockRetry(t, bd, dir, "create", "--silent", title)
if err != nil {
r.err = fmt.Errorf("create %d: %v\n%s", i, err, out)
results[worker] = r
return
}
id := strings.TrimSpace(string(out))
if id == "" {
r.err = fmt.Errorf("create %d: empty ID", i)
results[worker] = r
return
}
r.ids = append(r.ids, id)
// Update: change status to in_progress.
uCmd := exec.Command(bd, "update", id, "--status", "in_progress")
uCmd.Dir = dir
uCmd.Env = bdEnv(dir)
uOut, err := uCmd.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("update status %d: %v\n%s", i, err, uOut)
results[worker] = r
return
}
// Update: set priority and assignee.
uCmd2 := exec.Command(bd, "update", id, "--priority", fmt.Sprintf("%d", worker%4), "--assignee", fmt.Sprintf("agent-%d", worker))
uCmd2.Dir = dir
uCmd2.Env = bdEnv(dir)
uOut2, err := uCmd2.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("update fields %d: %v\n%s", i, err, uOut2)
results[worker] = r
return
}
// Update: add a label.
uCmd3 := exec.Command(bd, "update", id, "--add-label", fmt.Sprintf("team-%d", worker%3))
uCmd3.Dir = dir
uCmd3.Env = bdEnv(dir)
uOut3, err := uCmd3.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("update label %d: %v\n%s", i, err, uOut3)
results[worker] = r
return
}
// List to verify consistency (interleaved with writes).
listCmd := exec.Command(bd, "list", "--json", "--limit", "0")
listCmd.Dir = dir
listCmd.Env = bdEnv(dir)
listStdout, listStderr, err := runCommandBuffers(t, listCmd)
if err != nil {
r.err = fmt.Errorf("list after update %d: %v\nstdout:\n%s\nstderr:\n%s", i, err, listStdout.String(), listStderr.String())
results[worker] = r
return
}
s := listStdout.String()
start := strings.Index(s, "[")
if start < 0 {
r.listCounts = append(r.listCounts, 0)
continue
}
var issues []json.RawMessage
if jsonErr := json.Unmarshal([]byte(s[start:]), &issues); jsonErr != nil {
r.err = fmt.Errorf("list parse %d: %v\nstdout:\n%s\nstderr:\n%s", i, jsonErr, s, listStderr.String())
results[worker] = r
return
}
r.listCounts = append(r.listCounts, len(issues))
}
results[worker] = r
}(w)
}
wg.Wait()
// Check for errors and collect IDs.
allIDs := make(map[string]bool)
var successes int
for _, r := range results {
if r.err != nil {
if !strings.Contains(r.err.Error(), "one writer at a time") {
t.Errorf("worker %d failed: %v", r.worker, r.err)
}
continue
}
successes++
for _, id := range r.ids {
if allIDs[id] {
t.Errorf("duplicate ID %q from worker %d", id, r.worker)
}
allIDs[id] = true
}
}
if successes == 0 {
t.Fatal("all workers failed — expected at least 1 success")
}
expectedIDs := successes * issuesPerWorker
if len(allIDs) != expectedIDs {
t.Errorf("expected %d unique IDs from %d successful workers, got %d", expectedIDs, successes, len(allIDs))
}
// Verify all successfully created issues exist and were updated correctly.
store := openStore(t, beadsDir, "cu")
stats, err := store.GetStatistics(t.Context())
if err != nil {
t.Fatalf("GetStatistics: %v", err)
}
if stats.TotalIssues < len(allIDs) {
t.Errorf("expected at least %d issues in DB, got %d", len(allIDs), stats.TotalIssues)
}
// Spot-check: every issue should be in_progress with an assignee.
for id := range allIDs {
issue, err := store.GetIssue(t.Context(), id)
if err != nil {
t.Errorf("GetIssue(%s): %v", id, err)
continue
}
if issue.Status != types.StatusInProgress {
t.Errorf("issue %s: expected status in_progress, got %s", id, issue.Status)
}
if issue.Assignee == "" {
t.Errorf("issue %s: expected assignee to be set", id)
}
}
// Verify list counts were monotonically non-decreasing per worker.
for _, r := range results {
if r.err != nil {
continue
}
for i := 1; i < len(r.listCounts); i++ {
if r.listCounts[i] < r.listCounts[i-1] {
t.Errorf("worker %d: list count decreased from %d to %d at step %d",
r.worker, r.listCounts[i-1], r.listCounts[i], i)
}
}
}
t.Logf("created and updated %d issues across %d/%d successful workers, %d in DB",
len(allIDs), successes, numWorkers, stats.TotalIssues)
}