fix(cmd): stop a canceled rootCtx leaking into the next in-process command (#5204)

PersistentPostRunE cancels the signal context and leaves the rootCtx
global pointing at it. A real bd process exits right after, so nothing
notices. The cmd/bd test binary runs Execute() many times in one
process, so every test following the first full command path inherits a
dead root context.

That was latent until #5093 threaded rootCtx into acquireMigrateGates.
Since then main has been red on both ubuntu-latest and macos-latest:
eleven TestMigrate* cases fail at 0.00s with

  cannot migrate while other bd activity holds this workspace:
  workspacegate: acquiring <dir>/.beads.gate.lock: context canceled

which is workspacegate.Acquire's ctx.Err() pre-check firing on a
cancellation nobody requested. The tests pass in isolation, which is why
the failure reads as noise until you order the package.

#5093 already knew about the leak - workspace_gate_test.go pins rootCtx
to nil so TestChokepointSharedExcludesMigrateExclusive survives it - but
migrate_dolt_mode_test.go was left undefended. Pinning each affected
test is the wrong shape; the leak belongs to the lifecycle.

- PersistentPostRunE cancels and clears the context globals from a
  deferred hook registered before the cleanup defers. Deferred so the
  maintenance block's error returns clear them too; registered first so
  it runs last, because closeStoreBeforeGateRelease passes rootCtx to
  uowProvider.Close and used to receive an already-canceled context.
  nil is the documented "no process signal context yet" state and
  normalizes back to Background() through getRootContext().

- PersistentPreRunE publishes the signal context through setRootContext
  rather than assigning the globals directly. cmdCtx exists by then, so
  getRootContext() reads cmdCtx.RootCtx, and every skipsStoreInit
  command - migrate among them - returns before syncCommandContext can
  backfill it. Without this, those commands see a nil per-command
  context and lose Ctrl-C.

- acquireMigrateGates reads getRootContext() rather than the raw global,
  so it honors the per-command context when globals are disabled.

- Add root_context_lifecycle_test.go covering both context
  representations, the error path, and the nil case, so the next
  consumer to thread rootCtx somewhere new does not rediscover this the
  way migrate did.

Agent-Signature: claude-opus-5-high on behalf of maphew
This commit is contained in:
matt wilkie 2026-07-31 15:45:55 -07:00 • committed by GitHub
commit 35ccd0df73
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 164 additions and 6 deletions

View file

@ -793,7 +793,15 @@ var rootCmd = &cobra.Command{
// Set up signal-aware context with batch commit flush on shutdown.
// Unlike signal.NotifyContext, this also handles SIGHUP and flushes
// pending batch commits before canceling the context.
rootCtx, rootCancel = setupGracefulShutdown()
//
// Publish through setRootContext, not a bare assignment to the
// globals: cmdCtx exists by now (initCommandContext above), so
// getRootContext() reads cmdCtx.RootCtx, and the commands that
// return early from this hook -- every skipsStoreInit command,
// migrate among them -- never reach syncCommandContext to have it
// backfilled. A bare assignment leaves those commands reading a nil
// per-command context and losing Ctrl-C entirely.
setRootContext(setupGracefulShutdown())
// Initialize OTel (no-op unless BD_OTEL_METRICS_URL or BD_OTEL_STDOUT=true).
// Must run before any DB access so SQL spans nest under command spans.
@ -1552,6 +1560,27 @@ var rootCmd = &cobra.Command{
return nil
},
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
// Registered FIRST so it runs LAST: the signal context must outlive
// the store/gate cleanup below, which passes rootCtx to
// uowProvider.Close. Canceling in the function body (as this used
// to) handed those closers a dead context on the way out.
//
// Clearing matters as much as canceling. Leaving rootCtx pointing at
// the context we just canceled is harmless when a real bd process
// exits here, but every in-process caller that runs Execute() more
// than once -- the cmd/bd test binary, library embedders -- would
// hand that dead context to the next command, and anything reading
// it refuses work nobody canceled. nil is the documented "no process
// signal context yet" state and normalizes back to Background().
//
// Deferred rather than inline so the early error returns below clear
// the globals too.
defer func() {
if rootCancel != nil {
rootCancel()
}
setRootContext(nil, nil)
}()
defer restoreChangeDirSelection()
// Release the workspace/physical-root gates on EVERY exit from
// PostRunE — deferred so the early error returns below cannot leak
@ -1684,10 +1713,9 @@ var rootCmd = &cobra.Command{
}
}
// Cancel the signal context to clean up resources
if rootCancel != nil {
rootCancel()
}
// The signal context is canceled and cleared by the deferred hook
// registered at the top of this function, so that it also covers the
// early error returns above.
return nil
},
}

View file

@ -186,7 +186,10 @@ func acquireMigrateGates(beadsDir string, shared bool, reason string) (func(), e
if err != nil {
return nil, HandleError("failed to resolve migration destination root: %v", err)
}
h, err := acquireExclusiveWorkspaceGates(rootCtx, beadsDir, reason, destRoot)
// getRootContext(), not the rootCtx global: it honors the per-command
// context when globals are disabled, and normalizes the not-yet-set case
// to context.Background().
h, err := acquireExclusiveWorkspaceGates(getRootContext(), beadsDir, reason, destRoot)
if err != nil {
return nil, HandleErrorWithHint(
fmt.Sprintf("cannot migrate while other bd activity holds this workspace: %v", err),

View file

@ -0,0 +1,127 @@
package main
import (
"context"
"errors"
"testing"
"github.com/spf13/cobra"
)
// snapshotRootContext saves and restores BOTH representations of the root
// context. setRootContext writes the raw globals and cmdCtx, so restoring
// only the globals would leak half the state into the next test — the exact
// failure mode these tests exist to prevent.
func snapshotRootContext(t *testing.T) {
t.Helper()
oldCtx, oldCancel := rootCtx, rootCancel
oldReadonly := readonlyMode
oldUseGlobals := testModeUseGlobals
var oldCmdCtx context.Context
var oldCmdCancel context.CancelFunc
if cmdCtx != nil {
oldCmdCtx, oldCmdCancel = cmdCtx.RootCtx, cmdCtx.RootCancel
}
t.Cleanup(func() {
rootCtx, rootCancel = oldCtx, oldCancel
readonlyMode = oldReadonly
testModeUseGlobals = oldUseGlobals
if cmdCtx != nil {
cmdCtx.RootCtx, cmdCtx.RootCancel = oldCmdCtx, oldCmdCancel
}
})
}
// PersistentPostRunE cancels the signal context on the way out. It must also
// drop the globals: a cancelled context left in rootCtx is invisible to the
// next Execute() in the same process and makes every context-aware command
// refuse work that nobody cancelled.
//
// Regression: #5093 threaded rootCtx into acquireMigrateGates, which turned
// this latent leak into eleven hard failures in cmd/bd — every earlier test
// that ran a full command path left migrate's workspace-gate acquisition
// failing with "context canceled" at 0.00s.
func TestPersistentPostRunE_ClearsCancelledRootContext(t *testing.T) {
// strictReadonly short-circuits the post-run maintenance block, so these
// exercise the context lifecycle without needing a live store.
run := func(t *testing.T, useGlobals bool) {
t.Helper()
snapshotRootContext(t)
testModeUseGlobals = useGlobals
readonlyMode = true
ctx, cancel := context.WithCancel(context.Background())
setRootContext(ctx, cancel)
if err := rootCmd.PersistentPostRunE(&cobra.Command{Use: "list"}, nil); err != nil {
t.Fatalf("PersistentPostRunE: %v", err)
}
if err := ctx.Err(); !errors.Is(err, context.Canceled) {
t.Errorf("post-run must cancel the context it was handed, got %v", err)
}
if rootCtx != nil {
t.Errorf("rootCtx must be cleared after post-run, got %v (err=%v)", rootCtx, rootCtx.Err())
}
if rootCancel != nil {
t.Error("rootCancel must be cleared after post-run")
}
if cmdCtx != nil && cmdCtx.RootCtx != nil {
t.Errorf("cmdCtx.RootCtx must be cleared after post-run, got %v", cmdCtx.RootCtx)
}
if err := getRootContext().Err(); err != nil {
t.Errorf("getRootContext() must hand back a live context after post-run, got %v", err)
}
}
// The package TestMain pins testModeUseGlobals, so the cmdCtx branch of
// getRootContext() is only reached if this test unpins it. Production
// runs that branch, so it is the one that must not regress.
t.Run("legacy globals", func(t *testing.T) { run(t, true) })
t.Run("command context", func(t *testing.T) {
if cmdCtx == nil {
t.Skip("no command context initialized in this binary")
}
run(t, false)
})
}
// The clear is deferred, not inline, so the maintenance block's error
// returns cannot strand a cancelled context in the globals either.
func TestPersistentPostRunE_ClearsOnErrorPath(t *testing.T) {
snapshotRootContext(t)
testModeUseGlobals = true
readonlyMode = false // let the maintenance block run
oldBackup, oldExport := runPostRunAutoBackup, runPostRunAutoExport
t.Cleanup(func() { runPostRunAutoBackup, runPostRunAutoExport = oldBackup, oldExport })
runPostRunAutoBackup = func(context.Context) {}
runPostRunAutoExport = func(context.Context, bool) error { return errors.New("boom") }
ctx, cancel := context.WithCancel(context.Background())
setRootContext(ctx, cancel)
// "create" is not read-only, so post-run reaches the auto-export hook.
if err := rootCmd.PersistentPostRunE(&cobra.Command{Use: "create"}, nil); err == nil {
t.Fatal("expected the stubbed auto-export failure to surface")
}
if err := ctx.Err(); !errors.Is(err, context.Canceled) {
t.Errorf("post-run must cancel the context even on the error path, got %v", err)
}
if rootCtx != nil || rootCancel != nil {
t.Errorf("post-run must clear the globals on the error path, got ctx=%v cancel!=nil=%v", rootCtx, rootCancel != nil)
}
}
// getRootContext must survive a command that never installed a context at
// all — the state every test in this binary starts from.
func TestGetRootContext_NilIsLive(t *testing.T) {
snapshotRootContext(t)
testModeUseGlobals = true
setRootContext(nil, nil)
if err := getRootContext().Err(); err != nil {
t.Errorf("a nil root context must normalize to a live one, got %v", err)
}
}