test(cmd/bd): drop dead unsupported-storage test, CWD-independent bd fallback build, stop BEADS_DIR leaking between in-process runs (#7171)

* test(delete): drop stale TestDeleteIssueUnsupportedStorage

The test asserted that deleteIssue returns "delete operation not supported
by this storage backend" when the global store is nil. That error came
from a type assertion to a deleter interface that a5da57e39 (Phase 7:
remove storage factory/memory backend/provider abstraction) removed:
store is now storage.DoltStorage, whose method set always includes
DeleteIssue, so there is no unsupported backend left to report. With the
assertion gone, the test's nil store is just a nil-interface method call
and panics at deleteIssue, killing the whole cmd/bd test binary.

The nil store is not reachable in production: deleteIssue's only caller
(bd doctor --check=pollution --clean) has already queried the store to
find the issues it deletes. So the test constructs an impossible state
for a removed behavior; delete it rather than reintroduce a dead branch.

No CI lane ran it: it needs the integration tag and a Dolt test server
(testDoltServerPort != 0), and every integration lane that builds
cmd/bd (main.yml integration cmd/bd shards, nightly Full Test Suite,
bazel --config=integration) sets BEADS_TEST_SKIP=dolt, while the
proxied/dolt-server lanes run only their TestProxiedServer*/
TestServerMode* manifests. It only ran in local integration runs with
Docker or a matching dolt.

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

* test(cmd/bd): build the fallback bd by package path, independent of CWD

When BEADS_TEST_BD_BINARY is unset, buildEmbeddedBD and its sibling
helpers fall back to `go build -tags gms_pure_go -o X .`, which builds
whatever package is in the process's working directory. That is cmd/bd
only if the first caller of the sync.Once has not chdir'd into a fixture
and the test binary was started in cmd/bd. A precompiled test binary run
from the repo root (the pr-risk pattern) builds the root library package
instead: go writes a non-executable archive to X and the test dies with
"fork/exec .../bd: permission denied" (reproduced with TestEmbeddedCount).

Add goBuildBDCommand: the same non-race -tags gms_pure_go build CI
prebuilds BEADS_TEST_BD_BINARY with, naming
github.com/steveyegge/beads/cmd/bd explicitly and running in cmd/bd's
source directory, resolved at package init (this file's compiled-in path,
else the start-up working directory) before any test can chdir. Use it in
buildEmbeddedBD and the other copies of the pattern (cli_fast,
doctor_repair, explicit_db_nodb, init_permissions, scripttest,
shared_server, buildBDForInitTests); migrationFrontDoorBinary keeps its
untagged cgo build but gets the same package path and directory.
TestGoBuildBDCommandIsCWDIndependent checks it from a chdir'd temp dir
with go list (no link).

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

* test(cmd/bd): stop in-process bd from leaking BEADS_DIR into later tests

TestResolvedConfigRepoRoot's two CWD-discovery subtests ("uses local
workspace from subdirectory", "uses worktree fallback when local .beads
is absent") failed in full cmd/bd runs with "no active beads workspace
found" but passed alone. Cause: runBDInProcess / runBDInProcessAllowError
run rootCmd.Execute in the test process, and PersistentPreRun exports the
selected workspace with a raw os.Setenv("BEADS_DIR", ...) that nothing
restores. After any TestCLI_* test, BEADS_DIR still names that test's
since-deleted bd-cli-test-* fixture; FindBeadsDir honors an explicit
BEADS_DIR before walking from CWD, finds nothing there, and reports no
workspace. Minimal repro: -run '^(TestCLI_Ready|TestResolvedConfigRepoRoot)$'.

The leak also broke later TestCLI_* tests themselves: with
-run '^(TestCLI_.*|TestResolvedConfigRepoRoot)$' against a Dolt test
server, failures drop from 47 to 20 with this change and no new ones (the
remaining 20 are leftover cobra flag values between in-process runs, a
separate issue).

- runBDInProcess(AllowError): snapshot os.Environ() around Execute and
  restore exactly the keys it changed (restoreEnvSnapshot).
- TestResolvedConfigRepoRoot: clear BEADS_DIR (t.Setenv) in the two
  subtests that test CWD discovery, so neither a leak nor a developer's
  exported BEADS_DIR decides them.

Not host-specific (HOME, global git config and ceilings play no part),
and CI never saw it: the TestCLI_* leakers need a Dolt test server, and
every CI lane that runs cmd/bd's integration tests sets
BEADS_TEST_SKIP=dolt, so they skip and BEADS_DIR is never set.

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

* test(delete): expect storage.ErrNotFound after delete in TestDeleteIssueWrapper

"successful issue deletion" asserted that GetIssue returns (nil, nil)
for a deleted issue; the Dolt store reports a missing issue as
storage.ErrNotFound, so the subtest failed with "GetIssue failed: not
found: issue test-xxx" whenever it ran. Like TestDeleteIssueUnsupportedStorage
it needs the integration tag and a Dolt test server, which no CI lane
provides to cmd/bd (BEADS_TEST_SKIP=dolt), so it rotted unseen.

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 Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-10-03 23:44:37 -07:00 • committed by GitHub
commit cdda0dffa5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 126 additions and 45 deletions

View file

@ -144,6 +144,38 @@ func createTempDirWithCleanup(t *testing.T) string {
return tmpDir
}
// restoreEnvSnapshot puts the process environment back to before, a prior
// os.Environ(), touching only the keys that differ. An in-process
// rootCmd.Execute mutates the environment with raw os.Setenv and restores
// nothing (PersistentPreRun exports the selected workspace as BEADS_DIR,
// loads the workspace's .beads/.env, ...); left in place, the BEADS_DIR of a
// since-deleted fixture makes every later test's workspace discovery report
// "no active beads workspace found" (e.g. TestResolvedConfigRepoRoot).
func restoreEnvSnapshot(before []string) {
want := make(map[string]string, len(before))
for _, kv := range before {
if k, v, ok := strings.Cut(kv, "="); ok && k != "" {
want[k] = v
}
}
for _, kv := range os.Environ() {
k, v, ok := strings.Cut(kv, "=")
if !ok || k == "" {
continue
}
if old, had := want[k]; !had {
_ = os.Unsetenv(k)
} else if old != v {
_ = os.Setenv(k, old)
}
}
for k, v := range want {
if _, ok := os.LookupEnv(k); !ok {
_ = os.Setenv(k, v)
}
}
}
// runBDInProcess runs bd commands in-process by calling rootCmd.Execute
// This is ~10-20x faster than exec.Command because it avoids process spawn overhead
func runBDInProcess(t *testing.T, dir string, args ...string) string {
@ -180,7 +212,9 @@ func runBDInProcess(t *testing.T, dir string, args ...string) string {
os.Args = append([]string{"bd"}, args...)
// Execute command
envBefore := os.Environ()
err := rootCmd.Execute()
restoreEnvSnapshot(envBefore)
// Close and clean up all global state to prevent contamination between tests
if store != nil {
@ -1042,7 +1076,7 @@ func init() {
panic(err)
}
testBD = filepath.Join(tmpDir, bdBinary)
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", testBD, ".")
cmd := goBuildBDCommand(testBD)
if out, err := cmd.CombinedOutput(); err != nil {
panic(string(out))
}
@ -1234,7 +1268,9 @@ func runBDInProcessAllowError(t *testing.T, dir string, args ...string) (string,
rootCmd.SetArgs(args)
os.Args = append([]string{"bd"}, args...)
envBefore := os.Environ()
cmdErr := rootCmd.Execute()
restoreEnvSnapshot(envBefore)
if store != nil {
store.Close()

View file

@ -758,6 +758,10 @@ func TestResolvedConfigRepoRoot(t *testing.T) {
t.Fatalf("Failed to create sub dir: %v", err)
}
// CWD discovery is what is under test: an inherited BEADS_DIR
// (a developer's shell, or one an earlier in-process command
// exported) would take precedence and fail the lookup.
t.Setenv("BEADS_DIR", "")
t.Chdir(subDir)
resetResolutionCaches(t)
@ -802,6 +806,7 @@ func TestResolvedConfigRepoRoot(t *testing.T) {
t.Fatalf("Failed to create bare metadata.json: %v", err)
}
t.Setenv("BEADS_DIR", "") // as above: discovery, not BEADS_DIR, is under test
t.Chdir(worktreeDir)
resetResolutionCaches(t)

View file

@ -5,11 +5,13 @@ package main
import (
"context"
"errors"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
@ -211,13 +213,11 @@ func TestDeleteIssueWrapper(t *testing.T) {
t.Fatalf("deleteIssue failed: %v", err)
}
// Verify issue is gone
// Verify issue is gone: GetIssue reports a missing issue as
// storage.ErrNotFound.
deleted, err := s.GetIssue(ctx, issue.ID)
if err != nil {
t.Fatalf("GetIssue failed: %v", err)
}
if deleted != nil {
t.Error("Issue should be completely deleted")
if !errors.Is(err, storage.ErrNotFound) {
t.Fatalf("GetIssue after delete: got (%v, %v), want storage.ErrNotFound", deleted, err)
}
})
@ -309,25 +309,3 @@ func TestDeleteIssueWrapper(t *testing.T) {
}
})
}
func TestDeleteIssueUnsupportedStorage(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("skipping: Dolt test container not available")
}
oldStore := store
defer func() { store = oldStore }()
// Set store to nil - the type assertion will fail
store = nil
ctx := context.Background()
err := deleteIssue(ctx, "any-id")
if err == nil {
t.Error("Expected error when storage is nil")
}
expectedMsg := "delete operation not supported by this storage backend"
if err.Error() != expectedMsg {
t.Errorf("Expected error %q, got %q", expectedMsg, err.Error())
}
}

View file

@ -22,7 +22,7 @@ func buildBDForTest(t *testing.T) string {
binDir := t.TempDir()
exe := filepath.Join(binDir, exeName)
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", exe, ".")
cmd := goBuildBDCommand(exe)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("go build failed: %v\n%s", err, string(out))

View file

@ -52,7 +52,7 @@ func buildBDUnderTest(t *testing.T) string {
binName = "bd.exe"
}
buildBDPath = filepath.Join(dir, binName)
buildCmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", buildBDPath, ".")
buildCmd := goBuildBDCommand(buildBDPath)
if out, err := buildCmd.CombinedOutput(); err != nil {
buildBDErr = &buildBDError{err: err, output: out}
return

View file

@ -95,7 +95,7 @@ func buildEmbeddedBD(t *testing.T) string {
name = "bd.exe"
}
embeddedBD = filepath.Join(tmpDir, name)
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", embeddedBD, ".")
cmd := goBuildBDCommand(embeddedBD)
if out, err := cmd.CombinedOutput(); err != nil {
embeddedBDErr = fmt.Errorf("go build failed: %v\n%s", err, out)
}

View file

@ -37,7 +37,7 @@ func buildBDForInitPermissionTests(t *testing.T) string {
return
}
initPermissionTestBD = filepath.Join(tmpDir, "bd")
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", initPermissionTestBD, ".")
cmd := goBuildBDCommand(initPermissionTestBD)
if out, err := cmd.CombinedOutput(); err != nil {
initPermissionTestBDErr = fmt.Errorf("go build failed: %v\n%s", err, out)
}

View file

@ -75,8 +75,8 @@ func migrationFrontDoorBinary(t *testing.T) string {
return p
}
out := filepath.Join(t.TempDir(), "bd")
cmd := exec.Command("go", "build", "-o", out, ".")
cmd.Dir = "."
cmd := exec.Command("go", "build", "-o", out, bdModulePackage)
cmd.Dir = bdSourceDir
if b, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("build cgo bd: %v\n%s", err, b)
}

View file

@ -6,7 +6,6 @@ package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
@ -32,7 +31,7 @@ func TestScripts(t *testing.T) {
if prebuilt, err := findPrebuiltBDBinary(); err == nil && prebuilt != "" && filepath.Base(prebuilt) == exeName {
exe = prebuilt
binDir = filepath.Dir(prebuilt)
} else if err := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", exe, ".").Run(); err != nil {
} else if err := goBuildBDCommand(exe).Run(); err != nil {
t.Fatal(err)
}

View file

@ -611,19 +611,13 @@ func buildSharedServerTestBinary(t *testing.T) string {
sharedServerBdBinary = prebuilt
return
}
pkgDir, err := os.Getwd()
if err != nil {
sharedServerBuildErr = fmt.Errorf("getwd: %w", err)
return
}
buildDir, err := testTempDir("beads-shared-server-bd-*")
if err != nil {
sharedServerBuildErr = fmt.Errorf("mkdirtemp: %w", err)
return
}
bdBin := filepath.Join(buildDir, "bd")
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", bdBin, ".")
cmd.Dir = pkgDir
cmd := goBuildBDCommand(bdBin)
cmd.Env = append(os.Environ(), "CGO_ENABLED=1")
out, err := cmd.CombinedOutput()
if err != nil {

View file

@ -324,6 +324,73 @@ func findPrebuiltBDBinary() (string, error) {
return bazeltest.PrebuiltBD()
}
// bdModulePackage is cmd/bd's import path. The in-test fallback build names
// it explicitly instead of "." so it can never build whatever package happens
// to be in the working directory.
const bdModulePackage = "github.com/steveyegge/beads/cmd/bd"
// bdSourceDir is cmd/bd's source directory, resolved during package
// initialization, before TestMain or any test can chdir: this file's
// compiled-in path when it is absolute (not -trimpath) and next to main.go,
// else the working directory go test starts the binary in (the package
// directory).
var bdSourceDir = resolveBDSourceDir()
func resolveBDSourceDir() string {
if _, file, _, ok := runtime.Caller(0); ok && filepath.IsAbs(file) {
dir := filepath.Dir(file)
if _, err := os.Stat(filepath.Join(dir, "main.go")); err == nil {
return dir
}
}
wd, _ := os.Getwd()
return wd
}
// goBuildBDCommand returns the `go build` that subprocess-test helpers fall
// back to when BEADS_TEST_BD_BINARY is unset. It is the build CI prebuilds
// that binary with (main.yml build-artifacts: go build -tags gms_pure_go
// ./cmd/bd; no -race), and it builds cmd/bd whatever the caller's working
// directory is: the package is named by import path and the command runs in
// bdSourceDir, so a helper first reached from a test that chdir'd into a
// fixture (or a precompiled test binary run from elsewhere) still builds bd.
func goBuildBDCommand(out string) *exec.Cmd {
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", out, bdModulePackage)
cmd.Dir = bdSourceDir
return cmd
}
// TestGoBuildBDCommandIsCWDIndependent pins that the fallback build resolves
// cmd/bd from any working directory. It resolves the command's package in
// the command's directory with `go list` rather than paying for a full link.
func TestGoBuildBDCommandIsCWDIndependent(t *testing.T) {
if bazeltest.IsBazel() {
t.Skip("Bazel always injects bd through BEADS_TEST_BD_BINARY; the fallback build is unused")
}
if _, err := exec.LookPath("go"); err != nil {
t.Skipf("go toolchain not on PATH: %v", err)
}
t.Chdir(t.TempDir())
cmd := goBuildBDCommand(filepath.Join(t.TempDir(), "bd"))
if got := cmd.Args[len(cmd.Args)-1]; got != bdModulePackage {
t.Fatalf("goBuildBDCommand builds %q, want %q", got, bdModulePackage)
}
if !strings.Contains(strings.Join(cmd.Args, " "), "-tags gms_pure_go") {
t.Fatalf("goBuildBDCommand args %q lack CI's -tags gms_pure_go", cmd.Args)
}
list := exec.Command("go", "list", "-tags", "gms_pure_go", "-f", "{{.Name}} {{.ImportPath}}", bdModulePackage)
list.Dir = cmd.Dir
out, err := list.CombinedOutput()
if err != nil {
t.Fatalf("go list %s in %q: %v\n%s", bdModulePackage, cmd.Dir, err, out)
}
if got, want := strings.TrimSpace(string(out)), "main "+bdModulePackage; got != want {
t.Fatalf("go list in %q = %q, want %q", cmd.Dir, got, want)
}
}
// buildBDForInitTests builds (or locates) a bd binary suitable for subprocess
// tests. Uses the gms_pure_go tag so the resulting binary works in either
// CGO mode. Lives in the pure-Go helpers file so subprocess-style tests can
@ -360,7 +427,7 @@ func buildBDForInitTests(t *testing.T) string {
return
}
initTestBD = filepath.Join(tmpDir, bdBinary)
cmd := exec.Command("go", "build", "-tags", "gms_pure_go", "-o", initTestBD, ".")
cmd := goBuildBDCommand(initTestBD)
if out, err := cmd.CombinedOutput(); err != nil {
initTestBDErr = fmt.Errorf("go build failed: %v\n%s", err, out)
}

View file

@ -15,6 +15,8 @@
# The in-test `go build` of bd that this test guards does not happen under
# Bazel (bd comes in through BEADS_TEST_BD_BINARY); go test still runs it.
cmd/bd TestGOMODCACHENotUnderTestHome skip # no in-test go build under Bazel; guarded by go test
# Same: it checks the fallback `go build` of bd, which Bazel never takes.
cmd/bd TestGoBuildBDCommandIsCWDIndependent skip # no in-test go build under Bazel; guarded by go test
# Needs TestAAAStdioBaseline in the same process; sharding splits them.
# TestMain's checkStdioAfterRun still checks every shard.
cmd/bd TestZZStdioNotLeaked skip # baseline test lands in another shard; checkStdioAfterRun covers each shard