fix(storage): shared stores refuse version-bump migration without explicit consent (#5920, #5043) (#6048)

* feat(schema): add the shared-store migration gate and a locked migration gate hook

Grows checkRemoteMigrateGate with a `shared` flag, exposed as
CheckSharedStoreMigrateGate. On a shared store (a database served to
co-resident bd clients) the gate:

  - refuses a version-bump migration when there is NO remote and the
    operator has not consented, with the new "shared-no-remote" decision
    on the existing RemoteMigrateGateError. Promoting the schema cursor
    on a shared server locks out every client still on an older bd —
    gastownhall/beads#5920;
  - suppresses the smart gate's two auto-EXECUTE arms with a remote
    configured. The safe-first-mover argument is about clones, not
    clients; it firing on a shared server IS the #5920 mechanism.

A fresh database (current == 0) still migrates: creating a database is
consent for its schema. Consent surfaces are the migrate verb (new
process-local SetSharedMigrateConsent, unlocking only the no-remote arm),
--force, and the reused BD_ALLOW_REMOTE_MIGRATE.

schema.WithMigrationGate gives MigrateUpWithLock a pre-migration hook for
callers whose migration runs entirely inside it. It sits after locked
preparation and before MigrateUp, so the 4a3c02abc converged fast path
still costs it zero statements.

No call site changes behavior yet: every existing exported variant passes
shared=false, so embedded recompiles untouched.

* fix(storage): refuse version-bump migration on shared dolt sql-server stores

Switches internal/storage/dolt's writable-open gate to the shared variant.
A DoltStore is always a sql-server client, and a sql-server accepts
co-resident clients by construction — the property that distinguishes it
from the flock-guarded single-writer embedded store — so this open must
never promote the schema cursor on its own.

This closes gastownhall/beads#5920 at its mechanism: the version-bump
reconciliation (autoMigrateOnVersionBump) opens its OWN writable store for
every non-preview command, including read-only ones, and that open is what
migrated a shared database out from under a team of co-resident v1.2.2
clients. It now refuses, and the refusal — previously swallowed to
debug.Logf with everything else — prints a one-shot stderr notice saying
nothing was applied and what to run instead.

`bd migrate` / `bd migrate schema` set the new verb consent in the root
pre-run (withheld under a preview flag), so the typed verb still migrates.

Tests: a full-CLI #5920 regression (server mode, no remote, stale
.local_version, `bd list` must not promote MAX(version) — it does promote
it, 65 -> 66, with this commit's one-line gate swap reverted), the
server-mode open matrix on a real sql-server (writable refuses, read-only
succeeds, verb consent migrates), refusal permanence in the retry loop,
and the agent-facing JSON block.

* docs(upgrading): document the shared-server upgrade path

Adds a "Shared servers" section: a version bump never auto-migrates a
database served to co-resident clients, upgrade every client first, then
consent once with `bd migrate schema`, and `bd serve` refuses to start
until the schema is reconciled.

Two corrections to what was already there:

  - the smart gate's "auto-migrates as a safe first-mover" arm is now
    embedded-only, so the bullet says so and links to the new section;
  - the literal `BD_ALLOW_REMOTE_MIGRATE=1 bd migrate` recipe is removed
    in favor of "run bd migrate as an explicit step in exactly one job; if
    the gate blocks a run it prints the options and the scripted
    override". Per settled decision 4
    (engdocs/decisions/2026-07-17-docs-release-pin.md), the escape hatch
    is not documented as a recipe — the gate prints its own guidance and
    the docs defer to it. This brings the page back into compliance
    rather than amending the decision.

* fix(storage): address review of the shared-store migration gate

CI blocker: cmd/bd/shared_store_migrate_gate_test.go uses cgo-tagged
helpers but carried no build tag, so the required pure-Go compile lane
(CGO_ENABLED=0 go test -tags gms_pure_go -c ./cmd/bd) failed on undefined
symbols. Tagged //go:build cgo, like every sibling Dolt-server test.

Truth at the merge point. This PR gates the sql-server store; the proxied /
`bd serve` plane is #6055. So its text no longer claims that plane: the
shared-no-remote body, the gate's doc comment, the decision constant, and
WithMigrationGate's doc all describe a dolt sql-server, and upgrading.md
drops the `bd serve` paragraph. #6055 adds them back with the code.

Remedies now match the refusal they are attached to:

  - the one-shot version-bump notice keyed only on the error TYPE, so an
    "adopt" refusal (another clone already migrated) told the operator to
    run `bd migrate schema` — a command the verb consent deliberately does
    not unlock for that arm. It now picks the line per Decision, and stays
    silent under --json, where it was corrupting the gate's own JSON block
    on the same stream;
  - a new Shared flag marks refusals that came from a shared store, so the
    adopt and adopt-ff options can say that adopting promotes the schema
    for every co-resident client. adopt-ff previously advertised
    "Risk: none", which is true only of local data;
  - handleRemoteMigrateGateJSON gains the missing adopt-ff case (now a
    routine outcome, since the auto-execute arm is suppressed), and
    shared-no-remote points at the #shared-servers docs anchor instead of
    inheriting the migrate-or-adopt one;
  - `bd init` joining a behind shared server exits before writing
    metadata.json, so its refusal now says where the prescribed command
    can actually be run;
  - the beads_global refusal names `bd migrate schema --global`, in the
    init warning and under --global at the store open — the unflagged
    command migrates the project database and leaves the refusal in place;
  - a consented `bd migrate schema` that hits the dirty-table guard names
    the recovery that terminates, instead of pointing at `bd dolt commit`,
    which is itself gated in server mode and points back.

Behavior: consent is now scoped to `bd migrate schema` alone. Bare
`bd migrate` never applies a schema migration itself, and
`bd migrate --update-repo-id` is repo-fingerprint surgery — neither should
promote the schema for a whole server as a side effect. A consented
`bd migrate schema` now also stamps the version marker the refused
reconciliation could not, so `bd doctor` stops reporting a permanent
mismatch after the operator has done exactly what the refusal asked.

Library API: beads.AllowSharedSchemaMigration is the programmatic consent
embedders had no way to give except os.Setenv, which is process-global and
inherited by every child.

Cleanup: the force/env consent ladder was hand-copied into both arms; it is
now one helper that also names the surface that granted consent, so the
warning can stop hardcoding a command the operator may not have typed. Two
gate wrappers left with no callers at all are deleted.

* fix(cli): make --json shared-store migrate gate --global-aware

The shared-no-remote refusal's JSON gate block hardcoded the project-scoped
`bd migrate schema` consent command, so a --json/agent consumer operating on
the global database (--global) was handed a command that consents the wrong
database and leaves the refusal in place. The human/text path was already
--global-aware (printGlobalDatabaseConsentHint, noticeSharedMigrateRefusal),
but the notice self-suppresses under --json, making the gate block the sole
channel for that consumer.

Mirror the human-path consent idiom in handleRemoteMigrateGateJSON: retarget
both the top-level `expected` directive and the runnable migrate-shared option
command to `bd migrate schema --global` when the refused open targeted the
global database, scoped strictly to the shared-no-remote decision. Add a JSON
--global regression test at parity with TestPrintGlobalDatabaseConsentHint.

Also tighten the AllowSharedSchemaMigration doc to state it authorizes only the
no-remote shared arm (a remote-backed shared store still needs --force /
AllowRemoteMigrateEnv), matching the exported API's actual reach.

Maintainer review fixup for PR #6048.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-08-29 21:47:24 -07:00 • committed by GitHub
commit 8bb2781a8b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 1810 additions and 83 deletions

View file

@ -26,6 +26,7 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/schema"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workspacegate"
)
@ -275,6 +276,39 @@ type (
StatusEntry = storage.StatusEntry
)
// AllowSharedSchemaMigration authorizes this process to apply pending schema
// migrations to a database that is SHARED with other bd clients — a Dolt
// sql-server, where migrating promotes the schema version for every connected
// client at once and clients still running an older bd will refuse the
// database until they are upgraded (gastownhall/beads#5920).
//
// Without it, an embedder that upgrades its beads dependency across a schema
// bump gets a migration-gate error from every writable Open* call, whose
// guidance names CLI commands (`bd migrate schema`) that mean nothing inside a
// library process. This is the programmatic equivalent of that command.
//
// It is process-local and set-or-clear, which is the point: the alternative —
// os.Setenv("BD_ALLOW_REMOTE_MIGRATE", "1") — is process-GLOBAL and inherited
// by every child process the embedder spawns, including git hooks and dolt
// subprocesses.
//
// The parity with that env var is only in the process-local mechanism, not the
// reach: BD_ALLOW_REMOTE_MIGRATE=1 unlocks BOTH the no-remote and the
// remote-backed shared arms, while this authorizes ONLY the no-remote arm. A
// remote-backed shared store still needs --force / AllowRemoteMigrateEnv,
// because #4259 cross-clone coordination is a stronger, different contract.
//
// Call it before the Open* call that should perform the migration, and clear
// it afterwards. Only grant it once the operator has confirmed that every
// other client of the server is upgraded; it is a coordination decision the
// library cannot make, because other clients' versions are not observable from
// this process.
//
// Embedded (single-writer) databases never need it: they still auto-migrate.
func AllowSharedSchemaMigration(allow bool) {
schema.SetSharedMigrateConsent(allow)
}
// Open opens a Dolt-backed beads database at the given path.
// This always opens in embedded mode. Use OpenFromConfig to respect
// server mode settings from metadata.json.

View file

@ -1002,6 +1002,28 @@ func executeSyncAction(ctx context.Context, plan BootstrapPlan, cfg *configfile.
return nil
}
// printInitJoinGuidance corrects the one thing the gate's shared-store block
// gets wrong when `bd init` is the caller: it says to run `bd migrate schema`,
// but this init failed before writing metadata.json, so there is no workspace
// here to run it from (gastownhall/beads#5920). A client JOINING an existing,
// behind shared server has to be told where the command actually works.
//
// Only the shared-store arm needs this. The remote-backed refusals from init
// are already handled by printBootstrapRemoteBehindGuidance above, and their
// remedies are not workspace-local in the same way.
func printInitJoinGuidance(w io.Writer, e *schema.RemoteMigrateGateError) {
if e.Decision != "shared-no-remote" {
return
}
fmt.Fprintf(w,
"\n This workspace was NOT created — bd init stopped before writing\n"+
" .beads/metadata.json, so `%s` cannot be run from here yet.\n"+
" Either run it from a workspace already set up against this server, or\n"+
" join and migrate in one step once every client is upgraded:\n"+
" %s=1 bd init …\n",
schema.SharedConsentCommand, schema.AllowRemoteMigrateEnv)
}
// printBootstrapRemoteBehindGuidance explains a remote-migrate gate refusal in
// bootstrap terms. The gate's generic remedy ("adopt the migrated database:
// bd bootstrap") is wrong from inside a bootstrap-style clone — the database

View file

@ -1474,6 +1474,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
printBootstrapRemoteBehindGuidance(os.Stderr, gateErr, syncURL, "bd init")
} else {
fmt.Fprint(os.Stderr, gateErr.UserMessage())
printInitJoinGuidance(os.Stderr, gateErr)
}
return &exitError{Code: 1}
}
@ -3436,6 +3437,15 @@ func initGlobalDatabaseConfig(ctx context.Context, projectCfg *dolt.Config, quie
globalStore, err := newDoltStore(ctx, globalCfg)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to open global database: %v\n", err)
// The gate's own block prescribes `bd migrate schema`, which migrates
// the PROJECT database — on this path that leaves the global database
// exactly as refused. Name the command that actually reaches it
// (#5920); this warning is the only place the global refusal surfaces.
if schema.IsRemoteMigrateGateError(err) {
fmt.Fprintf(os.Stderr,
" The global database is shared by every workspace on this server. To migrate it, run:\n %s\n",
schema.SharedConsentCommandGlobal)
}
return
}
defer func() { _ = globalStore.Close() }()

View file

@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
@ -328,6 +329,40 @@ func isForcedMigrate(cmd *cobra.Command) bool {
return force
}
// printGlobalDatabaseConsentHint adds the one thing the gate's own block
// cannot know: which database this invocation was aimed at. Under --global the
// open targets `beads_global`, so the block's `bd migrate schema` would
// migrate the PROJECT database and leave the refusal in place — the working
// remedy is the same verb with the same flag.
func printGlobalDatabaseConsentHint(w io.Writer) {
if !globalFlag {
return
}
fmt.Fprintf(w,
"\n This command targeted the global database (--global), so run the\n"+
" migrate step with the same flag:\n"+
" %s\n",
schema.SharedConsentCommandGlobal)
}
// isSchemaMigrateVerb reports whether cmd is `bd migrate schema` — the one
// invocation in which the operator asked for a schema migration by name. That
// request is the consent the shared-store gate wants for a database with no
// remote (#5920); see schema.SetSharedMigrateConsent.
//
// Deliberately just this one command, not the `bd migrate` tree. Bare
// `bd migrate` reconciles version/repo-id/clone-id metadata and never applies
// a migration itself, and its flag modes are further from schema work still:
// `bd migrate --update-repo-id` is repo-fingerprint surgery after a git remote
// change, and treating it as consent would let a repo-ID update promote the
// schema for every co-resident client as a side effect. `bd migrate sync`,
// `bd migrate hooks`, and the mode-switch verbs consent to nothing either.
// The operator who does want to migrate has the verb this names, and
// `--force` still unlocks from either migrate command.
func isSchemaMigrateVerb(cmd *cobra.Command) bool {
return cmd == migrateSchemaCmd
}
// forcedMigratePreviewFlag returns the name of a preview flag (--dry-run,
// --inspect) that conflicts with --force on a forced migrate invocation, or ""
// when there is no conflict. The combination must be rejected BEFORE the store
@ -1456,6 +1491,14 @@ var rootCmd = &cobra.Command{
// root command ever be re-run in-process (tests, a future server mode).
schema.SetForceAllowRemoteMigrate(forcedMigrate)
// Typing `bd migrate schema` is consent to migrate a shared database
// that has no remote (#5920): there is no cross-clone fork to risk,
// only the co-resident lockout the operator is asking to accept. A
// preview withholds it — `bd migrate schema --dry-run` must not
// migrate on the way to printing what it would do. Same set-or-clear
// discipline as the --force override above.
schema.SetSharedMigrateConsent(isSchemaMigrateVerb(cmd) && !previewMode)
// Auto-migrate database on version bump (bd-jgxi).
// Runs for ALL non-preview commands (including read-only ones) because
// the migration opens its own store connection, writes the version
@ -1685,6 +1728,7 @@ var rootCmd = &cobra.Command{
handleRemoteMigrateGateJSON(gateErr)
} else {
fmt.Fprint(os.Stderr, gateErr.UserMessage())
printGlobalDatabaseConsentHint(os.Stderr)
}
return SilentExit()
}

View file

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"os"
"strings"
@ -8,12 +9,14 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/schema"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/issueops"
)
var migrateCmd = &cobra.Command{
@ -633,6 +636,19 @@ func handleSchemaMigrate() error {
}
return SilentExit()
}
var dirtyErr *schema.DirtyTablesError
if errors.As(err, &dirtyErr) {
// The dirty guard's own remedy is `bd dolt commit`, which on a
// shared server opens writably, hits the migrate gate, and is told
// to run this command — the two messages point at each other and
// the operator loops (gastownhall/beads#5920 review). Name the
// sequence that actually terminates.
return HandleErrorWithHint(
fmt.Sprintf("schema migration failed: %v", err),
"in server mode `bd dolt commit` is itself gated, so commit the working set on the server first "+
"(`CALL DOLT_COMMIT('-Am', 'pre-migration working set')` over the sql-server, or "+
schema.AllowRemoteMigrateEnv+"=1 bd dolt commit), then re-run this command")
}
return HandleError("schema migration failed: %v", err)
}
@ -641,6 +657,14 @@ func handleSchemaMigrate() error {
if applied > 0 {
status = "applied"
commandDidWrite.Store(true)
// Stamp the version markers the refused version-bump reconciliation
// could not (gastownhall/beads#5920 review). autoMigrateOnVersionBump
// is the only automatic writer of bd_version, it was refused by the
// gate this command just satisfied, and its one-shot .local_version
// signal is already consumed — so without this, `bd doctor` and the
// git-hook health check keep reporting a version mismatch after the
// operator has done everything the refusal told them to.
stampWorkspaceVersionAfterMigrate(store)
}
if jsonOutput {
@ -659,6 +683,24 @@ func handleSchemaMigrate() error {
return nil
}
// stampWorkspaceVersionAfterMigrate records this binary's version through the
// store's own reconciler, exactly as autoMigrateOnVersionBump would have.
//
// Best-effort by design, and deliberately not fatal: the migration itself has
// already succeeded and been reported, so a marker write that fails must not
// turn a successful migration into a failed command. A stale marker is a
// cosmetic doctor warning; a false "schema migration failed" is not.
func stampWorkspaceVersionAfterMigrate(store storage.DoltStorage) {
reconciler, err := store.VersionReconciler()
if err != nil {
debug.Logf("migrate schema: version markers unavailable: %v", err)
return
}
if _, err := reconciler.ReconcileVersion(rootCtx, issueops.VersionReconcileRequest{CLIVersion: Version}); err != nil {
debug.Logf("migrate schema: failed to record workspace version: %v", err)
}
}
func handleToSeparateBranch(branch string, dryRun bool) error {
b := strings.TrimSpace(branch)
if b == "" || strings.ContainsAny(b, " \t\n") {

View file

@ -8,6 +8,16 @@ import (
"github.com/steveyegge/beads/internal/storage/schema"
)
const (
// remoteBackedDocsURL covers the #4259 migrate-or-adopt decisions: the
// database syncs with a remote and the question is which clone migrates.
remoteBackedDocsURL = "https://github.com/gastownhall/beads/blob/main/docs/getting-started/upgrading.md#remote-backed-databases-and-multiple-clones"
// sharedServersDocsURL covers the #5920 shared-store decisions: one
// database, many clients of one server, and the question is whether they
// are all upgraded.
sharedServersDocsURL = "https://github.com/gastownhall/beads/blob/main/docs/getting-started/upgrading.md#shared-servers"
)
// handleRemoteMigrateGateJSON renders the #4259 remote-migrate gate error as a
// structured JSON error block for agent consumption.
//
@ -21,12 +31,43 @@ import (
func handleRemoteMigrateGateJSON(e *schema.RemoteMigrateGateError) {
outer := buildJSONError(e.Error(), e.AgentDirective())
if m, ok := outer.(map[string]interface{}); ok {
// The shared-no-remote consent verb is the one command in this block
// that is target-scoped: under --global the refused open aimed at
// beads_global, so the project-scoped `bd migrate schema` would consent
// the WRONG database and leave the refusal in place. Mirror the
// human/text path (printGlobalDatabaseConsentHint,
// noticeSharedMigrateRefusal) and name the --global verb when this
// invocation targeted the global database. Only shared-no-remote is
// retargeted; the remote-backed arms coordinate through bd bootstrap /
// bd migrate --force, which --global does not rewrite.
sharedConsent := schema.SharedConsentCommand
if globalFlag {
sharedConsent = schema.SharedConsentCommandGlobal
}
retargetShared := globalFlag && e.Decision == "shared-no-remote"
opts := make([]map[string]interface{}, 0, len(e.Options()))
for _, o := range e.Options() {
commands := o.Commands
if retargetShared {
// The runnable command deliberately lives inside the option, not
// in the top-level hint, so an agent that extracts it
// programmatically must get the --global verb too — fixing only
// "expected" would still hand it the wrong-target command.
retargeted := make([]string, len(commands))
for i, c := range commands {
if c == schema.SharedConsentCommand {
retargeted[i] = schema.SharedConsentCommandGlobal
} else {
retargeted[i] = c
}
}
commands = retargeted
}
opts = append(opts, map[string]interface{}{
"id": o.ID,
"when": o.When,
"commands": o.Commands,
"commands": commands,
"risk": o.Risk,
})
}
@ -39,7 +80,7 @@ func handleRemoteMigrateGateJSON(e *schema.RemoteMigrateGateError) {
"observed": fmt.Sprintf("%d pending schema migration(s) and a configured remote", e.Pending),
"expected": "exactly one designated clone migrates and publishes; every other clone adopts the result",
"options": opts,
"docs": "https://github.com/gastownhall/beads/blob/main/docs/getting-started/upgrading.md#remote-backed-databases-and-multiple-clones",
"docs": remoteBackedDocsURL,
}
// Smart gate (#4516): when a state-aware decision narrowed the stop,
// tell the agent which case it is and (for a fork) which versions skewed.
@ -48,6 +89,26 @@ func handleRemoteMigrateGateJSON(e *schema.RemoteMigrateGateError) {
gate["decision"] = "adopt"
gate["observed"] = "the remote is already migrated; migrating here would fork it"
gate["expected"] = "adopt the remote's migrated database (destructive re-clone — operator decision)"
case "shared-no-remote":
// #5920: no remote at all, so the migrate-or-adopt framing above
// does not apply — there is one shared copy and the only question
// is whether every client of it is upgraded. The base docs link
// goes with that framing, so it has to move too: an agent
// following it would brief the operator on designated-migrator
// and bd bootstrap coordination that does not exist here.
gate["decision"] = "shared-no-remote"
gate["observed"] = fmt.Sprintf("%d pending schema migration(s) on a shared server database, no consent", e.Pending)
gate["expected"] = "operator upgrades co-resident clients, then consents once via " + sharedConsent
gate["docs"] = sharedServersDocsURL
case "adopt-ff":
// A strict refinement of adopt, and on a shared store now a
// routine outcome rather than something auto-executed — so it
// needs its own tailoring instead of inheriting the default
// "exactly one designated clone migrates and publishes", which
// contradicts the adopt-only options this decision carries.
gate["decision"] = "adopt-ff"
gate["observed"] = "the remote is already migrated and this clone can fast-forward to it losslessly (no unpushed commits, clean working set)"
gate["expected"] = "adopt the remote's migrated database; nothing local is discarded"
case "fork-skew":
gate["decision"] = "fork-skew"
gate["observed"] = fmt.Sprintf("this clone and the remote applied different content for migration(s) %s — already forked", schema.FormatMigrationVersions(e.SkewVersions))

View file

@ -5,6 +5,7 @@ import (
"encoding/json"
"io"
"os"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage/schema"
@ -166,3 +167,140 @@ func TestHandleRemoteMigrateGateJSON_FallbackReason(t *testing.T) {
}
})
}
// TestHandleRemoteMigrateGateJSON_SharedNoRemote covers the shared-store
// refusal's agent-facing block (gastownhall/beads#5920). It is deliberately
// NOT the migrate-or-adopt shape: with no remote there is nothing to adopt
// from, so the only option is "migrate once the fleet is upgraded", and the
// runnable command stays inside that conditional option.
func TestHandleRemoteMigrateGateJSON_SharedNoRemote(t *testing.T) {
gate := &schema.RemoteMigrateGateError{
CurrentVersion: 53, LatestVersion: 66, Pending: 13,
Decision: "shared-no-remote",
}
origStderr := os.Stderr
r, w, pipeErr := os.Pipe()
if pipeErr != nil {
t.Fatal(pipeErr)
}
os.Stderr = w
defer func() { os.Stderr = origStderr }()
handleRemoteMigrateGateJSON(gate)
_ = w.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
t.Fatal(err)
}
_ = r.Close()
var parsed map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &parsed); err != nil {
t.Fatalf("json.Unmarshal stderr: %v\nstderr was: %s", err, buf.String())
}
if parsed["hint"] == gate.EscapeHint() {
t.Errorf("hint must not be the runnable escape command %q (agent footgun)", gate.EscapeHint())
}
obj, ok := parsed["remote_migrate_gate"].(map[string]interface{})
if !ok {
t.Fatalf("remote_migrate_gate key missing or wrong type: %T", parsed["remote_migrate_gate"])
}
if got, _ := obj["decision"].(string); got != "shared-no-remote" {
t.Errorf("decision = %v, want \"shared-no-remote\"", obj["decision"])
}
if got, _ := obj["observed"].(string); !strings.Contains(got, "shared server database") {
t.Errorf("observed = %q, want the shared-server framing", got)
}
if got, _ := obj["expected"].(string); !strings.Contains(got, "bd migrate schema") {
t.Errorf("expected = %q, want the consent verb", got)
}
if _, ok := obj["fallback_reason"]; ok {
t.Errorf("a tailored decision must not carry fallback_reason, got %v", obj["fallback_reason"])
}
rawOpts, ok := obj["options"].([]interface{})
if !ok || len(rawOpts) != 1 {
t.Fatalf("options = %v, want exactly one (no adopt path without a remote)", obj["options"])
}
o, _ := rawOpts[0].(map[string]interface{})
if id, _ := o["id"].(string); id != "migrate-shared" {
t.Errorf("option id = %v, want \"migrate-shared\"", o["id"])
}
if o["when"] == nil || o["risk"] == nil {
t.Errorf("migrate-shared option missing when/risk: %v", o)
}
cmds, _ := o["commands"].([]interface{})
if len(cmds) != 1 || cmds[0] != "bd migrate schema" {
t.Errorf("commands = %v, want [\"bd migrate schema\"]", cmds)
}
}
// TestHandleRemoteMigrateGateJSON_SharedNoRemoteGlobal covers the shared-store
// refusal's agent-facing block when the refused open targeted the global
// database (--global). The consent verb is target-scoped: the project-scoped
// `bd migrate schema` would consent the WRONG database and leave the refusal in
// place, so both the top-level "expected" directive and the runnable
// migrate-shared option command must name `bd migrate schema --global`
// (gastownhall/beads#5920), at parity with the human/text path
// (TestPrintGlobalDatabaseConsentHint). The --json notice self-suppresses, so
// this block is the sole channel for a --json consumer.
func TestHandleRemoteMigrateGateJSON_SharedNoRemoteGlobal(t *testing.T) {
origGlobal := globalFlag
globalFlag = true
defer func() { globalFlag = origGlobal }()
gate := &schema.RemoteMigrateGateError{
CurrentVersion: 53, LatestVersion: 66, Pending: 13,
Decision: "shared-no-remote",
}
origStderr := os.Stderr
r, w, pipeErr := os.Pipe()
if pipeErr != nil {
t.Fatal(pipeErr)
}
os.Stderr = w
defer func() { os.Stderr = origStderr }()
handleRemoteMigrateGateJSON(gate)
_ = w.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
t.Fatal(err)
}
_ = r.Close()
var parsed map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &parsed); err != nil {
t.Fatalf("json.Unmarshal stderr: %v\nstderr was: %s", err, buf.String())
}
obj, ok := parsed["remote_migrate_gate"].(map[string]interface{})
if !ok {
t.Fatalf("remote_migrate_gate key missing or wrong type: %T", parsed["remote_migrate_gate"])
}
if got, _ := obj["decision"].(string); got != "shared-no-remote" {
t.Errorf("decision = %v, want \"shared-no-remote\"", obj["decision"])
}
// Under --global the top-level directive must name the --global consent verb.
if got, _ := obj["expected"].(string); !strings.Contains(got, schema.SharedConsentCommandGlobal) {
t.Errorf("expected = %q, want the --global consent verb %q", got, schema.SharedConsentCommandGlobal)
}
rawOpts, ok := obj["options"].([]interface{})
if !ok || len(rawOpts) != 1 {
t.Fatalf("options = %v, want exactly one (no adopt path without a remote)", obj["options"])
}
o, _ := rawOpts[0].(map[string]interface{})
if id, _ := o["id"].(string); id != "migrate-shared" {
t.Errorf("option id = %v, want \"migrate-shared\"", o["id"])
}
// The runnable command inside the option must be the --global verb too: an
// agent extracts the command from here, not from the prose directive.
cmds, _ := o["commands"].([]interface{})
if len(cmds) != 1 || cmds[0] != schema.SharedConsentCommandGlobal {
t.Errorf("commands = %v, want [%q]", cmds, schema.SharedConsentCommandGlobal)
}
}

View file

@ -0,0 +1,161 @@
package main
import (
"bytes"
"io"
"os"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage/schema"
)
// captureNoticeStderr runs fn with os.Stderr redirected and returns what it
// wrote.
func captureNoticeStderr(t *testing.T, fn func()) string {
t.Helper()
orig := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stderr = w
fn()
_ = w.Close()
os.Stderr = orig
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
t.Fatal(err)
}
_ = r.Close()
return buf.String()
}
// TestIsSchemaMigrateVerbScope pins which invocations count as consent to
// migrate a shared database (gastownhall/beads#5920). Only `bd migrate schema`
// does. Bare `bd migrate` reconciles version/repo-id metadata and never
// applies a schema migration itself, and its flag modes are further still from
// schema work — `bd migrate --update-repo-id` is repo-fingerprint surgery, and
// treating it as consent would let a repo-ID update promote the schema for
// every co-resident client as a side effect.
func TestIsSchemaMigrateVerbScope(t *testing.T) {
for _, tt := range []struct {
name string
cmd *cobra.Command
want bool
}{
{name: "migrate schema consents", cmd: migrateSchemaCmd, want: true},
{name: "bare migrate does not", cmd: migrateCmd, want: false},
{name: "migrate sync does not", cmd: migrateSyncCmd, want: false},
{name: "an unrelated command does not", cmd: rootCmd, want: false},
} {
t.Run(tt.name, func(t *testing.T) {
if got := isSchemaMigrateVerb(tt.cmd); got != tt.want {
t.Fatalf("isSchemaMigrateVerb(%q) = %t, want %t", tt.cmd.Name(), got, tt.want)
}
})
}
}
// TestNoticeSharedMigrateRefusalPerDecision covers the one-shot version-bump
// notice. It fires once per upgrade (.local_version is consumed in the same
// pre-run), so the remedy it names has to be right for THIS refusal — the gate
// returns one error type for several decisions whose correct actions differ,
// and the migrate verb does not unlock the remote-backed ones at all.
func TestNoticeSharedMigrateRefusalPerDecision(t *testing.T) {
for _, tt := range []struct {
decision string
want string
absent string
}{
{decision: "shared-no-remote", want: "bd migrate schema"},
{decision: "adopt", want: "bd bootstrap", absent: "bd migrate schema"},
{decision: "adopt-ff", want: "bd bootstrap", absent: "bd migrate schema"},
{decision: "fork-skew", want: "bd doctor", absent: "bd migrate schema"},
{decision: "", want: "bd migrate", absent: "bd migrate schema"},
} {
name := tt.decision
if name == "" {
name = "blunt stop"
}
t.Run(name, func(t *testing.T) {
out := captureNoticeStderr(t, func() {
noticeSharedMigrateRefusal(&schema.RemoteMigrateGateError{
CurrentVersion: 65, LatestVersion: 66, Pending: 1,
Decision: tt.decision,
})
})
if !strings.Contains(out, tt.want) {
t.Errorf("notice for %q missing %q:\n%s", tt.decision, tt.want, out)
}
if tt.absent != "" && strings.Contains(out, tt.absent) {
t.Errorf("notice for %q must not prescribe %q (the verb does not unlock this arm):\n%s",
tt.decision, tt.absent, out)
}
})
}
// --json puts a machine-readable gate block on this same stream a moment
// later; prose prepended to it makes the documented contract unparseable.
t.Run("suppressed in json mode", func(t *testing.T) {
orig := jsonOutput
jsonOutput = true
defer func() { jsonOutput = orig }()
out := captureNoticeStderr(t, func() {
noticeSharedMigrateRefusal(&schema.RemoteMigrateGateError{
CurrentVersion: 65, LatestVersion: 66, Pending: 1,
Decision: "shared-no-remote",
})
})
if out != "" {
t.Errorf("notice must be silent in --json mode, got:\n%s", out)
}
})
t.Run("global flag names the global remedy", func(t *testing.T) {
orig := globalFlag
globalFlag = true
defer func() { globalFlag = orig }()
out := captureNoticeStderr(t, func() {
noticeSharedMigrateRefusal(&schema.RemoteMigrateGateError{
CurrentVersion: 65, LatestVersion: 66, Pending: 1,
Decision: "shared-no-remote",
})
})
if !strings.Contains(out, schema.SharedConsentCommandGlobal) {
t.Errorf("notice under --global must name %q:\n%s", schema.SharedConsentCommandGlobal, out)
}
})
t.Run("an untyped error prints nothing", func(t *testing.T) {
out := captureNoticeStderr(t, func() { noticeSharedMigrateRefusal(io.EOF) })
if out != "" {
t.Errorf("only a gate refusal should produce a notice, got:\n%s", out)
}
})
}
// TestPrintGlobalDatabaseConsentHint pins the one fact the gate's own block
// cannot know: which database the invocation targeted. Under --global the open
// hits `beads_global`, so the block's unflagged `bd migrate schema` would
// migrate the project database and leave the refusal in place.
func TestPrintGlobalDatabaseConsentHint(t *testing.T) {
orig := globalFlag
defer func() { globalFlag = orig }()
globalFlag = false
var off bytes.Buffer
printGlobalDatabaseConsentHint(&off)
if off.Len() != 0 {
t.Errorf("no hint without --global, got:\n%s", off.String())
}
globalFlag = true
var on bytes.Buffer
printGlobalDatabaseConsentHint(&on)
if !strings.Contains(on.String(), schema.SharedConsentCommandGlobal) {
t.Errorf("hint must name %q:\n%s", schema.SharedConsentCommandGlobal, on.String())
}
}

View file

@ -0,0 +1,202 @@
//go:build cgo
package main
import (
"context"
"database/sql"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/storage/doltutil"
"github.com/steveyegge/beads/internal/storage/schema"
"github.com/steveyegge/beads/internal/types"
)
// TestSharedServerVersionBumpDoesNotPromoteCursor reproduces
// gastownhall/beads#5920 end to end, through the real CLI.
//
// The incident: a shared dolt sql-server with no remote, a team of co-resident
// bd clients, one of them upgraded. That client's first command was a plain
// `bd list` — a read — but the root pre-run's version-bump reconciliation
// (autoMigrateOnVersionBump) opens its OWN writable store, which migrated the
// database and promoted schema_migrations for everyone. Every co-resident
// client still on the old binary then refused the database until it was
// upgraded too, for ~14 minutes, with nothing in the output saying what had
// happened.
//
// The assertion that matters is MAX(version): the read must succeed and the
// cursor must not move.
func TestSharedServerVersionBumpDoesNotPromoteCursor(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("Dolt test server not available, skipping")
}
repo := t.TempDir()
beadsDir := filepath.Join(repo, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("create .beads: %v", err)
}
database := uniqueTestDBName(t)
if err := (&configfile.Config{
Backend: configfile.BackendDolt,
DoltMode: configfile.DoltModeServer,
DoltServerHost: "127.0.0.1",
DoltServerPort: testDoltServerPort,
DoltDatabase: database,
}).Save(beadsDir); err != nil {
t.Fatalf("save metadata: %v", err)
}
ctx := context.Background()
// SetForceAllowRemoteMigrate is deliberately NOT set: this fixture creates
// the database from scratch, so the gate sees version 0 and allows it —
// creating a database is consent for its schema.
store, err := dolt.New(ctx, &dolt.Config{
Path: filepath.Join(beadsDir, "dolt"),
BeadsDir: beadsDir,
ServerHost: "127.0.0.1",
ServerPort: testDoltServerPort,
Database: database,
CreateIfMissing: true,
})
if err != nil {
t.Fatalf("create test store: %v", err)
}
if err := store.SetConfig(ctx, "issue_prefix", "shr"); err != nil {
t.Fatalf("set issue_prefix: %v", err)
}
now := time.Now()
if err := store.CreateIssue(ctx, &types.Issue{
ID: "shr-1",
Title: "Readable through the upgrade window",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: now,
UpdatedAt: now,
}, "test-user"); err != nil {
t.Fatalf("create issue: %v", err)
}
if err := store.Close(); err != nil {
t.Fatalf("close setup store: %v", err)
}
// The version-bump reconciliation only runs when the workspace has a local
// Dolt data dir (it stats cfg.DatabasePath before opening anything) — the
// shape of the auto-started localhost server the incident was reported on.
// The bytes live in the test container, but the directory is what arms the
// code path under test.
if err := os.MkdirAll(filepath.Join(beadsDir, "dolt"), 0o755); err != nil {
t.Fatalf("create local dolt data dir: %v", err)
}
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
admin, err := sql.Open("mysql", doltutil.ServerDSN{
Host: "127.0.0.1", Port: testDoltServerPort, User: "root", Database: database,
}.String())
if err != nil {
t.Fatalf("connect to test dolt server: %v", err)
}
t.Cleanup(func() { admin.Close() })
// Put the database one migration behind the candidate binary by regressing
// only the recorded cursor — the schema change itself stays applied, so
// reads keep working, exactly as they did throughout the incident.
if _, err := admin.ExecContext(ctx,
"DELETE FROM schema_migrations WHERE version = ?", schema.LatestVersion()); err != nil {
t.Fatalf("regress schema_migrations: %v", err)
}
cursor := func() int {
var v int
if err := admin.QueryRowContext(ctx,
"SELECT COALESCE(MAX(version), 0) FROM schema_migrations").Scan(&v); err != nil {
t.Fatalf("read schema cursor: %v", err)
}
return v
}
behind := cursor()
if behind != schema.LatestVersion()-1 {
t.Fatalf("precondition failed: cursor = %d, want %d", behind, schema.LatestVersion()-1)
}
// The one-shot upgrade signal: a stale .local_version makes trackBdVersion
// report a version bump, which is what arms autoMigrateOnVersionBump. The
// value has to be strictly below the candidate binary's Version and still
// in the 1.x era — a pre-1.0 witness is refused outright by the cross-era
// legacy guard long before any of this runs.
if err := os.WriteFile(filepath.Join(beadsDir, localVersionFile), []byte("1.0.0\n"), 0o600); err != nil {
t.Fatalf("write stale %s: %v", localVersionFile, err)
}
bd := buildBDForInitTests(t)
run := func(args ...string) (string, string, int) {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = repo
cmd.Env = append(filteredEnvForContextBinding("BEADS_DIR", "BEADS_DB", "BD_DB",
"BEADS_DOLT_SERVER_PORT", "BEADS_DOLT_SERVER_DATABASE", schema.AllowRemoteMigrateEnv),
"HOME="+t.TempDir(),
"XDG_CONFIG_HOME="+t.TempDir(),
"BEADS_TEST_MODE=1",
"BEADS_TEST_SERVER=1",
"BEADS_DIR="+beadsDir,
schema.AllowRemoteMigrateEnv+"=0",
)
var stdout, stderr strings.Builder
cmd.Stdout = &stdout
cmd.Stderr = &stderr
code := 0
if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("running bd %v: %v", args, err)
}
code = exitErr.ExitCode()
}
return stdout.String(), stderr.String(), code
}
stdout, stderr, code := run("list")
if code != 0 {
t.Fatalf("bd list exit = %d, want 0\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if !strings.Contains(stdout, "shr-1") {
t.Errorf("bd list did not render the issue; reads must keep working on the old schema:\n%s", stdout)
}
if got := cursor(); got != behind {
t.Fatalf("bd list promoted the schema cursor from %d to %d — this IS gastownhall/beads#5920", behind, got)
}
// The #5920 UX gap, inverted: nothing advanced, and the one-shot line says so.
if !strings.Contains(stderr, "not auto-applying") || !strings.Contains(stderr, "bd migrate schema") {
t.Errorf("expected the one-shot shared-store notice on stderr, got:\n%s", stderr)
}
// A write is refused outright, with the full guidance block rather than a
// bare error.
stdout, stderr, code = run("create", "Should be refused", "-p", "2")
if code == 0 {
t.Fatalf("bd create succeeded on a behind shared database\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
}
if !strings.Contains(stderr, "co-resident") {
t.Errorf("bd create refusal missing the shared-store guidance:\n%s", stderr)
}
if got := cursor(); got != behind {
t.Fatalf("the refused write promoted the schema cursor from %d to %d", behind, got)
}
// Consent completes the upgrade.
stdout, stderr, code = run("migrate", "schema")
if code != 0 {
t.Fatalf("bd migrate schema exit = %d, want 0\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if got := cursor(); got != schema.LatestVersion() {
t.Fatalf("cursor = %d after bd migrate schema, want %d", got, schema.LatestVersion())
}
}

View file

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
@ -14,6 +15,7 @@ import (
"github.com/steveyegge/beads/internal/doltserver"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/storage/schema"
"github.com/steveyegge/beads/issueops"
)
@ -250,6 +252,7 @@ func autoMigrateOnVersionBump(beadsDir string) {
if err != nil {
// Failed to open database - skip migration
debug.Logf("auto-migrate: failed to open database: %v", err)
noticeSharedMigrateRefusal(err)
return
}
defer func() {
@ -285,6 +288,62 @@ func autoMigrateOnVersionBump(beadsDir string) {
}
}
// noticeSharedMigrateRefusal turns the one failure autoMigrateOnVersionBump
// must not swallow into a one-line stderr notice.
//
// Every other failure here is genuinely best-effort — the command's own store
// open will report anything that matters. A gate refusal is different: it is
// the whole point of the version bump (there ARE pending migrations), it will
// not be reported by a read command's own open (read-only opens never touch
// the schema), and it is the moment gastownhall/beads#5920 used to silently
// promote the cursor for every co-resident client. Now nothing is promoted, so
// say what happened and what to do about it.
//
// It fires once per version bump, because .local_version is consumed in the
// same pre-run — which is exactly why the remedy it names has to be right for
// THIS refusal. The gate returns one error type for several very different
// decisions, and the remote-backed ones are not unlocked by the migrate verb
// at all (a clone whose remote is already migrated must adopt, not migrate),
// so the line is chosen per decision rather than printed unconditionally.
func noticeSharedMigrateRefusal(err error) {
var gateErr *schema.RemoteMigrateGateError
if !errors.As(err, &gateErr) {
return
}
// --json puts a machine-readable gate block on this same stream when the
// command's own open is refused a moment later; prose prepended to it
// makes the documented contract unparseable. The human-output sibling
// maybeShowUpgradeNotification takes the same care.
if jsonOutput {
return
}
consent := schema.SharedConsentCommand
if globalFlag {
consent = schema.SharedConsentCommandGlobal
}
var remedy string
switch gateErr.Decision {
case "shared-no-remote":
remedy = fmt.Sprintf("Run '%s' once every client of this server is upgraded; reads keep working meanwhile.", consent)
case "adopt", "adopt-ff":
// The remote is already migrated: migrating here would fork it, and
// the verb consent deliberately does not unlock this arm.
remedy = "Another clone has already migrated this database — adopt it with 'bd bootstrap' rather than migrating here; reads keep working meanwhile."
case "fork-skew":
remedy = "This database and its remote already applied different content for the same migration (#4259) — run 'bd doctor' and follow its migration-content-skew guidance; do not migrate."
default:
// The blunt remote-backed stop, including the shared-store
// first-mover suppression. Its full block names the designated-
// migrator and adopt paths with their preconditions, and picking one
// here would be guessing.
remedy = "This database has a remote — run 'bd migrate' to see the migrate-or-adopt options before choosing; reads keep working meanwhile."
}
fmt.Fprintf(os.Stderr,
"bd upgraded to v%s: %d schema migration(s) pending on this database — not auto-applying (#5920).\n%s\n",
Version, gateErr.Pending, remedy)
}
// recordedWorkspaceVersion reads the marker through the role's accessor on a
// store the caller owns and closes. It takes the storage interface rather than
// the concrete store so the probe above cannot drift into using a seam the role

View file

@ -160,7 +160,9 @@ The gate is **state-aware by default**
- **auto-migrates** when the remote is at the same schema version as this
clone — no one has migrated yet, so this clone is a safe first-mover
(concurrent first-movers converge to identical tables). It reminds you to
`bd dolt push` afterwards.
`bd dolt push` afterwards. This applies to embedded mode only: a shared
server always stops for consent, because migrating it changes the schema
every connected client sees (see [Shared servers](#shared-servers) below).
- **stops and directs you to adopt** (`bd bootstrap`) when the remote has
already been migrated by another clone.
- **stops for a human decision** when this clone and the remote applied
@ -204,11 +206,10 @@ migrating here as the designated migrator, adopting the remote's already-migrate
database, or recovering a fork — and asks for an explicit operator decision.
Follow the guidance it prints.
For scripted or CI upgrades where nobody reads the prompt,
`BD_ALLOW_REMOTE_MIGRATE=1 bd migrate` (any boolean true value works) declares
this clone the designated migrator and bypasses the gate entirely — including
its already-forked checks — so wire it into exactly one clone's upgrade job,
never all of them.
For scripted or CI upgrades where nobody reads the output, run `bd migrate` as
an explicit step in exactly one job, never in all of them. If the gate blocks a
run it prints both the available options and the scripted override that fits
the situation.
**Multiple clones sharing one remote:**
@ -243,6 +244,56 @@ schema against the cached remote ref — a useful post-upgrade verification.
It runs in both server and embedded modes.
</Note>
### Shared servers
A server-mode database is served to every `bd` client connected to that
`dolt sql-server`, so a schema migration is not a local event: it promotes the
schema version for **all** of them at once, and clients still running an older
`bd` refuse the database until they are upgraded too. `bd` therefore never
auto-migrates a shared database on a version bump — with or without a remote
configured, though the two cases consent differently
([#5920](https://github.com/gastownhall/beads/issues/5920)).
Upgrade one server's clients like this:
```bash
# 1. Upgrade bd on every client of the server. Reads keep working throughout —
# an upgraded client reads the old schema, it just cannot write to it.
bd version # on each client, confirm the new version
# 2. Once, from a workspace already set up against this server: consent.
bd migrate schema # add --global for the shared global database
# 3. Confirm.
bd doctor
```
Between steps 1 and 2, an upgraded client reads normally and its writes are
refused with the gate's guidance. Nothing is silently promoted, so there is no
deadline — but the window is a degraded one, so keep it short.
**If the shared server also has a Dolt remote**, step 2 is not enough. Two
hazards now apply at once — the co-resident lockout above and the cross-clone
fork of [Remote-backed databases](#remote-backed-databases-and-multiple-clones)
— so `bd` requires the stronger designated-migrator consent it describes:
`bd migrate --force`, from exactly one machine, followed by `bd dolt push`. If
another clone has already migrated and pushed, adopt its database with
`bd bootstrap` instead of migrating. On a shared server, adopting also promotes
the schema for every client of that server, so step 1 still comes first either
way.
<Warning>
Migrating is one-way for the fleet: after step 2, a client still on the older
`bd` refuses the database until it is upgraded. Do step 1 first, and confirm it
— the gate cannot see the other clients' versions and will take your word for
it.
</Warning>
A new client **joining** a server whose schema is behind is refused before its
workspace is written, so there is nothing to run `bd migrate schema` from
there: do step 2 from a client that is already set up, or join and migrate in
one step with `BD_ALLOW_REMOTE_MIGRATE=1 bd init …`.
## Cross-era Upgrades
If you're upgrading from a much older version of bd, inspect the storage layout

View file

@ -91,6 +91,27 @@ func TestInitSchemaOnDBWithRetryAndGate_GateErrorClassification(t *testing.T) {
}
})
t.Run("shared-store refusal is permanent, not retried", func(t *testing.T) {
// The classification keys on the error TYPE, so the new #5920 decision
// inherits it — pinned explicitly because retrying this particular
// refusal would mean retrying it into the migration it just refused.
calls := 0
gate := func(context.Context, *sql.DB) error {
calls++
return &schema.RemoteMigrateGateError{
CurrentVersion: 65, LatestVersion: 66, Pending: 1,
Decision: "shared-no-remote",
}
}
_, err := initSchemaOnDBWithRetryAndGate(ctx, db, gate)
if !schema.IsRemoteMigrateGateError(err) {
t.Fatalf("err = %T (%v), want *schema.RemoteMigrateGateError", err, err)
}
if calls != 1 {
t.Fatalf("gate calls = %d, want 1 (a shared-store refusal must not be retried)", calls)
}
})
t.Run("non-retryable probe error is permanent", func(t *testing.T) {
calls := 0
gate := func(context.Context, *sql.DB) error {

View file

@ -0,0 +1,132 @@
package dolt
import (
"context"
"errors"
"fmt"
"testing"
"github.com/steveyegge/beads/internal/storage/schema"
)
// TestDoltNew_SharedStoreMigrateGate_NoRemote is the server-mode half of
// gastownhall/beads#5920: a dolt sql-server database with NO remote at all.
//
// Before this gate, the first upgraded client to open such a database writably
// migrated it silently, promoting the schema cursor for every co-resident bd
// client on the same server — which then refused the database until each was
// upgraded too (~14 minutes of a locked-out team, in the incident). A
// sql-server store serves co-resident clients by construction, so the refusal
// does not depend on a remote existing.
//
// One CREATE/DROP DATABASE cycle covers the whole matrix: consecutive cycles
// destabilize the test dolt server, so the states are walked in order on a
// single database.
func TestDoltNew_SharedStoreMigrateGate_NoRemote(t *testing.T) {
skipIfNoDolt(t)
t.Setenv(schema.AllowRemoteMigrateEnv, "0")
t.Setenv(schema.SmartGateEnv, "0")
t.Cleanup(func() {
schema.SetSharedMigrateConsent(false)
schema.SetForceAllowRemoteMigrate(false)
})
ctx, cancel := testContext(t)
defer cancel()
tmpDir := t.TempDir()
dbName := uniqueTestDBName(t)
store, err := New(ctx, &Config{
Path: tmpDir,
CommitterName: "test",
CommitterEmail: "test@example.com",
Database: dbName,
CreateIfMissing: true,
})
if err != nil {
t.Fatalf("New (create): %v", err)
}
defer func() {
dropCtx, dropCancel := context.WithTimeout(context.Background(), 5*testTimeout)
defer dropCancel()
_, _ = store.db.ExecContext(dropCtx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName))
store.Close()
}()
// Precondition: no remote anywhere. This is the state the ordinary #4259
// gate allows straight through.
if remotes, err := store.ListRemotes(ctx); err != nil {
t.Fatalf("ListRemotes: %v", err)
} else if len(remotes) != 0 {
t.Fatalf("precondition failed: %d remote(s) registered; this test covers the no-remote case", len(remotes))
}
// Put the database one migration behind the binary by regressing only the
// recorded cursor, exactly as the #4259 integration test does.
if _, err := store.db.ExecContext(ctx,
"DELETE FROM schema_migrations WHERE version = ?", schema.LatestVersion()); err != nil {
t.Fatalf("regress schema_migrations: %v", err)
}
openWith := func(cfg *Config) error {
cfg.Path = tmpDir
cfg.CommitterName = "test"
cfg.CommitterEmail = "test@example.com"
cfg.Database = dbName
s, err := New(ctx, cfg)
if err == nil {
s.Close()
}
return err
}
cursor := func() int {
var v int
if err := store.db.QueryRowContext(ctx,
"SELECT COALESCE(MAX(version), 0) FROM schema_migrations").Scan(&v); err != nil {
t.Fatalf("read schema cursor: %v", err)
}
return v
}
behind := cursor()
if behind != schema.LatestVersion()-1 {
t.Fatalf("precondition failed: cursor = %d, want %d", behind, schema.LatestVersion()-1)
}
t.Run("writable open refuses without consent", func(t *testing.T) {
err := openWith(&Config{})
var gateErr *schema.RemoteMigrateGateError
if !errors.As(err, &gateErr) {
t.Fatalf("New (writable, behind, no remote) = %T (%v), want *schema.RemoteMigrateGateError", err, err)
}
if gateErr.Decision != "shared-no-remote" {
t.Errorf("Decision = %q, want %q", gateErr.Decision, "shared-no-remote")
}
if got := cursor(); got != behind {
t.Fatalf("the refused open promoted the cursor to %d (was %d) — this is the #5920 regression", got, behind)
}
})
// The bd-578h9.5 contract: reads must keep working on the old schema while
// the operator decides. Read-only opens never touch the schema at all.
t.Run("read-only open still succeeds", func(t *testing.T) {
if err := openWith(&Config{ReadOnly: true}); err != nil {
t.Fatalf("New (read-only, behind, no remote) = %v, want success", err)
}
if got := cursor(); got != behind {
t.Fatalf("read-only open promoted the cursor to %d (was %d)", got, behind)
}
})
t.Run("verb consent migrates", func(t *testing.T) {
schema.SetSharedMigrateConsent(true)
defer schema.SetSharedMigrateConsent(false)
if err := openWith(&Config{}); err != nil {
t.Fatalf("New (writable, consented) = %v, want success", err)
}
if got := cursor(); got != schema.LatestVersion() {
t.Fatalf("cursor = %d after a consented open, want %d", got, schema.LatestVersion())
}
})
}

View file

@ -2820,8 +2820,15 @@ func (s *DoltStore) initSchema(ctx context.Context, bootstrapHeal *schema.FreshB
// depend on that external guard alone.
ReadOnly: s.readOnly,
}
// The shared variant (#5920): a DoltStore is always a sql-server client,
// and a sql-server accepts co-resident clients by construction — that is
// what distinguishes it from the flock-guarded single-writer embedded
// store. So this open must never promote the schema cursor on its own,
// with or without a remote. Auto-started servers included: other bd
// processes attach to them while they run, which is the exact shape #5920
// was reported on.
gate := func(ctx context.Context, db *sql.DB) error {
return schema.CheckRemoteMigrateGateForRemoteWithRemoteCheckAndAdopt(ctx, db, s.remote, s.hasPersistedCLIRemote, adopt)
return schema.CheckSharedStoreMigrateGate(ctx, db, s.remote, s.hasPersistedCLIRemote, adopt)
}
applied, err := initSchemaOnDBWithRetryAndGateBootstrapHeal(ctx, migDB, gate, bootstrapHeal, s.serverEndpoint)
return applied, err

View file

@ -58,6 +58,7 @@ type migrateLockOptions struct {
freshBootstrapHeal *freshBootstrapHealRequest
lockedPreparation *lockedPreparationRequest
databaseSelector DatabaseSelector
migrationGate MigrationGate
}
type freshBootstrapHealRequest struct {
@ -188,6 +189,33 @@ func WithLockedPreparation(endpoint string, fn LockedPreparation) MigrateLockOpt
// without this package depending on it.
type DatabaseSelector func(ctx context.Context, conn DBConn, databaseName string) (quotedName string, err error)
// MigrationGate decides whether MigrateUpWithLock may apply the migrations it
// found pending. A non-nil error refuses the migration and is returned to the
// caller unchanged, so a typed refusal (*RemoteMigrateGateError) survives
// errors.As at the CLI boundary.
type MigrationGate func(context.Context, *sql.Conn) error
// WithMigrationGate installs a pre-migration gate for callers whose migration
// runs entirely inside MigrateUpWithLock, with no separate pre-open gate hook
// of the kind internal/storage/dolt runs in its own retry loop.
//
// It runs after the migration lock is acquired and after any locked
// preparation, immediately before MigrateUp. That placement is the whole
// design:
//
// - the steady-state alreadyConverged fast path above returns before the
// lock is ever taken, so a converged open pays the gate zero statements;
// - preparation has already CREATEd and USEd the database, so a fresh
// bootstrap reads CurrentVersion == 0 and passes (creating a database is
// consent for its schema);
// - a refusal propagates out through the deferred lock release, so refusing
// cannot leak the lock.
func WithMigrationGate(fn MigrationGate) MigrateLockOption {
return func(o *migrateLockOptions) {
o.migrationGate = fn
}
}
// WithDatabaseSelector lets the convergence probe put the pinned session on
// the target database itself.
//
@ -276,6 +304,12 @@ func MigrateUpWithLock(ctx context.Context, conn *sql.Conn, databaseName string,
}
}
if o.migrationGate != nil {
if gateErr := o.migrationGate(ctx, conn); gateErr != nil {
return 0, gateErr
}
}
applied, err = MigrateUp(ctx, conn)
var dirtyErr *DirtyTablesError
if err != nil && o.freshBootstrapHeal != nil && errors.As(err, &dirtyErr) {

View file

@ -913,3 +913,103 @@ func TestMigrateUpWithLockFreshBootstrapHealCapabilityIsOneShot(t *testing.T) {
t.Fatalf("unmet SQL expectations: %v", err)
}
}
// TestMigrateUpWithLockMigrationGate pins where WithMigrationGate's callback
// sits: after the lock and after locked preparation (so the gate reads a
// prepared, selected database), before MigrateUp (so a refusal applies no
// migration), and inside the deferred release (so refusing cannot leak the
// lock).
func TestMigrateUpWithLockMigrationGate(t *testing.T) {
t.Run("refusal stops before MigrateUp and releases the lock", func(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("create sql mock: %v", err)
}
defer db.Close()
ctx := context.Background()
conn, err := db.Conn(ctx)
if err != nil {
t.Fatalf("pin mock connection: %v", err)
}
defer conn.Close()
lockName := MigrationLockName("testdb")
expectConvergedFastPathMiss(mock, "testdb")
mock.ExpectQuery(regexp.QuoteMeta("SELECT GET_LOCK(?, ?)")).
WithArgs(lockName, migrationLockAcquireTimeoutSeconds).
WillReturnRows(sqlmock.NewRows([]string{"locked"}).AddRow(1))
// No migration statements between here and the release: the refusal
// must land before MigrateUp issues its first one.
mock.ExpectQuery(regexp.QuoteMeta("SELECT RELEASE_LOCK(?)")).
WithArgs(lockName).
WillReturnRows(sqlmock.NewRows([]string{"released"}).AddRow(1))
refusal := &RemoteMigrateGateError{CurrentVersion: 1, LatestVersion: 2, Pending: 1, Decision: gateDecisionSharedNoRemote}
prepared := 0
gated := 0
applied, err := MigrateUpWithLock(ctx, conn, "testdb",
WithDatabaseSelector(testDatabaseSelector),
WithLockedPreparation("tcp:test", func(context.Context, *sql.Conn) (*FreshBootstrapHealCapability, error) {
prepared++
if gated != 0 {
t.Error("the gate ran before locked preparation; it must read a prepared database")
}
return nil, nil
}),
WithMigrationGate(func(context.Context, *sql.Conn) error {
gated++
return refusal
}))
if applied != 0 {
t.Fatalf("MigrateUpWithLock() applied = %d, want 0", applied)
}
if prepared != 1 || gated != 1 {
t.Fatalf("preparation calls = %d, gate calls = %d, want 1 and 1", prepared, gated)
}
var gateErr *RemoteMigrateGateError
if !errors.As(err, &gateErr) || gateErr != refusal {
t.Fatalf("MigrateUpWithLock() error = %v, want the gate refusal unwrapped", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
t.Run("converged fast path never reaches the gate", func(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("create sql mock: %v", err)
}
defer db.Close()
ctx := context.Background()
conn, err := db.Conn(ctx)
if err != nil {
t.Fatalf("pin mock connection: %v", err)
}
defer conn.Close()
expectConvergedProbe(mock, "testdb")
gated := 0
applied, err := MigrateUpWithLock(ctx, conn, "testdb",
WithDatabaseSelector(testDatabaseSelector),
WithMigrationGate(func(context.Context, *sql.Conn) error {
gated++
return errors.New("the gate must not run on a converged database")
}))
if err != nil {
t.Fatalf("MigrateUpWithLock() error = %v", err)
}
if applied != 0 {
t.Fatalf("MigrateUpWithLock() applied = %d, want 0", applied)
}
if gated != 0 {
t.Fatalf("gate calls = %d, want 0 — the steady-state open must cost the gate nothing", gated)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet SQL expectations: %v", err)
}
})
}

View file

@ -17,6 +17,13 @@ import (
// otherwise fire, so exporting it permanently does not warn on every store open.
// The CLI-flag twin `bd migrate --force` is the preferred interactive form;
// this env var remains supported for scripted/CI use.
//
// It also unlocks the shared-store arm below, where a shared database has NO
// remote at all — "REMOTE" in the name is then a wart. It is deliberate: this
// is the single knob operators and CI already export for exactly this
// semantic ("I am the designated migrator; apply pending migrations to a
// database other clients depend on"), and a second variable would multiply
// the escape-hatch surface for no new meaning.
const AllowRemoteMigrateEnv = "BD_ALLOW_REMOTE_MIGRATE"
// forceAllowRemoteMigrate is the programmatic (in-process) twin of
@ -32,6 +39,22 @@ var forceAllowRemoteMigrate bool
// open. External test packages may reset it to false after each test case.
func SetForceAllowRemoteMigrate(v bool) { forceAllowRemoteMigrate = v }
// sharedMigrateConsent records that the operator typed the migrate verb
// itself. It unlocks ONLY the shared-store-without-a-remote arm of the gate:
// with no remote there is no cross-clone fork to risk, so the single hazard is
// locking out co-resident clients of the same server — a hazard the operator
// accepts by asking for a migration by name. A remote-backed database still
// needs --force / AllowRemoteMigrateEnv, because #4259 coordination is a
// stronger, different contract.
var sharedMigrateConsent bool
// SetSharedMigrateConsent sets (or clears) the verb consent above. Like
// SetForceAllowRemoteMigrate it is set unconditionally (set-or-clear) in the
// root PersistentPreRunE, before both autoMigrateOnVersionBump and the store
// open, and is process-local so it cannot leak into child processes. External
// test packages may reset it to false after each test case.
func SetSharedMigrateConsent(v bool) { sharedMigrateConsent = v }
// RemoteMigrateGateError is returned when bd is about to auto-apply pending
// schema migrations to an existing database that has a remote configured.
//
@ -43,6 +66,14 @@ func SetForceAllowRemoteMigrate(v bool) { forceAllowRemoteMigrate = v }
// migrated database from the remote". This gate refuses the silent in-place
// migration and makes the operator choose migrate vs. adopt. It applies to both
// server mode and embedded mode (the mode the original report was filed against).
//
// The type also carries the shared-store refusal (Decision "shared-no-remote",
// gastownhall/beads#5920), where there is no remote at all and the hazard is
// co-resident clients of one server rather than forked clones. The name is
// imperfect for that arm; every consumer — the server retry loop's permanence
// classification, embedded's lenient handling, the CLI text and JSON
// rendering, the AgentDirective/Options contract — already handles this type,
// and a parallel error universe would cost far more than the imprecise name.
type RemoteMigrateGateError struct {
CurrentVersion int
LatestVersion int
@ -73,6 +104,13 @@ type RemoteMigrateGateError struct {
// for the recognized values. Always empty when Decision is "adopt",
// "adopt-ff", or "fork-skew" — those stops already explain themselves.
FallbackReason string
// Shared marks a refusal that came from a database served to co-resident
// bd clients (gastownhall/beads#5920). It is set on EVERY arm of the
// shared gate, not just "shared-no-remote": the remote-backed arms keep
// their #4259 decisions, but their remedies carry an extra consequence
// there — adopting or migrating promotes the schema for every client of
// the server at once — so the guidance has to say so.
Shared bool
// UnrecognizedSmartGateEnv carries a BD_SMART_GATE value that was set but
// not understood (only boolean values are recognized), mirroring
// UnrecognizedEnv above but for the smart gate's own opt-out variable, so
@ -90,6 +128,13 @@ const (
// working set — adopting is loss-free, unlike a plain adopt.
gateDecisionAdoptFastForward = "adopt-ff"
gateDecisionForkSkew = "fork-skew"
// gateDecisionSharedNoRemote (gastownhall/beads#5920): the database is
// shared with co-resident bd clients (a dolt sql-server) and has NO
// remote, so there is no fork to reason about — but migrating still
// promotes the schema cursor for every client at once and locks out each
// one still on an older binary. Unlocked by the migrate verb, --force, or
// AllowRemoteMigrateEnv.
gateDecisionSharedNoRemote = "shared-no-remote"
)
// fallbackReason* enumerates why the smart gate (#4516) fell back to the
@ -111,6 +156,11 @@ const (
// recognized boolean, so the gate stayed enabled by default (same as
// unset) but still could not resolve this particular stop.
fallbackReasonUnparseableEnv = "unparseable-env"
// fallbackReasonSharedStore (gastownhall/beads#5920): the smart gate
// resolved a safe first-mover migrate, but this store is shared, so
// auto-executing it would promote the schema for every co-resident client.
// Structural, not a routing outcome — it outranks the other reasons.
fallbackReasonSharedStore = "shared-store"
)
func (e *RemoteMigrateGateError) Error() string {
@ -128,6 +178,9 @@ func (e *RemoteMigrateGateError) Error() string {
case gateDecisionForkSkew:
return fmt.Sprintf("refusing to migrate a remote-backed database (v%d -> v%d): this clone and the remote applied different content for migration(s) %s — the schema has already forked (#4259)",
e.CurrentVersion, e.LatestVersion, FormatMigrationVersions(e.SkewVersions))
case gateDecisionSharedNoRemote:
return fmt.Sprintf("refusing to auto-apply %d pending schema %s to a shared server database (v%d -> v%d): migrating would lock out every co-resident bd client still on the old schema (#5920)",
e.Pending, unit, e.CurrentVersion, e.LatestVersion)
default:
return fmt.Sprintf("refusing to auto-apply %d pending schema %s to a remote-backed database (v%d -> v%d): migrating clones independently forks the schema (#4259)",
e.Pending, unit, e.CurrentVersion, e.LatestVersion)
@ -174,6 +227,8 @@ func (e *RemoteMigrateGateError) fallbackReasonNote() string {
why = "it is disabled (" + SmartGateEnv + "=0)"
case fallbackReasonUnparseableEnv:
why = SmartGateEnv + "=" + e.UnrecognizedSmartGateEnv + " is set but was not recognized (only boolean values enable/disable it), so it stayed enabled by default but still could not resolve this stop"
case fallbackReasonSharedStore:
why = "this store is shared (dolt sql-server); the first-mover auto-migrate is disabled here because it would lock out co-resident clients (#5920)"
default:
return ""
}
@ -200,6 +255,28 @@ func (e *RemoteMigrateGateError) userBody() string {
" bd bootstrap\n" +
" Unlike the usual re-clone, this clone has no unpushed commits and no\n" +
" uncommitted local changes to discard.\n"
case gateDecisionSharedNoRemote:
return "\n" +
" This database is served to multiple clients (a dolt sql-server).\n" +
" Applying schema migrations promotes the schema version for EVERY\n" +
" client at once: bd clients still running an older version will refuse\n" +
" this database until they are upgraded.\n" +
"\n" +
" To migrate (explicit consent):\n" +
" 1. Upgrade bd on every client of this server first (or accept that\n" +
" older clients refuse until they are upgraded).\n" +
" 2. Then run, once, from a workspace already set up against this\n" +
" server:\n" +
" " + SharedConsentCommand + "\n" +
" (" + SharedConsentCommandGlobal + " for the shared global database;\n" +
" " + AllowRemoteMigrateEnv + "=1 bd <cmd> in scripted/CI use)\n" +
"\n" +
" Read commands keep working against the current schema in the meantime;\n" +
" writes stay refused until the schema is migrated.\n" +
"\n" +
" If the migration then reports dirty tables, that working set has to be\n" +
" committed first — see the recovery the dirty-table error names; do not\n" +
" re-run this command in a loop.\n"
case gateDecisionForkSkew:
return "\n" +
" This clone and the remote already applied DIFFERENT content for migration(s) " +
@ -239,6 +316,11 @@ func (e *RemoteMigrateGateError) userBody() string {
// EscapeHint returns the escape-hatch string for JSON error output.
func (e *RemoteMigrateGateError) EscapeHint() string {
if e.Decision == gateDecisionSharedNoRemote {
// No remote, so there is no designated-migrator coordination to force
// past: typing the verb IS the consent.
return SharedConsentCommand
}
return "bd migrate --force"
}
@ -266,6 +348,12 @@ func (e *RemoteMigrateGateError) AgentDirective() string {
FormatMigrationVersions(e.SkewVersions) + " — the schema has forked (#4259) and migrating cannot un-fork it. " +
"Resolving requires picking a canonical clone and re-bootstrapping the others, discarding their unpushed " +
"work — a data-loss decision. Surface remote_migrate_gate.options to the operator; do NOT auto-run anything."
case gateDecisionSharedNoRemote:
return "Coordination decision required: this database is shared with co-resident bd clients, and migrating " +
"promotes the schema for all of them at once — every client still on an older bd refuses the database " +
"until it is upgraded (#5920). Other clients' binary versions are not observable from this process, so " +
"do NOT auto-run the migration: surface remote_migrate_gate.options to the operator and let them confirm " +
"the fleet is upgraded first. Reads keep working on the current schema meanwhile."
default:
return "Coordination decision required: only ONE clone may migrate a shared remote; " +
"a second clone migrating independently forks the schema unrecoverably (#4259). " +
@ -289,11 +377,20 @@ type GateOption struct {
// present but reachable only through its "single designated migrator" condition,
// never as a top-level hint.
func (e *RemoteMigrateGateError) Options() []GateOption {
// On a shared store every remedy below lands on the database the whole
// server is serving, so each one's risk gains a consequence that has
// nothing to do with local data (gastownhall/beads#5920). Adopting is the
// case that reads most wrong without it: its risk is otherwise annotated
// purely in terms of what this machine loses.
sharedRisk := ""
if e.Shared {
sharedRisk = "; on this shared server it also promotes the schema for every co-resident client, and clients still on an older bd will refuse the database until upgraded"
}
adopt := GateOption{
ID: "adopt",
When: "another machine has already migrated and pushed",
Commands: []string{"bd bootstrap"},
Risk: "re-clones and replaces the local database; push or export unpushed work first or it is lost",
Risk: "re-clones and replaces the local database; push or export unpushed work first or it is lost" + sharedRisk,
}
switch e.Decision {
case gateDecisionAdopt:
@ -303,11 +400,18 @@ func (e *RemoteMigrateGateError) Options() []GateOption {
case gateDecisionAdoptFastForward:
// Remote is confirmed ahead AND this clone is a strict ancestor with a
// clean working set: adopting is loss-free, unlike the plain-adopt case.
// "Risk: none" is a statement about LOCAL data, and it stays true —
// but on a shared store it is not the whole risk, and an agent reading
// only this field would treat the adopt as free.
ffRisk := "none — this clone's local history is a strict ancestor of the remote's, so nothing local is discarded"
if e.Shared {
ffRisk = "nothing local is discarded (this clone's history is a strict ancestor of the remote's), but on this shared server the adopted schema is promoted for every co-resident client, and clients still on an older bd will refuse the database until upgraded"
}
return []GateOption{{
ID: "adopt-fast-forward",
When: "the remote is already migrated and this clone can fast-forward to it losslessly (no unpushed commits, clean working set)",
Commands: []string{"bd bootstrap"},
Risk: "none — this clone's local history is a strict ancestor of the remote's, so nothing local is discarded",
Risk: ffRisk,
}}
case gateDecisionForkSkew:
// Already forked: neither migrate nor a plain adopt is unconditionally
@ -318,6 +422,15 @@ func (e *RemoteMigrateGateError) Options() []GateOption {
Commands: []string{"bd export --all -o backup.jsonl", "bd bootstrap"},
Risk: "re-bootstrapping the non-canonical clones discards their unpushed work; export it first",
}}
case gateDecisionSharedNoRemote:
// No remote means no adopt path — the database is the single copy every
// client shares. The only question is whether the fleet is ready.
return []GateOption{{
ID: "migrate-shared",
When: "every co-resident bd client of this server is upgraded to this binary (confirmed with the operator), run from a workspace already set up against this server",
Commands: []string{SharedConsentCommand},
Risk: "co-resident clients still on an older bd will refuse this database until upgraded",
}}
default:
return []GateOption{
{
@ -346,7 +459,7 @@ func IsRemoteMigrateGateError(err error) bool {
// store open. Embedded mode uses this form: its dolt_remotes table already
// reflects remotes persisted in .dolt/config on a fresh open.
func CheckRemoteMigrateGate(ctx context.Context, db DBConn) error {
return checkRemoteMigrateGate(ctx, db, "", nil, nil)
return checkRemoteMigrateGate(ctx, db, "", nil, nil, false)
}
// CheckRemoteMigrateGateWithAdopt is CheckRemoteMigrateGate plus the injected
@ -357,46 +470,55 @@ func CheckRemoteMigrateGate(ctx context.Context, db DBConn) error {
// behaves exactly as CheckRemoteMigrateGate. Embedded mode uses this form
// alongside CheckRemoteMigrateGate's no-remote-name default.
func CheckRemoteMigrateGateWithAdopt(ctx context.Context, db DBConn, adopt *FastForwardAdopter) error {
return checkRemoteMigrateGate(ctx, db, "", nil, adopt)
}
// CheckRemoteMigrateGateWithRemoteCheck is CheckRemoteMigrateGate plus an on-disk
// fallback remote probe. When the dolt_remotes SQL table reports no remote,
// extraHasRemote is consulted and a true result still trips the gate.
//
// Server mode needs this: a freshly (auto-)started dolt sql-server starts with an
// empty dolt_remotes table and only re-registers CLI remotes from .dolt/config
// later, during the post-open sync (GH#2315). Because this gate runs before that
// sync, the SQL-only check would see no remote on the first write open after an
// upgrade and silently migrate the shared database in place — exactly the
// cross-clone fork #4259 is meant to prevent. extraHasRemote (a probe of the
// persisted CLI remotes) closes that window.
//
// extraHasRemote is only invoked when the database has a pending migration AND the
// SQL table shows no remote, so the (subprocess-backed) filesystem probe stays off
// the common open path. A nil extraHasRemote disables the fallback.
func CheckRemoteMigrateGateWithRemoteCheck(ctx context.Context, db DBConn, extraHasRemote func() bool) error {
return checkRemoteMigrateGate(ctx, db, "", extraHasRemote, nil)
}
// CheckRemoteMigrateGateForRemoteWithRemoteCheck is CheckRemoteMigrateGate plus
// an explicit sync remote name for the smart gate's cached remote-ref read.
// The blunt gate still trips when any Dolt remote exists; the remote name only
// chooses which remote-tracking ref the opt-in smart router compares against.
func CheckRemoteMigrateGateForRemoteWithRemoteCheck(ctx context.Context, db DBConn, remoteName string, extraHasRemote func() bool) error {
return checkRemoteMigrateGate(ctx, db, remoteName, extraHasRemote, nil)
return checkRemoteMigrateGate(ctx, db, "", nil, adopt, false)
}
// CheckRemoteMigrateGateForRemoteWithRemoteCheckAndAdopt is
// CheckRemoteMigrateGateForRemoteWithRemoteCheck plus the injected
// fast-forward ancestry callbacks (mybd-ae1i piece 2); see
// CheckRemoteMigrateGateWithAdopt. Server mode uses this form: it already has
// both a configured sync remote and the on-disk remote-check fallback.
// CheckRemoteMigrateGateWithAdopt plus an explicit sync remote name for the
// smart gate's cached remote-ref read and an on-disk fallback remote probe.
//
// The remote name only chooses which remote-tracking ref the opt-in smart
// router compares against; the blunt gate still trips when any Dolt remote
// exists. extraHasRemote covers the window where dolt_remotes reads empty
// even though a remote is configured: a freshly (auto-)started dolt
// sql-server re-registers CLI remotes from .dolt/config only later, during the
// post-open sync (GH#2315), so an SQL-only check would see no remote on the
// first write open after an upgrade. It is consulted only when the database
// has a pending migration AND the SQL table shows no remote, so the
// (subprocess-backed) filesystem probe stays off the common open path; a nil
// extraHasRemote disables the fallback.
//
// This is the non-shared form of what server mode now calls through
// CheckSharedStoreMigrateGate, and it is what internal/storage/dolt's
// smart-gate tests exercise to pin the embedded-semantics routing that the
// shared form deliberately narrows. Two thinner wrappers of the same shape
// were deleted with the swap to the shared gate: they had no callers left.
func CheckRemoteMigrateGateForRemoteWithRemoteCheckAndAdopt(ctx context.Context, db DBConn, remoteName string, extraHasRemote func() bool, adopt *FastForwardAdopter) error {
return checkRemoteMigrateGate(ctx, db, remoteName, extraHasRemote, adopt)
return checkRemoteMigrateGate(ctx, db, remoteName, extraHasRemote, adopt, false)
}
func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, extraHasRemote func() bool, adopt *FastForwardAdopter) error {
// CheckSharedStoreMigrateGate is the gate for a database that is served to
// co-resident bd clients — today, an internal/storage/dolt sql-server store.
// It adds two refusals on top of the remote-backed #4259 flow
// (gastownhall/beads#5920):
//
// - With NO remote, where the ordinary gate allows a silent in-place
// migration, it refuses unless the operator consented (the migrate verb,
// --force, or AllowRemoteMigrateEnv). Promoting the schema cursor on a
// shared server locks out every co-resident client still on an older bd.
// - With a remote, it suppresses the smart gate's two auto-EXECUTE arms
// (first-mover auto-migrate and auto-fast-forward). Both were written for
// a clone this process owns; on a shared server neither can observe the
// other clients, and the first-mover arm firing is exactly the #5920
// mechanism. The refusal directives are unchanged.
//
// A fresh database (current == 0) still migrates: creating a database is
// consent for its schema.
func CheckSharedStoreMigrateGate(ctx context.Context, db DBConn, remoteName string, extraHasRemote func() bool, adopt *FastForwardAdopter) error {
return checkRemoteMigrateGate(ctx, db, remoteName, extraHasRemote, adopt, true)
}
func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, extraHasRemote func() bool, adopt *FastForwardAdopter, shared bool) error {
// CurrentVersion treats a missing schema_migrations table as version 0, so a
// brand-new database falls through the current==0 check below — nothing to fork.
current, err := CurrentVersion(ctx, db)
@ -426,40 +548,23 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
hasRemote = extraHasRemote()
}
if !hasRemote {
return nil // no remote — no cross-clone fork risk
if !shared {
return nil // no remote — no cross-clone fork risk
}
// A shared store has co-resident clients whether or not it has a
// remote, and migrating promotes the schema cursor for all of them at
// once (gastownhall/beads#5920).
return sharedNoRemoteGate(current, len(pending))
}
// Programmatic override — set by `bd migrate --force` / `bd migrate schema
// --force` in the root PersistentPreRunE before both
// autoMigrateOnVersionBump and the main store open. Process-local by
// design: unlike os.Setenv(AllowRemoteMigrateEnv), it cannot leak into
// child processes (git hooks, dolt subprocesses). Consulted here — only
// once the gate would otherwise fire — so normal opens produce no noise.
if forceAllowRemoteMigrate {
consent := forceOrEnvConsent()
if consent.allowed {
fmt.Fprintf(os.Stderr,
"Warning: applying %d pending schema migration(s) to a remote-backed database (bd migrate --force); only one clone should migrate, then `bd dolt push`\n",
len(pending))
"Warning: applying %d pending schema migration(s) to a remote-backed database (%s); only one clone should migrate, then `bd dolt push`\n",
len(pending), consent.how)
return nil
}
// Escape hatch — consulted only once the gate would actually fire, so an
// operator who exports it in a shell profile is not warned on every store
// open with nothing pending or no remote (bd-6dnrw.34). Any boolean true
// ("1", "true", "TRUE", ...) unlocks; a set-but-unparseable value is
// surfaced in the gate error instead of silently staying locked.
unrecognizedEnv := ""
if v := os.Getenv(AllowRemoteMigrateEnv); v != "" {
if allowed, perr := strconv.ParseBool(v); perr == nil {
if allowed {
fmt.Fprintf(os.Stderr,
"Warning: applying %d pending schema migration(s) to a remote-backed database (%s=%s); only one clone should migrate, then `bd dolt push`\n",
len(pending), AllowRemoteMigrateEnv, v)
return nil
}
} else {
unrecognizedEnv = v
}
}
unrecognizedEnv := consent.unrecognizedEnv
latest := LatestVersion()
@ -483,6 +588,14 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
decision, skew, ref, atLatest := routeSmartGate(ctx, db, current, latest, remoteName, adopt)
switch decision {
case smartAutoMigrate:
// The safe-first-mover argument is about clones, not clients: it
// proves nothing about the co-resident bd processes attached to
// this same server, and auto-executing it here IS the #5920
// mechanism. Fall through to the blunt stop, naming why.
if shared {
fallbackReason = fallbackReasonSharedStore
break
}
smartGateAllowMigrate(len(pending), current)
return nil
case smartAdopt:
@ -491,6 +604,7 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
LatestVersion: latest,
Pending: len(pending),
UnrecognizedEnv: unrecognizedEnv,
Shared: shared,
Decision: gateDecisionAdopt,
}
case smartAdoptFastForward:
@ -503,7 +617,11 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
// #4259 fork risk this gate exists to prevent. Landing past
// latest would mean a newer binary already migrated the remote
// further than this one understands (#4135/#4137 class).
if atLatest && canAutoFastForward(adopt) {
// Suppressed on a shared store for the same reason as the
// first-mover arm above: the fast-forward is a WRITE that promotes
// the schema for every co-resident client. The adopt-ff refusal
// directive below is still accurate and still offered.
if !shared && atLatest && canAutoFastForward(adopt) {
// attemptFastForward re-verifies the ancestry/clean/
// remoteMax-at-latest preconditions in this SAME db session
// immediately before the write (TOCTOU guard) and performs
@ -522,6 +640,7 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
LatestVersion: latest,
Pending: len(pending),
UnrecognizedEnv: unrecognizedEnv,
Shared: shared,
Decision: gateDecisionAdopt,
}
}
@ -537,6 +656,7 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
LatestVersion: latest,
Pending: len(pending),
UnrecognizedEnv: unrecognizedEnv,
Shared: shared,
Decision: gateDecisionAdoptFastForward,
}
case smartForkSkew:
@ -545,6 +665,7 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
LatestVersion: latest,
Pending: len(pending),
UnrecognizedEnv: unrecognizedEnv,
Shared: shared,
Decision: gateDecisionForkSkew,
SkewVersions: skew,
}
@ -556,8 +677,11 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
// An unparseable BD_SMART_GATE value defaults to enabled (same as
// unset), so routing above still ran — but it is a more actionable
// fact for the operator than the technical routing outcome, so it
// takes priority as the surfaced reason.
if envState, envValue := smartGateEnvValue(); envState == smartGateEnvUnparseable {
// takes priority as the surfaced reason. Not over shared-store: that
// one is structural (the gate WOULD have resolved, and was overruled),
// so fixing the env value would not change the outcome.
envState, envValue := smartGateEnvValue()
if envState == smartGateEnvUnparseable && fallbackReason != fallbackReasonSharedStore {
fallbackReason = fallbackReasonUnparseableEnv
unrecognizedSmartGateEnv = envValue
}
@ -571,10 +695,102 @@ func checkRemoteMigrateGate(ctx context.Context, db DBConn, remoteName string, e
Pending: len(pending),
UnrecognizedEnv: unrecognizedEnv,
FallbackReason: fallbackReason,
Shared: shared,
UnrecognizedSmartGateEnv: unrecognizedSmartGateEnv,
}
}
// migrateConsent is the outcome of the consent ladder. how names the surface
// that granted it, so each arm's warning can attribute itself accurately
// instead of hardcoding one command.
type migrateConsent struct {
allowed bool
how string
// unrecognizedEnv carries an AllowRemoteMigrateEnv value that was set but
// is not a boolean, so a typo'd escape hatch fails with a hint rather than
// silently staying locked (bd-6dnrw.34).
unrecognizedEnv string
}
// forceOrEnvConsent runs the two consent surfaces BOTH arms share: the
// programmatic `--force` twin and AllowRemoteMigrateEnv.
//
// It exists so the parsing lives in one place. The two arms had hand-copied
// ladders that could drift, which is a real hazard for a variable whose own
// doc comment insists it is "the single knob" with one semantic.
//
// Both are consulted only once the gate would otherwise fire, so an operator
// who exports the env var in a shell profile is never warned on an open with
// nothing pending.
func forceOrEnvConsent() migrateConsent {
// Process-local by design: unlike os.Setenv(AllowRemoteMigrateEnv), the
// programmatic twin cannot leak into child processes (git hooks, dolt
// subprocesses). Set by `bd migrate --force` in the root PersistentPreRunE
// before both autoMigrateOnVersionBump and the main store open.
if forceAllowRemoteMigrate {
return migrateConsent{allowed: true, how: "bd migrate --force"}
}
v := os.Getenv(AllowRemoteMigrateEnv)
if v == "" {
return migrateConsent{}
}
// Any boolean true ("1", "true", "TRUE", ...) unlocks; a set-but-
// unparseable value is surfaced in the gate error instead of silently
// staying locked.
allowed, err := strconv.ParseBool(v)
if err != nil {
return migrateConsent{unrecognizedEnv: v}
}
if !allowed {
return migrateConsent{}
}
return migrateConsent{allowed: true, how: AllowRemoteMigrateEnv + "=" + v}
}
// SharedConsentCommand is the command that consents to migrating a shared
// database that has no remote. It is the single source for the gate's escape
// hint, its remediation option, and the warning it prints once consent is
// given, so those three can never name different commands.
//
// On the shared GLOBAL database (`beads_global`) the same command needs
// `--global` to route there; see SharedConsentCommandGlobal.
const SharedConsentCommand = "bd migrate schema"
// SharedConsentCommandGlobal is SharedConsentCommand aimed at the shared
// global database. `bd init` and any `--global` invocation refuse against
// their own database, so the remedy they print must carry the flag or it
// migrates the wrong one.
const SharedConsentCommandGlobal = SharedConsentCommand + " --global"
// sharedNoRemoteGate decides the shared-store-without-a-remote arm
// (gastownhall/beads#5920). There is no remote, so none of the #4259
// migrate-vs-adopt machinery applies: the only question is whether the
// operator consented to promoting the schema for every co-resident client.
func sharedNoRemoteGate(current, pending int) error {
consent := forceOrEnvConsent()
// The migrate verb is the third surface, and unlike the other two it
// unlocks ONLY here: with a remote configured, #4259's cross-clone fork
// risk still demands the stronger designated-migrator confirmation.
if !consent.allowed && sharedMigrateConsent {
consent.allowed, consent.how = true, SharedConsentCommand
}
if consent.allowed {
fmt.Fprintf(os.Stderr,
"Warning: applying %d pending schema migration(s) to a shared server database (%s); co-resident bd clients still on an older binary will refuse this database until they are upgraded (#5920)\n",
pending, consent.how)
return nil
}
return &RemoteMigrateGateError{
CurrentVersion: current,
LatestVersion: LatestVersion(),
Pending: pending,
UnrecognizedEnv: consent.unrecognizedEnv,
Decision: gateDecisionSharedNoRemote,
Shared: true,
}
}
// anyDoltRemoteConfigured reports whether the database has any Dolt remote
// registered. dolt_remotes is always present in a Dolt database; a
// "table not found" is treated as "no remotes" so a missing system table can

View file

@ -199,7 +199,7 @@ func TestCheckRemoteMigrateGateWithRemoteCheck(t *testing.T) {
mock.ExpectQuery(`SELECT COUNT\(\*\) FROM dolt_remotes`).
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0))
err := CheckRemoteMigrateGateWithRemoteCheck(context.Background(), db, func() bool { return true })
err := checkRemoteMigrateGate(context.Background(), db, "", func() bool { return true }, nil, false)
var gateErr *RemoteMigrateGateError
if !errors.As(err, &gateErr) {
t.Fatalf("expected *RemoteMigrateGateError when the disk fallback reports a remote, got %v", err)
@ -218,7 +218,7 @@ func TestCheckRemoteMigrateGateWithRemoteCheck(t *testing.T) {
mock.ExpectQuery(`SELECT COUNT\(\*\) FROM dolt_remotes`).
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0))
if err := CheckRemoteMigrateGateWithRemoteCheck(context.Background(), db, func() bool { return false }); err != nil {
if err := checkRemoteMigrateGate(context.Background(), db, "", func() bool { return false }, nil, false); err != nil {
t.Fatalf("no remote anywhere should be allowed, got %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
@ -236,10 +236,10 @@ func TestCheckRemoteMigrateGateWithRemoteCheck(t *testing.T) {
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(1))
called := false
err := CheckRemoteMigrateGateWithRemoteCheck(context.Background(), db, func() bool {
err := checkRemoteMigrateGate(context.Background(), db, "", func() bool {
called = true
return false
})
}, nil, false)
if !IsRemoteMigrateGateError(err) {
t.Fatalf("expected gate error when dolt_remotes already shows a remote, got %v", err)
}
@ -260,10 +260,10 @@ func TestCheckRemoteMigrateGateWithRemoteCheck(t *testing.T) {
expectGateCurrentVersion(mock, latest) // PendingVersions -> none
called := false
err := CheckRemoteMigrateGateWithRemoteCheck(context.Background(), db, func() bool {
err := checkRemoteMigrateGate(context.Background(), db, "", func() bool {
called = true
return true
})
}, nil, false)
if err != nil {
t.Fatalf("at-latest DB should be allowed, got %v", err)
}

View file

@ -0,0 +1,393 @@
package schema
import (
"context"
"errors"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
// expectSharedGateProbe mocks the probe sequence every gate invocation issues
// before it can decide anything: CurrentVersion, PendingVersions, and the
// dolt_remotes count.
func expectSharedGateProbe(mock sqlmock.Sqlmock, current int, remotes int) {
expectGateCurrentVersion(mock, current) // CurrentVersion
expectGateCurrentVersion(mock, current) // PendingVersions -> pending exists
mock.ExpectQuery(`SELECT COUNT\(\*\) FROM dolt_remotes`).
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(remotes))
}
func sharedGate(t *testing.T, mock sqlmock.Sqlmock, db DBConn) error {
t.Helper()
err := CheckSharedStoreMigrateGate(context.Background(), db, "", nil, nil)
if merr := mock.ExpectationsWereMet(); merr != nil {
t.Fatalf("unmet expectations: %v", merr)
}
return err
}
// resetConsent clears both process-local consent flags around a test case.
// They are package-level by design (set once in the root pre-run), so a test
// that leaves one set silently unlocks every later case.
func resetConsent(t *testing.T) {
t.Helper()
t.Cleanup(func() {
SetForceAllowRemoteMigrate(false)
SetSharedMigrateConsent(false)
})
}
// TestSharedStoreGateNoRemote covers the gastownhall/beads#5920 arm: a shared
// database with NO remote, where the ordinary (embedded) gate allows a silent
// in-place migration. On a shared store that promotes the schema cursor for
// every co-resident client at once, so it refuses without explicit consent.
func TestSharedStoreGateNoRemote(t *testing.T) {
t.Setenv(SmartGateEnv, "0") // no remote, so the smart router never runs anyway
latest := LatestVersion()
t.Run("pending migrations, no remote, no consent → refused", func(t *testing.T) {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 0)
var gateErr *RemoteMigrateGateError
if err := sharedGate(t, mock, db); !errors.As(err, &gateErr) {
t.Fatalf("expected *RemoteMigrateGateError, got %v", err)
}
if gateErr.Decision != gateDecisionSharedNoRemote {
t.Fatalf("Decision = %q, want %q", gateErr.Decision, gateDecisionSharedNoRemote)
}
if gateErr.CurrentVersion != 1 || gateErr.LatestVersion != latest || gateErr.Pending <= 0 {
t.Errorf("gate error = %+v, want current 1, latest %d, pending > 0", gateErr, latest)
}
msg := gateErr.UserMessage()
for _, want := range []string{
"lock out every co-resident bd client",
"bd migrate schema",
"Read commands keep working",
AllowRemoteMigrateEnv + "=1",
} {
if !strings.Contains(msg, want) {
t.Errorf("UserMessage missing %q:\n%s", want, msg)
}
}
// The #4259 remedies do not apply with no remote: there is one copy of
// the database, so there is nothing to adopt and nothing to push.
for _, absent := range []string{"bd bootstrap", "bd dolt push"} {
if strings.Contains(msg, absent) {
t.Errorf("UserMessage must not offer %q with no remote:\n%s", absent, msg)
}
}
if hint := gateErr.EscapeHint(); hint != "bd migrate schema" {
t.Errorf("EscapeHint = %q, want %q", hint, "bd migrate schema")
}
opts := gateErr.Options()
if len(opts) != 1 || opts[0].ID != "migrate-shared" {
t.Fatalf("Options = %+v, want a single migrate-shared option", opts)
}
if opts[0].When == "" || opts[0].Risk == "" {
t.Errorf("migrate-shared option must carry its precondition and risk: %+v", opts[0])
}
if directive := gateErr.AgentDirective(); !strings.Contains(directive, "do NOT auto-run") {
t.Errorf("AgentDirective must forbid auto-running the migration: %q", directive)
}
})
t.Run("fresh database still migrates — creating a database is consent", func(t *testing.T) {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectGateCurrentVersion(mock, 0)
if err := sharedGate(t, mock, db); err != nil {
t.Fatalf("fresh shared database must be allowed, got %v", err)
}
})
t.Run("nothing pending is allowed", func(t *testing.T) {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectGateCurrentVersion(mock, latest) // CurrentVersion
expectGateCurrentVersion(mock, latest) // PendingVersions -> none
if err := sharedGate(t, mock, db); err != nil {
t.Fatalf("converged shared database must be allowed, got %v", err)
}
})
t.Run("verb consent unlocks with a warning", func(t *testing.T) {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 0)
SetSharedMigrateConsent(true)
var err error
stderr := captureStderr(t, func() { err = sharedGate(t, mock, db) })
if err != nil {
t.Fatalf("bd migrate schema consent must unlock, got %v", err)
}
if !strings.Contains(stderr, "bd migrate schema") || !strings.Contains(stderr, "#5920") {
t.Errorf("expected a shared-store warning naming the verb, got %q", stderr)
}
})
t.Run("--force unlocks with a warning", func(t *testing.T) {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 0)
SetForceAllowRemoteMigrate(true)
var err error
stderr := captureStderr(t, func() { err = sharedGate(t, mock, db) })
if err != nil {
t.Fatalf("--force must unlock, got %v", err)
}
if !strings.Contains(stderr, "bd migrate --force") {
t.Errorf("expected a warning naming --force, got %q", stderr)
}
})
t.Run("env unlocks with a warning", func(t *testing.T) {
for _, v := range []string{"1", "true", "TRUE"} {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, v)
db, mock, _ := sqlmock.New()
expectSharedGateProbe(mock, 1, 0)
var err error
stderr := captureStderr(t, func() { err = sharedGate(t, mock, db) })
if err != nil {
t.Fatalf("%s=%s must unlock, got %v", AllowRemoteMigrateEnv, v, err)
}
if !strings.Contains(stderr, AllowRemoteMigrateEnv+"="+v) {
t.Errorf("%s=%s: expected a warning naming the variable, got %q", AllowRemoteMigrateEnv, v, stderr)
}
db.Close()
}
})
t.Run("unparseable env stays locked with a hint", func(t *testing.T) {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, "yes")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 0)
var gateErr *RemoteMigrateGateError
if err := sharedGate(t, mock, db); !errors.As(err, &gateErr) {
t.Fatalf("expected *RemoteMigrateGateError, got %v", err)
}
if gateErr.UnrecognizedEnv != "yes" {
t.Errorf("UnrecognizedEnv = %q, want %q", gateErr.UnrecognizedEnv, "yes")
}
if !strings.Contains(gateErr.UserMessage(), "not recognized") {
t.Errorf("UserMessage missing the unrecognized-value hint:\n%s", gateErr.UserMessage())
}
})
// Invariant 1 of the decision: embedded/local databases keep auto-migrating
// on a version bump. Same state, non-shared caller, no refusal.
t.Run("embedded (non-shared) caller is unaffected", func(t *testing.T) {
resetConsent(t)
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 0)
if err := CheckRemoteMigrateGate(context.Background(), db); err != nil {
t.Fatalf("embedded no-remote open must still auto-migrate, got %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
})
}
// TestSharedStoreGateSuppressesSmartAutoArms covers the remote-configured half:
// the #4259 flow is unchanged except that the smart gate's two auto-EXECUTE
// arms never fire on a shared store. The first-mover arm firing here IS the
// #5920 mechanism.
func TestSharedStoreGateSuppressesSmartAutoArms(t *testing.T) {
floor := LastNonDeterministicMigration
latest := LatestVersion()
t.Run("first-mover auto-migrate is suppressed to a blunt stop", func(t *testing.T) {
resetConsent(t)
t.Setenv(SmartGateEnv, "1")
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSmartFiringGate(mock, floor)
hashes := map[int]string{floor - 1: "h1", floor: "h2"}
expectSmartRemoteRead(mock, hashes, hashes)
err := CheckSharedStoreMigrateGate(context.Background(), db, "", nil, nil)
var gateErr *RemoteMigrateGateError
if !errors.As(err, &gateErr) {
t.Fatalf("shared store must refuse the first-mover migrate, got %v", err)
}
if gateErr.Decision != "" {
t.Errorf("Decision = %q, want the blunt stop", gateErr.Decision)
}
if gateErr.FallbackReason != fallbackReasonSharedStore {
t.Errorf("FallbackReason = %q, want %q", gateErr.FallbackReason, fallbackReasonSharedStore)
}
if !strings.Contains(gateErr.UserMessage(), "lock out co-resident clients") {
t.Errorf("UserMessage should explain the shared-store suppression:\n%s", gateErr.UserMessage())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
})
t.Run("embedded caller in the same state still auto-migrates", func(t *testing.T) {
resetConsent(t)
t.Setenv(SmartGateEnv, "1")
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSmartFiringGate(mock, floor)
hashes := map[int]string{floor - 1: "h1", floor: "h2"}
expectSmartRemoteRead(mock, hashes, hashes)
if err := CheckRemoteMigrateGate(context.Background(), db); err != nil {
t.Fatalf("embedded safe first-mover must still be allowed, got %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
})
// A refusal that came from a shared store carries consequences its #4259
// decisions were never annotated for: every remedy lands on the database
// the whole server is serving. adopt-ff is the sharp case — its risk is
// otherwise literally "none", which an agent would read as free.
t.Run("shared refusals annotate the fleet-wide risk", func(t *testing.T) {
for _, decision := range []string{gateDecisionAdopt, gateDecisionAdoptFastForward} {
shared := (&RemoteMigrateGateError{Decision: decision, Shared: true}).Options()
if len(shared) != 1 {
t.Fatalf("%s: expected one option, got %+v", decision, shared)
}
if !strings.Contains(shared[0].Risk, "co-resident") {
t.Errorf("%s: shared risk must name the co-resident consequence, got %q", decision, shared[0].Risk)
}
local := (&RemoteMigrateGateError{Decision: decision}).Options()
if strings.Contains(local[0].Risk, "co-resident") {
t.Errorf("%s: a non-shared refusal must keep its original risk, got %q", decision, local[0].Risk)
}
}
// "Risk: none" is only ever correct off a shared store.
ff := (&RemoteMigrateGateError{Decision: gateDecisionAdoptFastForward, Shared: true}).Options()
if strings.HasPrefix(ff[0].Risk, "none") {
t.Errorf("adopt-ff on a shared store must not report no risk, got %q", ff[0].Risk)
}
})
t.Run("shared is set on the remote-backed arms too", func(t *testing.T) {
resetConsent(t)
t.Setenv(SmartGateEnv, "0")
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 1)
err := CheckSharedStoreMigrateGate(context.Background(), db, "", nil, nil)
var gateErr *RemoteMigrateGateError
if !errors.As(err, &gateErr) {
t.Fatalf("expected a gate error, got %v", err)
}
if !gateErr.Shared {
t.Error("a refusal from the shared gate must be marked Shared, whatever its decision")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
})
t.Run("auto fast-forward is never executed", func(t *testing.T) {
resetConsent(t)
t.Setenv(SmartGateEnv, "1")
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSmartFiringGate(mock, floor)
local := map[int]string{floor: "h1"}
// Exactly the fixture that DOES auto-execute on an embedded clone
// (remote at latest, strict ancestor, clean working set) — no TOCTOU
// re-read is expected here because the write never happens.
remote := map[int]string{floor: "h1", latest: "h2"}
expectSmartRemoteRead(mock, local, remote)
fa := &fakeAdopter{ancestorResult: true, cleanResult: true, withFastForward: true}
err := CheckSharedStoreMigrateGate(context.Background(), db, "", nil, fa.adopter())
var gateErr *RemoteMigrateGateError
if !errors.As(err, &gateErr) {
t.Fatalf("shared store must refuse rather than fast-forward, got %v", err)
}
if gateErr.Decision != gateDecisionAdoptFastForward {
t.Errorf("Decision = %q, want %q (the directive stays accurate, only the write is suppressed)",
gateErr.Decision, gateDecisionAdoptFastForward)
}
if fa.ffCalls != 0 {
t.Errorf("FastForward calls = %d, want 0 on a shared store", fa.ffCalls)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
})
// Verb consent is scoped to the no-remote arm on purpose: with a remote,
// #4259's cross-clone fork risk still demands the designated-migrator
// confirmation.
t.Run("verb consent does not unlock the remote-backed arm", func(t *testing.T) {
resetConsent(t)
t.Setenv(SmartGateEnv, "0")
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 1)
SetSharedMigrateConsent(true)
err := CheckSharedStoreMigrateGate(context.Background(), db, "", nil, nil)
if !IsRemoteMigrateGateError(err) {
t.Fatalf("verb consent must not unlock a remote-backed database, got %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
})
t.Run("--force still unlocks the remote-backed arm", func(t *testing.T) {
resetConsent(t)
t.Setenv(SmartGateEnv, "0")
t.Setenv(AllowRemoteMigrateEnv, "0")
db, mock, _ := sqlmock.New()
defer db.Close()
expectSharedGateProbe(mock, 1, 1)
SetForceAllowRemoteMigrate(true)
var err error
_ = captureStderr(t, func() {
err = CheckSharedStoreMigrateGate(context.Background(), db, "", nil, nil)
})
if err != nil {
t.Fatalf("--force must unlock a remote-backed shared database, got %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet expectations: %v", err)
}
})
}

View file

@ -168,7 +168,7 @@ func TestSmartGateRouting(t *testing.T) {
hashes := map[int]string{floor: "h"}
expectSmartRemoteReadForRemote(mock, "upstream", hashes, hashes)
if err := CheckRemoteMigrateGateForRemoteWithRemoteCheck(context.Background(), db, "upstream", nil); err != nil {
if err := checkRemoteMigrateGate(context.Background(), db, "upstream", nil, nil, false); err != nil {
t.Fatalf("safe first-mover on configured remote should be allowed, got %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {