fix(cmd/bd): run workspace identity check before applying schema migrations (#6674)
* test(feat): red — bd migrate schema advances schema_migrations before refusing an identity mismatch (refs be-0gfcs) validateWorkspaceIdentity runs after the shared pre-run has already opened the store and let the smart gate auto-apply a pending schema migration. The refusal (exit 1, mismatch message) is correct but arrives too late: schema_migrations has already advanced. New embedded-mode CLI integration test reproduces this by regressing schema_migrations one version and corrupting _project_id, then asserting the cursor is unchanged after a refused `bd migrate schema` -- it currently is not. * feat: green — bd migrate schema applies migrations BEFORE the workspace identity check refuses — the guard cannot prevent what it is guarding against (refs be-0gfcs) * test(feat): red — Review: bd migrate schema applies migrations BEFORE the workspace identity check refuses — the guard cannot prevent what it is guarding against (refs be-3bt2e) * feat: green — Review: bd migrate schema applies migrations BEFORE the workspace identity check refuses — the guard cannot prevent what it is guarding against (refs be-3bt2e) * fix(main): render typed open errors from the identity gate's refusal arm Maintainer review fixup for PR #6674 (adopt-pr iteration 1). Synthesis decision is request_changes with two majors and several non-gating minors. MAJOR 1 (fixed) — the gate's `default:` arm refused with a bare HandleError, so every typed open error the PREVIEW hits was reported as this gate's generic wrapper. That is two regressions against base, where the same classes surfaced from the real open and were rendered properly: (a) `bd --json` exited 1 with unstructured stderr and NO JSON body — a machine contract break for every JSON consumer; (b) the appended `BEADS_SKIP_IDENTITY_CHECK=1` hint is actively wrong for those classes, since skipping the gate leaves the real open failing identically. It matters most for schema skew: the preview runs CheckForwardDrift, so the recurring stale-binary class (#4135/#4137) now fails the preview first, and SchemaSkewError.UserMessage()'s actionable rebuild block was being replaced by a generic line plus a dead-end hint. handleFreshCloneError, RemoteMigrateGateError and the server-mode projectIdentityMismatchError refusal were bypassed the same way. The arm now mirrors the real-open arm — handleFreshCloneError, then renderTypedOpenError — before falling back to HandleErrorRespectJSON, so --json callers still get a structured body, and the override hint now lives only on the generic arm and says what it actually does. Extracted as refuseUnverifiablePreviewOpen so both halves are testable without standing up a forward-drifted workspace. Pinned by TestRefuseUnverifiablePreviewOpenRendersTypedErrors: a skew keeps its own UX and does NOT advertise the override; a skew under --json emits a schema_skew body with current/required/delta; a preview-specific error keeps the generic message, keeps the override hint, and still emits a JSON body. Proven non-vacuous — restoring the pre-fix shape (typed renderers bypassed) fails it. Note the two arms write their JSON to different streams (handleSchemaSkewJSON to stderr, HandleErrorRespectJSON to stdout); that split is pre-existing and the test documents rather than changes it. MAJOR 2 (deliberately not fixed here; filed with a measurement as mc-wbso0) — the gate is unscoped, and server mode already had the pre-migration identity guarantee (dolt/store.go:2030-2062 runs verifyProjectIdentity before initSchema at :2067). The reviewer offered scoping OR, explicitly, "keep the gate unconditional, fix Finding 1, and file the duplicate-open cost as a tracked follow-up with a measurement — not to leave both unaddressed". Taking the sanctioned alternative, because scoping carries two caveats neither reviewer priced (server-mode verification is itself conditional on `!cfg.CreateIfMissing || dbFacts.alreadyExisted`; gateway server mode is deliberately excluded from identity enforcement) and it changes hot-path startup behavior for every write command — not a change to guess at mid-adoption. Measured rather than asserted, on a healthy embedded workspace (ambient beads env unset, 2 warmup runs discarded, 8 runs of `bd config set` each way): WITH gate median 0.329s (mean 0.332, 0.317-0.362) WITHOUT gate median 0.290s (mean 0.292, 0.277-0.314) => +39ms, +14% of un-gated startup, spreads non-overlapping. That number is in mc-wbso0 along with both caveats. Also took one non-gating minor while in the file: the refusal test saved the `store` global but never zeroed it, so its closing `store != nil` assertion could pass or fail on a leftover from an earlier test. `store = nil` added. Validation: git diff --check clean; gofmt clean; go build ./... clean; go vet ./cmd/bd/ clean; golangci-lint v2.10.1 (pr.yml's pin) 0 issues; the gate's full test surface under CI's own flags (-tags gms_pure_go -race -short) 13 PASS 0 FAIL 0 SKIP, with no shared-TMPDIR sweep damage. ITERATION 2 — synthesis and scorecard both `approve`, `Required Changes: None`, four minors. Took all four; none is a merge gate, and the fixup commit already exists so none of them costs an extra push. 1. The doc comment on refuseUnverifiablePreviewOpen overstated its own coverage: it named four typed classes as "rendered exactly as the real-open arm renders them", but only schema skew can actually arrive typed from a preview. Verified each claim before rewriting the comment rather than trusting the review: handleFreshCloneError matches a post-migration string (`main_errors.go`) a non-mutating preview never produces, and both CheckRemoteMigrateGate* call sites (`embeddeddolt/store.go:442`, `dolt/store.go:3073`) are on mutating opens, never openReadOnly. projectIdentityMismatchError is a plain fmt.Errorf with no typed wrapper, so it falls to the generic arm and picks up its prefix — which matches base, where it reached the operator inside the real arm's "failed to open database: %v" wrapper. The comment now says that, names the other two calls as defensive-for-symmetry with the reason each cannot fire, and flags that handleFreshCloneError ignores jsonOutput, so making it reachable would break the --json guarantee this fix established. 2. Pinned the preview→skew WIRE, not just the renderer. TestRefuseUnverifiablePreviewOpenRendersTypedErrors hand-builds a SchemaSkewError, so it could stay green while a change to the preview's drift check moved skew back onto the generic arm — the durability gap that mattered most, since the wire is this fix's whole premise. New TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace bootstraps a real embedded workspace, stages one schema_migrations row above the binary's latest, and drives rootCmd.PersistentPreRunE end to end, asserting the skew UX arrives and the generic identity wrapper does not. Reuses the package's existing withEmbeddedMigrateSQL helper. Counterfactual run: restoring the pre-fix bare-HandleError arm reds it on exactly the three regression assertions, printing the original bug verbatim (generic wrapper swallowing the rebuild block, plus the dead-end BEADS_SKIP_IDENTITY_CHECK hint) at a real measured v68-vs-v67 drift. 3. Re-filed the MAJOR 2 tracking artifact as bd-ocmut in the beads rig store and closed mc-wbso0 as superseded. The body was complete and correct; only the routing was wrong — the finding is about beads repo code (cmd/bd), and beads-code PR follow-ups are triaged from the beads rig store, not maintainer-city. Also added a maintainer-notes section to the PR body carrying the deferral, the +39ms measurement and the bd-ocmut pointer, so the condition the deferral rests on is discoverable in-band rather than only out-of-band. 4. isBootstrapPreviewErr breadth is now explicitly on the deferral list below; it had been dropped from it without acknowledgment, which is how a checklist item vanishes at finalize. Tracked remainder, deliberately deferred (all non-gating across both iterations): - isBootstrapPreviewErr is still bare errors.Is(err, os.ErrNotExist), so it accepts any ENOENT-wrapped dial failure, not just "no database directory"; its table test pins only a fabricated negative. Message-contract weakening, not a safety hole, and no in-tree backend registers. - a non-nil fake for TestValidateWorkspaceIdentity_NonexistentDir - the nil-guard precondition on validateWorkspaceIdentity's doc comment - the embedded-tier-only reproduction pins now noted in the PR body Validation (iteration 2): gofmt clean; go build ./... clean; go vet ./cmd/bd/ clean; CGO_ENABLED=0 go vet -tags gms_pure_go ./cmd/bd/ clean (the new file is cgo-tagged, so the no-cgo lane must still compile); golangci-lint v2.10.1 (pr.yml's pin) 0 issues; git diff --check clean. Gate surface run per-test to avoid shared-rootCmd batch false-reds: 13 PASS 0 FAIL under CI's own flags (-tags gms_pure_go -race -short), and the 3 embedded-tier tests all PASS with BEADS_TEST_EMBEDDED_DOLT=1 (new pin 5.3s, fresh-workspace 4.0s, migrate-order 25.2s) — no silent skips. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
991e5e3aa4
commit
cb5ae77061
6 changed files with 717 additions and 28 deletions
238
cmd/bd/identity_preview_gate_cgo_test.go
Normal file
238
cmd/bd/identity_preview_gate_cgo_test.go
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/debug"
|
||||
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
)
|
||||
|
||||
// TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace is
|
||||
// the MINOR-criterion regression test for be-0gfcs round 2 (be-3bt2e): a
|
||||
// brand-new workspace -- metadata.json present, but no embedded database on
|
||||
// disk yet -- is the one previewErr case the identity check has always
|
||||
// tolerated. It must still emit a debug-visible log line explaining why it
|
||||
// was skipped, so the skip is diagnosable under BD_DEBUG/--verbose instead of
|
||||
// looking identical to "the check silently ran and found nothing wrong."
|
||||
//
|
||||
// This exercises a real embedded-Dolt bootstrap (schema init on first open),
|
||||
// so it is opt-in like the other embedded-dolt integration tests in this
|
||||
// package: set BEADS_TEST_EMBEDDED_DOLT=1 to run it.
|
||||
func TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
|
||||
}
|
||||
|
||||
repoDir := t.TempDir()
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
writeTestConfigYAML(t, beadsDir, "")
|
||||
// No .beads/embeddeddolt data dir: newPreviewStoreFromConfig's embedded
|
||||
// open fails with a wrapped os.ErrNotExist -- the legitimate first-run
|
||||
// condition this check must keep skipping (silently, save for the debug
|
||||
// log line under test here).
|
||||
writeMetadataConfig(t, beadsDir, configfile.DoltModeEmbedded, "identity_gate_bootstrap_test")
|
||||
|
||||
t.Chdir(repoDir)
|
||||
t.Setenv("BEADS_DIR", beadsDir)
|
||||
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
|
||||
t.Setenv("BEADS_DOLT_AUTO_START", "0")
|
||||
t.Setenv("BEADS_SKIP_IDENTITY_CHECK", "")
|
||||
|
||||
config.ResetForTesting()
|
||||
t.Cleanup(config.ResetForTesting)
|
||||
savePersistentPreRunState(t)
|
||||
|
||||
oldStore := store
|
||||
t.Cleanup(func() { store = oldStore })
|
||||
|
||||
// PersistentPreRunE itself calls debug.SetVerbose(verboseFlag) before
|
||||
// reaching the identity check (main.go), which would silently overwrite
|
||||
// this with the zero-value verboseFlag=false -- this test calls
|
||||
// PersistentPreRunE directly, bypassing the cobra flag parsing that
|
||||
// would otherwise populate verboseFlag from a real -v/--verbose flag.
|
||||
oldVerboseFlag := verboseFlag
|
||||
verboseFlag = true
|
||||
t.Cleanup(func() { verboseFlag = oldVerboseFlag })
|
||||
debug.SetVerbose(true)
|
||||
t.Cleanup(func() { debug.SetVerbose(false) })
|
||||
|
||||
if rootCmd.PersistentPreRunE == nil {
|
||||
t.Fatal("rootCmd.PersistentPreRunE must be set")
|
||||
}
|
||||
|
||||
// Named "import", not a distinct probe name: beads.FindDatabasePath()
|
||||
// legitimately returns "" for this exact on-disk state (metadata.json
|
||||
// present, no .beads/embeddeddolt/ yet -- see findDatabaseInBeadsDir),
|
||||
// and PersistentPreRunE's earlier, unrelated "no beads database found"
|
||||
// gate (main.go) refuses any command whose name isn't "import" or
|
||||
// "setup" before it ever reaches the identity check under test here.
|
||||
// "import" is also the realistic case: it is the one command documented
|
||||
// to auto-initialize a missing database, so it is the command a fresh
|
||||
// embedded workspace's first invocation would actually be. rootCmd
|
||||
// already has a real import command registered under the same name;
|
||||
// that's harmless here since PersistentPreRunE only ever compares
|
||||
// cmd.Name() as a string (never looks a sibling up by name), and
|
||||
// RemoveCommand below matches this probe by pointer identity, not name.
|
||||
probe := &cobra.Command{
|
||||
Use: "import",
|
||||
RunE: func(*cobra.Command, []string) error { return nil },
|
||||
}
|
||||
rootCmd.AddCommand(probe)
|
||||
t.Cleanup(func() { rootCmd.RemoveCommand(probe) })
|
||||
|
||||
oldStderr := os.Stderr
|
||||
r, w, pipeErr := os.Pipe()
|
||||
if pipeErr != nil {
|
||||
t.Fatalf("os.Pipe: %v", pipeErr)
|
||||
}
|
||||
os.Stderr = w
|
||||
|
||||
err := rootCmd.PersistentPreRunE(probe, nil)
|
||||
|
||||
w.Close()
|
||||
os.Stderr = oldStderr
|
||||
var captured bytes.Buffer
|
||||
io.Copy(&captured, r) //nolint:errcheck // best-effort drain of a test pipe
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("PersistentPreRunE on a fresh embedded workspace: %v\nstderr:\n%s", err, captured.String())
|
||||
}
|
||||
|
||||
const wantMarker = "workspace identity check: skipping"
|
||||
if !strings.Contains(captured.String(), wantMarker) {
|
||||
t.Errorf("expected a debug log line containing %q noting the identity check was skipped for a fresh workspace, got stderr:\n%s", wantMarker, captured.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace pins the
|
||||
// preview→skew WIRE, which TestRefuseUnverifiablePreviewOpenRendersTypedErrors
|
||||
// deliberately does not: that test hands refuseUnverifiablePreviewOpen a
|
||||
// hand-built *schema.SchemaSkewError, so it pins the renderer in isolation.
|
||||
//
|
||||
// The premise the renderer rests on is that a forward-drifted workspace now
|
||||
// fails the PREVIEW open (OpenForPreviewCommand runs CheckForwardDrift) rather
|
||||
// than the real one. Nothing pinned that link: a change to the preview's drift
|
||||
// check, or to which factory arm the gate calls, would move skew back onto the
|
||||
// generic arm -- restoring the exact regression this fix removed -- with every
|
||||
// renderer subtest still green. So drive it end to end instead, from a real
|
||||
// workspace whose schema cursor is ahead of this binary through
|
||||
// rootCmd.PersistentPreRunE.
|
||||
//
|
||||
// This bootstraps a real embedded-Dolt database, so it is opt-in on the same
|
||||
// tier as the sibling above: set BEADS_TEST_EMBEDDED_DOLT=1 to run it.
|
||||
func TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
|
||||
}
|
||||
|
||||
const database = "identity_gate_skew_test"
|
||||
ctx := t.Context()
|
||||
|
||||
repoDir := t.TempDir()
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
writeTestConfigYAML(t, beadsDir, "")
|
||||
writeMetadataConfig(t, beadsDir, configfile.DoltModeEmbedded, database)
|
||||
|
||||
// A real bootstrap, not a fake: Open creates the data dir and runs
|
||||
// initSchema, which is what leaves the schema_migrations cursor the drift
|
||||
// check reads. Closed again so the gate's own preview open is the only
|
||||
// holder.
|
||||
bootstrap, err := embeddeddolt.Open(ctx, beadsDir, database, "main")
|
||||
if err != nil {
|
||||
t.Fatalf("bootstrap embedded workspace: %v", err)
|
||||
}
|
||||
if err := bootstrap.Close(); err != nil {
|
||||
t.Fatalf("close bootstrap store: %v", err)
|
||||
}
|
||||
|
||||
// Forward-drift it. CurrentVersion is MAX(version) over schema_migrations,
|
||||
// so a single row above the binary's latest reproduces the recurring
|
||||
// stale-binary class (#4135/#4137) that made this arm's UX matter.
|
||||
ahead := schema.LatestVersion() + 1
|
||||
withEmbeddedMigrateSQL(t, beadsDir, database, func(db *sql.DB) error {
|
||||
_, err := db.ExecContext(ctx,
|
||||
"INSERT INTO schema_migrations (version, content_hash) VALUES (?, ?)",
|
||||
ahead, strings.Repeat("f", 64))
|
||||
return err
|
||||
})
|
||||
|
||||
t.Chdir(repoDir)
|
||||
t.Setenv("BEADS_DIR", beadsDir)
|
||||
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
|
||||
t.Setenv("BEADS_DOLT_AUTO_START", "0")
|
||||
t.Setenv("BEADS_SKIP_IDENTITY_CHECK", "")
|
||||
// The skew check itself has an escape hatch; an ambient one would turn the
|
||||
// refusal under test into a warning and pass vacuously.
|
||||
t.Setenv("BD_IGNORE_SCHEMA_SKEW", "")
|
||||
|
||||
config.ResetForTesting()
|
||||
t.Cleanup(config.ResetForTesting)
|
||||
savePersistentPreRunState(t)
|
||||
|
||||
oldStore := store
|
||||
// Zero it: the closing assertion is that the gate refused before opening
|
||||
// the real store, which a leftover global would satisfy vacuously.
|
||||
store = nil
|
||||
t.Cleanup(func() { store = oldStore })
|
||||
|
||||
oldJSON := jsonOutput
|
||||
jsonOutput = false
|
||||
t.Cleanup(func() { jsonOutput = oldJSON })
|
||||
|
||||
if rootCmd.PersistentPreRunE == nil {
|
||||
t.Fatal("rootCmd.PersistentPreRunE must be set")
|
||||
}
|
||||
|
||||
probe := &cobra.Command{
|
||||
Use: "identity-gate-skew-probe",
|
||||
RunE: func(*cobra.Command, []string) error { return nil },
|
||||
}
|
||||
rootCmd.AddCommand(probe)
|
||||
t.Cleanup(func() { rootCmd.RemoveCommand(probe) })
|
||||
|
||||
var preRunErr error
|
||||
out := captureStderr(t, func() { preRunErr = rootCmd.PersistentPreRunE(probe, nil) })
|
||||
|
||||
if preRunErr == nil {
|
||||
t.Fatalf("PersistentPreRunE succeeded against a workspace %d migrations ahead of this binary; the gate must refuse\nstderr:\n%s", ahead-schema.LatestVersion(), out)
|
||||
}
|
||||
|
||||
// The actionable block SchemaSkewError.UserMessage() owns. Losing this to a
|
||||
// generic wrapper was the regression.
|
||||
if !strings.Contains(out, "Your bd binary is stale") {
|
||||
t.Errorf("stderr lacks the skew rebuild guidance, so the preview's typed error was not rendered as the real-open arm renders it:\n%s", out)
|
||||
}
|
||||
// Proves the drift came from the real workspace cursor, not a stray
|
||||
// SchemaSkewError manufactured somewhere else on the path.
|
||||
wantVersions := fmt.Sprintf("database is at v%d, binary knows up to v%d", ahead, schema.LatestVersion())
|
||||
if !strings.Contains(out, wantVersions) {
|
||||
t.Errorf("stderr = %q, want it to report %q", out, wantVersions)
|
||||
}
|
||||
if strings.Contains(out, "could not verify workspace identity") {
|
||||
t.Errorf("schema skew from the preview open was rendered as the gate's generic identity wrapper:\n%s", out)
|
||||
}
|
||||
if strings.Contains(out, "BEADS_SKIP_IDENTITY_CHECK") {
|
||||
t.Errorf("refusal advertised BEADS_SKIP_IDENTITY_CHECK, which cannot help here: skipping the gate leaves the real open failing on the identical skew:\n%s", out)
|
||||
}
|
||||
if store != nil {
|
||||
t.Error("PersistentPreRunE must not have opened the real store after refusing on a forward-drifted preview")
|
||||
}
|
||||
}
|
||||
128
cmd/bd/identity_preview_gate_test.go
Normal file
128
cmd/bd/identity_preview_gate_test.go
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
)
|
||||
|
||||
// TestIsBootstrapPreviewErr pins the classifier that decides whether the
|
||||
// identity check's preview-open failure is a legitimate first run (skip
|
||||
// silently) or something else (refuse). It must recognize the exact wrapping
|
||||
// shape embeddeddolt produces for "no database on disk yet" and nothing else,
|
||||
// including an error that merely happens to also be wrapped.
|
||||
func TestIsBootstrapPreviewErr(t *testing.T) {
|
||||
wrappedNotExist := fmt.Errorf("embeddeddolt: no embedded database at %s: %w", "/tmp/x/embeddeddolt", os.ErrNotExist)
|
||||
wrappedOther := fmt.Errorf("dial tcp 127.0.0.1:3306: %w", errors.New("connect: connection refused"))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{"nil error", nil, false},
|
||||
{"direct os.ErrNotExist", os.ErrNotExist, true},
|
||||
{"wrapped os.ErrNotExist (embedded store shape)", wrappedNotExist, true},
|
||||
{"generic non-ENOENT error", errors.New("connection refused"), false},
|
||||
{"wrapped non-ENOENT error", wrappedOther, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isBootstrapPreviewErr(tt.err); got != tt.want {
|
||||
t.Errorf("isBootstrapPreviewErr(%v) = %v, want %v", tt.err, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPersistentPreRunRefusesWhenIdentityPreviewFailsForNonBootstrapReason is
|
||||
// the MAJOR-criterion regression test for be-0gfcs round 2 (be-3bt2e): a
|
||||
// preview-open failure that is NOT the legitimate first-run case must refuse
|
||||
// before the real, mutating store open runs -- not silently no-op the way it
|
||||
// did when the guard's own peek could fail for the same reason it exists to
|
||||
// catch (an unreachable or misconfigured workspace), letting a pending schema
|
||||
// migration auto-apply unexamined.
|
||||
//
|
||||
// Dolt server-mode with no server listening is the hermetic trigger: it is
|
||||
// the same setup TestPersistentPreRunHonorsSkipStoreAnnotation's control case
|
||||
// already relies on to prove PersistentPreRunE reaches, and fails, a real
|
||||
// store open in this test environment -- and it fails for a connection
|
||||
// reason, never an os.ErrNotExist, so it is unambiguously NOT bootstrap.
|
||||
func TestPersistentPreRunRefusesWhenIdentityPreviewFailsForNonBootstrapReason(t *testing.T) {
|
||||
repoDir := t.TempDir()
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
writeTestConfigYAML(t, beadsDir, "")
|
||||
writeMetadataConfig(t, beadsDir, configfile.DoltModeServer, "identity_gate_test")
|
||||
|
||||
t.Chdir(repoDir)
|
||||
t.Setenv("BEADS_DIR", beadsDir)
|
||||
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
|
||||
// If the real store open is ever reached without refusing first (the bug),
|
||||
// fail fast: never auto-start a server from a test.
|
||||
t.Setenv("BEADS_DOLT_AUTO_START", "0")
|
||||
t.Setenv("BEADS_SKIP_IDENTITY_CHECK", "")
|
||||
|
||||
config.ResetForTesting()
|
||||
t.Cleanup(config.ResetForTesting)
|
||||
savePersistentPreRunState(t)
|
||||
|
||||
oldStore := store
|
||||
// Zero it too: the assertion at the end of this test is that the gate did
|
||||
// NOT open the real store, which a leftover non-nil global from an earlier
|
||||
// test would satisfy vacuously (or fail spuriously).
|
||||
store = nil
|
||||
t.Cleanup(func() { store = oldStore })
|
||||
|
||||
if rootCmd.PersistentPreRunE == nil {
|
||||
t.Fatal("rootCmd.PersistentPreRunE must be set")
|
||||
}
|
||||
|
||||
probe := &cobra.Command{
|
||||
Use: "identity-gate-refuse-probe",
|
||||
RunE: func(*cobra.Command, []string) error { return nil },
|
||||
}
|
||||
rootCmd.AddCommand(probe)
|
||||
t.Cleanup(func() { rootCmd.RemoveCommand(probe) })
|
||||
|
||||
oldStderr := os.Stderr
|
||||
r, w, pipeErr := os.Pipe()
|
||||
if pipeErr != nil {
|
||||
t.Fatalf("os.Pipe: %v", pipeErr)
|
||||
}
|
||||
os.Stderr = w
|
||||
|
||||
err := rootCmd.PersistentPreRunE(probe, nil)
|
||||
|
||||
w.Close()
|
||||
os.Stderr = oldStderr
|
||||
var captured bytes.Buffer
|
||||
io.Copy(&captured, r) //nolint:errcheck // best-effort drain of a test pipe
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected PersistentPreRunE to fail against an unreachable server-mode database; test-environment precondition broken")
|
||||
}
|
||||
|
||||
// HandleError's returned error carries only "exit code N" in its own
|
||||
// Error() string -- the real message goes to stderr (see HandleError in
|
||||
// errors.go) -- so the marker must be asserted against captured stderr,
|
||||
// not err.Error().
|
||||
const wantMarker = "could not verify workspace identity"
|
||||
if !strings.Contains(captured.String(), wantMarker) {
|
||||
t.Errorf("PersistentPreRunE stderr = %q, want it to contain %q -- a preview-open failure for a reason other than first-time bootstrap must refuse before the real, mutating store open runs (be-0gfcs: the guard cannot prevent what it is guarding against if it silently no-ops here)", captured.String(), wantMarker)
|
||||
}
|
||||
if store != nil {
|
||||
t.Error("PersistentPreRunE must not have opened the real store after refusing on an unverifiable identity preview")
|
||||
}
|
||||
}
|
||||
121
cmd/bd/identity_preview_refusal_test.go
Normal file
121
cmd/bd/identity_preview_refusal_test.go
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
)
|
||||
|
||||
// TestRefuseUnverifiablePreviewOpenRendersTypedErrors pins the regression the
|
||||
// identity gate introduced by refusing on its own generic wrapper.
|
||||
//
|
||||
// The preview open runs CheckForwardDrift, so a schema-ahead database — the
|
||||
// recurring stale-binary class — fails the PREVIEW now, not the real open. On
|
||||
// base that class surfaced from the real open and was rendered by
|
||||
// renderTypedOpenError with SchemaSkewError.UserMessage()'s actionable rebuild
|
||||
// block, and with a JSON body under --json. A bare HandleError on the gate's
|
||||
// refusal arm replaced both with an unstructured line, and appended a
|
||||
// BEADS_SKIP_IDENTITY_CHECK=1 hint that cannot help: skipping the gate just
|
||||
// makes the real open fail on the identical skew.
|
||||
func TestRefuseUnverifiablePreviewOpenRendersTypedErrors(t *testing.T) {
|
||||
skew := &schema.SchemaSkewError{DBVersion: 71, BinaryVersion: 68}
|
||||
|
||||
t.Run("schema skew keeps its own UX, not the generic wrapper", func(t *testing.T) {
|
||||
oldJSON := jsonOutput
|
||||
jsonOutput = false
|
||||
t.Cleanup(func() { jsonOutput = oldJSON })
|
||||
|
||||
var err error
|
||||
out := captureStderr(t, func() { err = refuseUnverifiablePreviewOpen(skew) })
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("refusal returned nil; the gate must still fail the command")
|
||||
}
|
||||
if strings.Contains(out, "could not verify workspace identity") {
|
||||
t.Errorf("schema skew was rendered as the generic identity wrapper:\n%s", out)
|
||||
}
|
||||
if strings.Contains(out, "BEADS_SKIP_IDENTITY_CHECK") {
|
||||
t.Errorf("refusal advertised BEADS_SKIP_IDENTITY_CHECK for a skew, where skipping the gate leaves the real open failing identically:\n%s", out)
|
||||
}
|
||||
// The skew renderer's own text, not this test's paraphrase of it.
|
||||
if !strings.Contains(out, skew.Error()) {
|
||||
t.Errorf("stderr = %q, want the SchemaSkewError message %q", out, skew.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("schema skew under --json emits a JSON body", func(t *testing.T) {
|
||||
oldJSON := jsonOutput
|
||||
jsonOutput = true
|
||||
t.Cleanup(func() { jsonOutput = oldJSON })
|
||||
|
||||
out := captureStderr(t, func() { _ = refuseUnverifiablePreviewOpen(skew) })
|
||||
|
||||
var body map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(out), &body); err != nil {
|
||||
t.Fatalf("--json refusal did not emit a JSON body (%v); raw stderr:\n%s", err, out)
|
||||
}
|
||||
raw, ok := body["schema_skew"]
|
||||
if !ok {
|
||||
t.Fatalf("JSON body has no schema_skew object, so a machine caller cannot tell skew from any other failure: %v", body)
|
||||
}
|
||||
detail, ok := raw.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("schema_skew is %T, want an object", raw)
|
||||
}
|
||||
for key, want := range map[string]float64{
|
||||
"current_version": 71,
|
||||
"required_version": 68,
|
||||
"delta": 3,
|
||||
} {
|
||||
if got, _ := detail[key].(float64); got != want {
|
||||
t.Errorf("schema_skew[%q] = %v, want %v", key, detail[key], want)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a preview-specific error keeps the generic message and respects --json", func(t *testing.T) {
|
||||
// Not a typed open error: this is the class the generic arm is for, and
|
||||
// the only class where the override hint is honest.
|
||||
previewErr := fmt.Errorf("dial tcp 127.0.0.1:3306: %w", errors.New("connection refused"))
|
||||
|
||||
oldJSON := jsonOutput
|
||||
jsonOutput = false
|
||||
t.Cleanup(func() { jsonOutput = oldJSON })
|
||||
|
||||
plain := captureStderr(t, func() { _ = refuseUnverifiablePreviewOpen(previewErr) })
|
||||
if !strings.Contains(plain, "could not verify workspace identity") {
|
||||
t.Errorf("stderr = %q, want the generic identity refusal", plain)
|
||||
}
|
||||
if !strings.Contains(plain, "BEADS_SKIP_IDENTITY_CHECK") {
|
||||
t.Errorf("stderr = %q, want the override hint on the arm where it actually applies", plain)
|
||||
}
|
||||
|
||||
// The generic arm's JSON body goes to STDOUT (HandleErrorRespectJSON →
|
||||
// jsonStdoutError), unlike handleSchemaSkewJSON's, which goes to stderr.
|
||||
// That split is pre-existing; what matters for this finding is that a
|
||||
// --json caller receives a parseable body on one of them instead of the
|
||||
// bare stderr line the gate used to emit.
|
||||
jsonOutput = true
|
||||
// captureStdout fails the test on a returned error, and this refusal
|
||||
// returns a non-nil exitError by design, so record it separately.
|
||||
var refusal error
|
||||
structured := captureStdout(t, func() error {
|
||||
refusal = refuseUnverifiablePreviewOpen(previewErr)
|
||||
return nil
|
||||
})
|
||||
if refusal == nil {
|
||||
t.Error("refusal returned nil under --json; the command must still fail")
|
||||
}
|
||||
var body map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(structured), &body); err != nil {
|
||||
t.Fatalf("--json generic refusal emitted no JSON body (%v); a machine caller gets exit 1 with nothing to parse:\n%s", err, structured)
|
||||
}
|
||||
if _, ok := body["error"]; !ok {
|
||||
t.Errorf("JSON body has no error field: %v", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
146
cmd/bd/main.go
146
cmd/bd/main.go
|
|
@ -1850,6 +1850,63 @@ var rootCmd = &cobra.Command{
|
|||
|
||||
doltCfg.Path = doltPath
|
||||
|
||||
// Validate workspace identity for write commands (GH#2438, GH#2372)
|
||||
// BEFORE the real store opens below. Skip for read-only commands
|
||||
// since they can't corrupt data. Skip for --global: the global
|
||||
// database uses a sentinel project ID that won't match any
|
||||
// project's metadata.json.
|
||||
//
|
||||
// This has to run before the store opens, not after: opening it is
|
||||
// what lets a pending schema migration auto-apply (the smart gate,
|
||||
// #4516), and checking identity only after that open means a
|
||||
// mismatch is caught after the migration already landed as a real,
|
||||
// permanent commit — the refusal arrives too late to prevent it
|
||||
// (be-0gfcs). newPreviewStoreFromConfig gives a non-mutating,
|
||||
// behind-schema-tolerant peek at the same database: enough to read
|
||||
// _project_id without running (or needing) the migration this check
|
||||
// must complete ahead of.
|
||||
//
|
||||
// Dispatches on previewErr, not on idStore's own nilness: even the
|
||||
// success case can't trust idStore to signal failure on its own.
|
||||
// openNonMutatingStoreFromConfig's dolt-server-mode branch returns
|
||||
// dolt.NewFromConfigWithOptions's result straight through, and on a
|
||||
// failed connection that is a nil *dolt.DoltStore boxed into a
|
||||
// non-nil storage.DoltStorage interface — the classic Go typed-nil
|
||||
// trap, where `idStore != nil` reads true even though the store
|
||||
// behind it is not there. Calling Close() (or anything else) on
|
||||
// that reference panics (confirmed live:
|
||||
// TestPersistentPreRunHonorsSkipStoreAnnotation's control case, a
|
||||
// command with no skip-store annotation run against an absent
|
||||
// server-mode database). Checking previewErr first sidesteps the
|
||||
// trap entirely, matching the ordinary (value, err) contract every
|
||||
// other caller of this pair already trusts.
|
||||
//
|
||||
// A failed peek still has to be told apart from a legitimate first
|
||||
// run: isBootstrapPreviewErr recognizes "no local database yet" (a
|
||||
// wrapped os.ErrNotExist from the embedded store's own data-dir
|
||||
// check), and only that case is skipped silently — the bootstrap
|
||||
// tolerance this check has always had. Any other previewErr
|
||||
// (unreachable server-mode endpoint, unloadable config, a
|
||||
// registered backend refusing the read-only open, ...) used to be
|
||||
// swallowed the same way, which let a preview failure wave the
|
||||
// real, mutating open through unexamined — the one thing this check
|
||||
// exists to prevent (be-3bt2e). Those cases now refuse instead.
|
||||
if !useReadOnly && !globalFlag && os.Getenv("BEADS_SKIP_IDENTITY_CHECK") != "1" {
|
||||
idStore, previewErr := newPreviewStoreFromConfig(rootCtx, beadsDir)
|
||||
switch {
|
||||
case previewErr == nil:
|
||||
checkErr := validateWorkspaceIdentity(rootCtx, idStore, beadsDir)
|
||||
_ = idStore.Close()
|
||||
if checkErr != nil {
|
||||
return checkErr
|
||||
}
|
||||
case isBootstrapPreviewErr(previewErr):
|
||||
debug.Logf("workspace identity check: skipping, no local database yet (%v)\n", previewErr)
|
||||
default:
|
||||
return refuseUnverifiablePreviewOpen(previewErr)
|
||||
}
|
||||
}
|
||||
|
||||
// WARNING: DO NOT remove, delete, or modify files inside Dolt's .dolt/
|
||||
// directory — including noms/LOCK files. These are Dolt-internal files.
|
||||
// Removing them WILL cause unrecoverable data corruption and data loss.
|
||||
|
|
@ -1897,15 +1954,10 @@ var rootCmd = &cobra.Command{
|
|||
maybeAutoImportJSONL(rootCtx, store, beadsDir)
|
||||
}
|
||||
|
||||
// Validate workspace identity for write commands (GH#2438, GH#2372)
|
||||
// Skip for read-only commands since they can't corrupt data.
|
||||
// Skip for --global: the global database uses a sentinel project ID
|
||||
// that won't match any project's metadata.json.
|
||||
if !useReadOnly && !globalFlag && os.Getenv("BEADS_SKIP_IDENTITY_CHECK") != "1" {
|
||||
if err := validateWorkspaceIdentity(rootCtx, beadsDir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Workspace identity is validated earlier now, before the store below
|
||||
// was allowed to open and auto-apply a pending schema migration as a
|
||||
// side effect (be-0gfcs) — see the check right before
|
||||
// newRegisteredBackendStore/newDoltStore.
|
||||
|
||||
// Initialize hook runner using the .beads directory resolved above via
|
||||
// resolveCommandBeadsDir. Do not use filepath.Dir(dbPath): for a
|
||||
|
|
@ -2336,16 +2388,80 @@ func flushBatchCommitOnShutdown() {
|
|||
fmt.Fprintf(os.Stderr, "\nFlushed pending batch commit on shutdown\n")
|
||||
}
|
||||
|
||||
// isBootstrapPreviewErr reports whether err is the identity check's preview
|
||||
// open failing because no local database exists yet — a legitimate first
|
||||
// run, not a workspace problem. It must stay narrow: any other previewErr
|
||||
// (unreachable server, bad config, ...) has to refuse rather than silently
|
||||
// wave the real, mutating open through (be-3bt2e).
|
||||
func isBootstrapPreviewErr(err error) bool {
|
||||
return errors.Is(err, os.ErrNotExist)
|
||||
}
|
||||
|
||||
// refuseUnverifiablePreviewOpen renders the identity gate's refusal when the
|
||||
// preview open failed for a reason other than first-run bootstrap.
|
||||
//
|
||||
// The preview IS a real store open, so it can hit the same typed open errors the
|
||||
// real one does, and those must be rendered exactly as the real-open arm renders
|
||||
// them. Moving the gate earlier is not license to downgrade
|
||||
// SchemaSkewError.UserMessage()'s actionable rebuild block into a generic
|
||||
// wrapper, nor to drop the JSON body that every `--json` consumer depends on.
|
||||
//
|
||||
// Only ONE class actually arrives here typed today — schema skew: the preview
|
||||
// runs CheckForwardDrift (embeddeddolt openReadOnly, dolt store open), which is
|
||||
// how the recurring stale-binary class #4135/#4137 surfaces at the preview
|
||||
// first. The other two calls below are defensive-for-symmetry with the real-open
|
||||
// arm, and cannot fire from a preview as the code stands:
|
||||
// - handleFreshCloneError matches a post-migration failure string that a
|
||||
// non-mutating preview never produces. Note for whoever makes it reachable:
|
||||
// it ignores jsonOutput (main_errors.go), so it would break the `--json`
|
||||
// guarantee this arm otherwise keeps.
|
||||
// - CheckRemoteMigrateGate* runs only from mutating opens, never from
|
||||
// openReadOnly, so RemoteMigrateGateError cannot originate in the preview.
|
||||
//
|
||||
// projectIdentityMismatchError is deliberately NOT in that list: it is a plain
|
||||
// fmt.Errorf block with no typed wrapper, so it falls to the generic arm below
|
||||
// and picks up its prefix. That matches base, where the mismatch block reached
|
||||
// the operator inside the real arm's "failed to open database: %v" wrapper.
|
||||
//
|
||||
// Extracted from the gate's default arm so both halves are directly testable
|
||||
// without standing up a forward-drifted workspace; the wire itself is pinned on
|
||||
// the embedded tier by
|
||||
// TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace.
|
||||
func refuseUnverifiablePreviewOpen(previewErr error) error {
|
||||
if handleFreshCloneError(previewErr) {
|
||||
return SilentExit()
|
||||
}
|
||||
if renderTypedOpenError(previewErr) {
|
||||
return SilentExit()
|
||||
}
|
||||
// What remains is preview-specific: an unreachable endpoint, unloadable
|
||||
// config, a registered backend refusing the read-only open. Respect --json
|
||||
// so a machine caller still receives a structured error. The override hint
|
||||
// lives only on this arm, and states what it actually does: on the typed
|
||||
// arms above it cannot help, because the real open fails on the identical
|
||||
// condition.
|
||||
return HandleErrorRespectJSON(
|
||||
"could not verify workspace identity before opening the database: %v "+
|
||||
"(BEADS_SKIP_IDENTITY_CHECK=1 skips this pre-open check; it does not fix an error the real open would hit too)",
|
||||
previewErr)
|
||||
}
|
||||
|
||||
// validateWorkspaceIdentity checks that the project identity from metadata.json
|
||||
// matches the database's stored project_id. A mismatch indicates configuration
|
||||
// drift — the CLI may be pointing at the wrong database (GH#2438, GH#2372).
|
||||
// matches s's stored project_id. A mismatch indicates configuration drift —
|
||||
// the CLI may be pointing at the wrong database (GH#2438, GH#2372).
|
||||
//
|
||||
// This check only runs for write commands because:
|
||||
// 1. Read commands are safe even against wrong databases (no data mutation)
|
||||
// 2. The check requires an open store connection
|
||||
// 2. The check requires a store connection
|
||||
// 3. New databases won't have _project_id yet (bootstrap case)
|
||||
func validateWorkspaceIdentity(ctx context.Context, beadsDir string) error {
|
||||
if store == nil {
|
||||
//
|
||||
// s is passed explicitly rather than read off the package-level store: the
|
||||
// caller runs this against a throwaway, non-mutating store opened BEFORE the
|
||||
// real command store, specifically so a mismatch is caught before that real
|
||||
// open lets a pending schema migration auto-apply (be-0gfcs) — see the call
|
||||
// site in the root command's PersistentPreRunE.
|
||||
func validateWorkspaceIdentity(ctx context.Context, s storage.DoltStorage, beadsDir string) error {
|
||||
if s == nil {
|
||||
return nil // No store connection, nothing to validate
|
||||
}
|
||||
|
||||
|
|
@ -2360,7 +2476,7 @@ func validateWorkspaceIdentity(ctx context.Context, beadsDir string) error {
|
|||
}
|
||||
|
||||
// Get project_id from database
|
||||
dbProjectID, err := store.GetMetadata(ctx, "_project_id")
|
||||
dbProjectID, err := s.GetMetadata(ctx, "_project_id")
|
||||
if err != nil || dbProjectID == "" {
|
||||
return nil // No project_id in DB (new or pre-identity database)
|
||||
}
|
||||
|
|
|
|||
90
cmd/bd/migrate_schema_identity_order_test.go
Normal file
90
cmd/bd/migrate_schema_identity_order_test.go
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
)
|
||||
|
||||
// TestMigrateSchema_IdentityMismatchRefusesBeforeApplying reproduces be-0gfcs:
|
||||
// bd migrate schema's workspace-identity guard (validateWorkspaceIdentity)
|
||||
// runs AFTER the shared pre-run has already opened the store and let the
|
||||
// smart gate auto-apply a pending schema migration as a side effect. The
|
||||
// refusal itself is correct -- exit 1, the mismatch message -- but it
|
||||
// arrives after a real, permanent Dolt commit has already advanced
|
||||
// schema_migrations. The fix must make the identity check run before (or
|
||||
// otherwise gate) that auto-apply, so a refused migrate leaves the schema
|
||||
// cursor untouched.
|
||||
func TestMigrateSchema_IdentityMismatchRefusesBeforeApplying(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "idm")
|
||||
|
||||
latest := schema.LatestVersion()
|
||||
behind := latest - 1
|
||||
|
||||
// Put the workspace one migration behind -- so opening the store has a
|
||||
// pending migration for the smart gate to auto-apply -- and give the
|
||||
// database a _project_id that no longer matches this workspace's
|
||||
// config.yaml. Both conditions together are what the real incident
|
||||
// needs: a decoy/mismatched database that is also behind on schema.
|
||||
withEmbeddedMigrateSQL(t, beadsDir, "idm", func(db *sql.DB) error {
|
||||
if _, err := db.ExecContext(t.Context(),
|
||||
"DELETE FROM schema_migrations WHERE version = ?", latest); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := db.ExecContext(t.Context(),
|
||||
"UPDATE metadata SET value = ? WHERE `key` = ?", "corrupted-project-id-be-0gfcs", "_project_id")
|
||||
return err
|
||||
})
|
||||
|
||||
cursor := func() int {
|
||||
t.Helper()
|
||||
var v int
|
||||
withEmbeddedMigrateSQL(t, beadsDir, "idm", func(db *sql.DB) error {
|
||||
return db.QueryRowContext(t.Context(),
|
||||
"SELECT COALESCE(MAX(version), 0) FROM schema_migrations").Scan(&v)
|
||||
})
|
||||
return v
|
||||
}
|
||||
if got := cursor(); got != behind {
|
||||
t.Fatalf("precondition failed: schema cursor = %d, want %d", got, behind)
|
||||
}
|
||||
|
||||
cmd := exec.Command(bd, "migrate", "schema")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = bdEnv(dir)
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
|
||||
code := 0
|
||||
if err != nil {
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(err, &exitErr) {
|
||||
t.Fatalf("running bd migrate schema: %v", err)
|
||||
}
|
||||
code = exitErr.ExitCode()
|
||||
}
|
||||
|
||||
if code != 1 {
|
||||
t.Errorf("bd migrate schema exit = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout.String(), stderr.String())
|
||||
}
|
||||
if !strings.Contains(stderr.String(), "workspace identity mismatch detected") {
|
||||
t.Errorf("bd migrate schema stderr missing identity mismatch message:\n%s", stderr.String())
|
||||
}
|
||||
|
||||
if got := cursor(); got != behind {
|
||||
t.Fatalf("bd migrate schema refused the workspace but still advanced schema_migrations from %d to %d -- "+
|
||||
"the smart-gate auto-migration on store-open ran before the identity check (be-0gfcs)", behind, got)
|
||||
}
|
||||
}
|
||||
|
|
@ -5,21 +5,17 @@ import (
|
|||
)
|
||||
|
||||
func TestValidateWorkspaceIdentity_NilStore(t *testing.T) {
|
||||
// When store is nil, validateWorkspaceIdentity should be a no-op
|
||||
// (no panic, no os.Exit)
|
||||
origStore := store
|
||||
store = nil
|
||||
defer func() { store = nil; store = origStore }()
|
||||
|
||||
validateWorkspaceIdentity(nil, "/nonexistent")
|
||||
// When the passed-in store is nil, validateWorkspaceIdentity should be a
|
||||
// no-op (no panic, no os.Exit).
|
||||
validateWorkspaceIdentity(nil, nil, "/nonexistent")
|
||||
// If we got here, no os.Exit was called — pass
|
||||
}
|
||||
|
||||
func TestValidateWorkspaceIdentity_NonexistentDir(t *testing.T) {
|
||||
// When beadsDir doesn't exist, configfile.Load fails and we skip validation
|
||||
origStore := store
|
||||
store = nil
|
||||
defer func() { store = origStore }()
|
||||
|
||||
validateWorkspaceIdentity(nil, "/nonexistent/path/that/does/not/exist")
|
||||
// When beadsDir doesn't exist, configfile.Load fails and we skip
|
||||
// validation. Store is nil here too (same as the pre-refactor version of
|
||||
// this test, which set the package-level store to nil): both cases
|
||||
// return before configfile.Load would even run, so this and
|
||||
// TestValidateWorkspaceIdentity_NilStore cover the same early return.
|
||||
validateWorkspaceIdentity(nil, nil, "/nonexistent/path/that/does/not/exist")
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue