* feat(workspacegate): wire the gate through a shared physical-root resolver, OpenGated, and the CLI (part 2) Part 2 of the workspace-gate work started in #5046, which landed the internal/workspacegate primitive and deliberately held back OpenGated because its private physical-root derivation was wrong in exactly the ways review found: it skipped the store's real mode resolution and silently skipped the physical gate on metadata-less workspaces. internal/doltserver.ResolvePhysicalRoots is now the one shared answer to 'which local directory will this workspace's store actually open': side-effect free (never triggers configfile.Load's legacy-migration write, never mkdirs the shared-server tree), central-config aware (the dolt_mode inheritance that previously existed only inside storage/dolt/open.go), correct for embedded (embeddeddolt, where ResolveDoltDir answers dolt/), proxied (env > client-info sidecar > default, hoisted out of package main so it cannot diverge), shared (no-mkdir path), remote backends (workspace gate only), and the supported no-metadata layouts (embeddeddolt-then-dolt stat probe). beads.OpenGated gives library consumers a store that holds SHARED workspace+physical gates for its lifetime. The CLI acquires at one chokepoint after workspace resolution - SHARED for store-opening commands, EXCLUSIVE for backup restore - and in-command for the noDbCommands that replace state: init, migrate from-*-to-* (both source and destination roots, ahead of migrate.lock per the normative lock order), and bootstrap. Posture is deliberate and asymmetric: SHARED acquisition failures that are not contention warn once and continue ungated (the gate is cooperative; normal commands must not brick existing deployments), while contention aborts with the holder's identity, and EXCLUSIVE failures of any kind refuse - maintenance must not pretend to a fence it does not hold. Known residual: discovery-path config loads before the chokepoint can still fire the legacy-migration write; deferring that is follow-up scope alongside doctor, secondary-target opens, and bd dolt set. Agent-Signature: claude-fable-5-medium on behalf of matt wilkie Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AQHiBWVPSXDCcUSG9EGw9d * fix(workspacegate): nil store on failed factory open before gate-release cleanup newDoltStore's concrete factory branches (e.g. server-mode dolt.New) return a typed-nil pointer on error; assigning it to the storage.DoltStorage interface makes 'store != nil' true in closeStoreBeforeGateRelease, which then calls Close on a nil receiver and panics (SIGSEGV observed in TestPersistentPreRunHonorsSkipStoreAnnotation, verify run 20260727T000727Z). No store was opened on that path, so drop the value before the error return. Agent-Signature: claude-fable-5-high on behalf of maphew Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01P3JtQ3ukoVmfg6LCKcKBBh * fix(workspacegate): address review — unparam, gate-busy lock classification, bootstrap dolt-dir gating Three fixes from the adversarial review of gastownhall/beads#5093 (see reports/2026-07-26-reviewer-dispatch-sweep.md, "#5093" section): - unparam (CI lint fail): drop the dead PhysicalRoots return value from buildWorkspaceGateSet; both call sites already discarded it, and the code comments already document that provenance is deliberately not surfaced in user-facing errors. Updated both callers. - TestEmbeddedInitConcurrent regression (CI test fail): the new EXCLUSIVE workspace gate in cmd/bd/init.go short-circuits before the embedded Dolt flock is ever attempted, so a losing concurrent `bd init` now reports gate-busy output that isEmbeddedLockOutput did not recognize. Taught isEmbeddedLockOutput to also match workspacegate.ErrBusy's "workspace gate busy" text, and added a deterministic TestInitGateBusyClassifiedAsLockContention that holds the gate in-process and exercises the exact classification path, independent of subprocess race timing. - Bootstrap dolt-dir gating gap: executeBootstrapPlan gated plan.BeadsDir's resolved physical roots but not doltserver.ResolveDoltDir(plan.BeadsDir), the directory executeInitAction/executeRestoreAction/executeJSONLImportAction actually open. Pass it as an extraRoot, mirroring how bd init passes its own resolved db path. Also fixes a locally-discovered flake in TestChokepointSharedExcludesMigrateExclusive: acquireMigrateGates now threads the package-global rootCtx into acquireExclusiveWorkspaceGates, so a prior in-process test that ran the full command path (which sets rootCtx via setupGracefulShutdown and cancels it via rootCancel() without resetting the var) can leak an already-canceled context into this test. Pin rootCtx to nil for the test's duration, matching the isolation pattern already used elsewhere in this file. Reproduced deterministically by injecting a canceled context before the fix, confirmed neutralized after. TestEmbeddedInitConcurrent itself still does not reproduce the CI gate-busy symptom on this dev machine (10/10 processes succeed within the 5s exclusive-gate wait, so the test's own "at least 1 lock error" assertion still fails locally) — that is a machine-speed-dependent property of the test's contention window, not the classification bug; the classification fix is independently verified by the new deterministic test and by code inspection of workspacegate.ErrBusy's text. Agent-Signature: claude-fable-5-high on behalf of matt wilkie --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
197 lines
6.3 KiB
Go
197 lines
6.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/workspacegate"
|
|
)
|
|
|
|
// resetGateTestEnv pins every env var the physical-root resolver consults so
|
|
// a developer machine's beads setup (shared-server mode, custom data dirs,
|
|
// central config) cannot change which gates these tests acquire.
|
|
func resetGateTestEnv(t *testing.T) {
|
|
t.Helper()
|
|
for _, k := range []string{
|
|
"BEADS_DOLT_SERVER_MODE",
|
|
"BEADS_DOLT_SHARED_SERVER",
|
|
"BEADS_DOLT_DATA_DIR",
|
|
"BEADS_DOLT_SERVER_HOST",
|
|
"BEADS_PROXIED_SERVER_ROOT_PATH",
|
|
"BEADS_SHARED_SERVER_DIR",
|
|
} {
|
|
t.Setenv(k, "")
|
|
}
|
|
t.Setenv("BEADS_CENTRAL_CONFIG", filepath.Join(t.TempDir(), "no-central.json"))
|
|
}
|
|
|
|
func newGateTestWorkspace(t *testing.T) string {
|
|
t.Helper()
|
|
beadsDir := filepath.Join(t.TempDir(), ".beads")
|
|
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
meta := `{"backend":"dolt","database":"beads.db","dolt_mode":"embedded"}`
|
|
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(meta), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return beadsDir
|
|
}
|
|
|
|
func TestCommandNeedsExclusiveGate(t *testing.T) {
|
|
root := &cobra.Command{Use: "bd"}
|
|
backup := &cobra.Command{Use: "backup"}
|
|
backupRestore := &cobra.Command{Use: "restore [path]"}
|
|
backup.AddCommand(backupRestore)
|
|
root.AddCommand(backup)
|
|
// Top-level `bd restore <issue-id>` is an ISSUE restore
|
|
// (cmd/bd/restore.go), not a database restore: it must stay SHARED.
|
|
issueRestore := &cobra.Command{Use: "restore [issue-id]"}
|
|
root.AddCommand(issueRestore)
|
|
list := &cobra.Command{Use: "list"}
|
|
root.AddCommand(list)
|
|
|
|
cases := []struct {
|
|
name string
|
|
cmd *cobra.Command
|
|
want bool
|
|
}{
|
|
{"backup restore is exclusive", backupRestore, true},
|
|
{"top-level issue restore is not", issueRestore, false},
|
|
{"list is not", list, false},
|
|
{"backup parent is not", backup, false},
|
|
{"root is not", root, false},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
if got := commandNeedsExclusiveGate(tc.cmd); got != tc.want {
|
|
t.Errorf("commandNeedsExclusiveGate(%s) = %v, want %v", tc.cmd.Name(), got, tc.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestAcquireCommandWorkspaceGatesAbsentWorkspace(t *testing.T) {
|
|
resetGateTestEnv(t)
|
|
t.Cleanup(releaseWorkspaceGates)
|
|
|
|
list := &cobra.Command{Use: "list"}
|
|
missing := filepath.Join(t.TempDir(), "nope", ".beads")
|
|
if err := acquireCommandWorkspaceGates(context.Background(), list, missing); err != nil {
|
|
t.Fatalf("absent beadsDir must be silently ungated, got %v", err)
|
|
}
|
|
if workspaceGateHandle != nil {
|
|
t.Error("absent beadsDir must leave no gate handle")
|
|
}
|
|
}
|
|
|
|
func TestAcquireCommandWorkspaceGatesBlockedByExclusiveHolder(t *testing.T) {
|
|
resetGateTestEnv(t)
|
|
t.Cleanup(releaseWorkspaceGates)
|
|
beadsDir := newGateTestWorkspace(t)
|
|
|
|
gate, err := workspacegate.ForWorkspace(beadsDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
holder, err := gate.Acquire(context.Background(), workspacegate.Exclusive,
|
|
workspacegate.Options{Reason: "test maintenance"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = holder.Release() }()
|
|
|
|
list := &cobra.Command{Use: "list"}
|
|
if err := acquireCommandWorkspaceGates(context.Background(), list, beadsDir); err == nil {
|
|
t.Fatal("SHARED acquisition under a foreign exclusive holder must abort, got nil error")
|
|
}
|
|
if workspaceGateHandle != nil {
|
|
t.Error("failed acquisition must leave no gate handle")
|
|
}
|
|
}
|
|
|
|
func TestReleaseWorkspaceGatesIdempotent(t *testing.T) {
|
|
resetGateTestEnv(t)
|
|
beadsDir := newGateTestWorkspace(t)
|
|
|
|
list := &cobra.Command{Use: "list"}
|
|
if err := acquireCommandWorkspaceGates(context.Background(), list, beadsDir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if workspaceGateHandle == nil {
|
|
t.Fatal("expected a held gate handle")
|
|
}
|
|
releaseWorkspaceGates()
|
|
if workspaceGateHandle != nil {
|
|
t.Error("handle must be cleared on release")
|
|
}
|
|
// Second release must be a no-op, not a panic or double-unlock.
|
|
releaseWorkspaceGates()
|
|
|
|
// And the gate must actually be free again: an exclusive acquisition
|
|
// succeeds after release.
|
|
gate, err := workspacegate.ForWorkspace(beadsDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
h, err := gate.Acquire(context.Background(), workspacegate.Exclusive, workspacegate.Options{})
|
|
if err != nil {
|
|
t.Fatalf("gate still held after releaseWorkspaceGates: %v", err)
|
|
}
|
|
_ = h.Release()
|
|
}
|
|
|
|
// The cross-wiring guarantee: a chokepoint SHARED hold (a normal command
|
|
// mid-flight) excludes acquireMigrateGates' EXCLUSIVE acquisition on the
|
|
// same workspace. Also exercises the nil-rootCtx path inside
|
|
// acquireMigrateGates (tests have no process signal context), which used to
|
|
// panic before the nil-context normalization.
|
|
func TestChokepointSharedExcludesMigrateExclusive(t *testing.T) {
|
|
resetGateTestEnv(t)
|
|
t.Cleanup(releaseWorkspaceGates)
|
|
beadsDir := newGateTestWorkspace(t)
|
|
|
|
// rootCtx is a package global that production sets via
|
|
// setupGracefulShutdown() in PersistentPreRunE and cancels via
|
|
// rootCancel() in PersistentPostRunE WITHOUT resetting the var to nil —
|
|
// harmless in production (the process exits), but any earlier in-process
|
|
// test that exercises the full command path (Execute()) leaves rootCtx
|
|
// pointing at an already-canceled context for whatever test runs next in
|
|
// the same binary. acquireMigrateGates now threads rootCtx through to
|
|
// acquireExclusiveWorkspaceGates, so this test is sensitive to that
|
|
// leak: pin it to nil (the documented "no process signal context yet"
|
|
// case this test exercises) regardless of what ran before it.
|
|
oldRootCtx := rootCtx
|
|
rootCtx = nil
|
|
t.Cleanup(func() { rootCtx = oldRootCtx })
|
|
|
|
oldWait := exclusiveGateWait
|
|
exclusiveGateWait = 10 * time.Millisecond
|
|
t.Cleanup(func() { exclusiveGateWait = oldWait })
|
|
|
|
list := &cobra.Command{Use: "list"}
|
|
if err := acquireCommandWorkspaceGates(context.Background(), list, beadsDir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if workspaceGateHandle == nil {
|
|
t.Fatal("expected a held shared gate handle")
|
|
}
|
|
|
|
release, err := acquireMigrateGates(beadsDir, false, "test migrate")
|
|
if err == nil {
|
|
release()
|
|
t.Fatal("migrate EXCLUSIVE acquisition must fail while the chokepoint holds SHARED")
|
|
}
|
|
|
|
// After the shared holder releases, the migration proceeds.
|
|
releaseWorkspaceGates()
|
|
release, err = acquireMigrateGates(beadsDir, false, "test migrate")
|
|
if err != nil {
|
|
t.Fatalf("migrate acquisition after shared release: %v", err)
|
|
}
|
|
release()
|
|
}
|