From cb0b35a92fcdcf05f4c7affb80eaea33c12167ca Mon Sep 17 00:00:00 2001 From: davevan2 <51385306+davevan2@users.noreply.github.com> Date: Sat, 1 Aug 2026 18:17:09 -0500 Subject: [PATCH] fix: keep preview commands from migrating stores (#4985) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: keep preview commands from migrating stores (rig-2ng3) Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of davevan2 * fix(uow): route proxied-server previews through the preview policy The proxied branch in root PersistentPreRunE short-circuited to newProxiedServerUOWProvider + reconcileVersionProxiedServer with no preview gating, so `--dry-run`/`--inspect` still ran CREATE DATABASE and schema.MigrateUpWithLock (via openAndInitSchema) and still wrote version metadata — during root pre-run, before the flag had any effect. That is the exact side effect this change exists to prevent, on the mode where it is least visible. Adds a variadic uow.ProviderOption seam (uow.WithPreview) so the existing constructor call sites are untouched, threads it from main.go through uow_factory.go, and makes initSchema attach to the existing database and stop when preview is set. reconcileVersionProxiedServer is skipped for previews for the same reason. Agent-Signature: claude-opus-5-medium on behalf of matt wilkie * fix(create): open the cross-repo dry-run parent target read-only openDryRunTargetStore documented read-only intent but passed the writable newDoltStoreFromConfig on both the cached-remote and local-target paths, so `create --dry-run --parent X --repo ` ran schema init against the other repo (and the factory path can rename a legacy database and rewrite its metadata.json on the way). The command opening its own store read-only says nothing about that second store. Adds newPreviewStoreFromConfig — newReadOnlyStoreFromConfig with the behind- cursor refusal relaxed, matching embeddeddolt.OpenForPreviewCommand — and uses it on both paths. A parent lookup in a repo that has not been migrated yet should not refuse, and must certainly not migrate. The new regression test puts the migration-cursor tripwire in the TARGET repo; the pre-existing single-repo test could not see this because it used neither --parent nor --repo. Verified failing before the fix (schema version 61 -> 62, HEAD moved). Agent-Signature: claude-opus-5-medium on behalf of matt wilkie * fix(version): do not let a preview consume the one-shot upgrade marker trackBdVersion() rewrote .beads/.local_version immediately on a version change, before the preview check. A preview run first after an upgrade correctly skipped autoMigrateOnVersionBump — but had already burned the marker, so the next ordinary command saw a matching version and never ran the version-bump reconciliation at all (including the pre-0.56 recovery path). Whichever command happened to run first silently decided whether the upgrade was ever finished. trackBdVersionPreview() does the same detection without the write; previewMode moves above the tracking call since that is now the first step it changes. Not writing is safe in the other direction: the marker is advisory and the next non-preview command writes it. Two-invocation regression test (preview, then `bd upgrade status --json`); verified failing before the fix (.local_version = 1.1.0, want 0.9.0). Agent-Signature: claude-opus-5-medium on behalf of matt wilkie * fix(main): tolerate a read-only refusal in the PostRun tip auto-commit The tip-metadata auto-commit is deliberately not gated by the read-only classification, and read-only commands tolerate it because OpenForReadOnlyCommand is intentionally writable for incidental writes. The write-refusing preview store breaks that assumption: with dolt.auto-commit=on and an eligible tip (human, non---json), SetLocalMetadata refuses and the command exits non-zero AFTER a successful dry-run. Treat that refusal as non-fatal and skip the tip commit, consistent with recordTipShown own "non-critical metadata, ok to fail silently" contract. embeddeddolt.errReadOnly becomes exported ErrReadOnly (declared without a cgo build tag) so the CLI can tell a by-construction refusal apart from a real failure. Agent-Signature: claude-opus-5-medium on behalf of matt wilkie * cmd/bd: extract previewProviderOptions and unit test it Blocker 1's CLI wiring (providerOpts built with uow.WithPreview() only when previewMode is set) had no test that would fail if a refactor dropped or inverted it. Extract the branch into previewProviderOptions(preview bool) []uow.ProviderOption and add a unit test pinning the observable shape: preview=true yields one option, preview=false yields none. The reconcileVersionProxiedServer guard is unchanged. Agent-Signature: claude-sonnet-5-medium on behalf of matt wilkie --------- Co-authored-by: matt wilkie --- cmd/bd/create.go | 14 +- cmd/bd/create_embedded_test.go | 273 ++++++++++++++++++ cmd/bd/directory_flag_test.go | 31 ++ cmd/bd/main.go | 104 +++++-- cmd/bd/store_factory.go | 25 ++ cmd/bd/store_factory_nocgo.go | 7 + cmd/bd/uow_factory.go | 42 ++- cmd/bd/uow_factory_test.go | 23 ++ cmd/bd/version_tracking.go | 24 +- internal/storage/dolt/store.go | 1 + .../embeddeddolt/preview_readonly_test.go | 57 ++++ internal/storage/embeddeddolt/readonly.go | 17 ++ internal/storage/embeddeddolt/store.go | 34 ++- internal/storage/embeddeddolt/store_stub.go | 5 + .../storage/embeddeddolt/version_control.go | 4 +- internal/storage/uow/dolt_sql_provider.go | 55 +++- internal/storage/uow/doltserver_provider.go | 3 +- .../uow/external_doltserver_provider.go | 3 +- internal/storage/uow/preview_provider_test.go | 73 +++++ 19 files changed, 745 insertions(+), 50 deletions(-) create mode 100644 internal/storage/embeddeddolt/preview_readonly_test.go create mode 100644 internal/storage/embeddeddolt/readonly.go create mode 100644 internal/storage/uow/preview_provider_test.go diff --git a/cmd/bd/create.go b/cmd/bd/create.go index 261b3a489..8a1b9932c 100644 --- a/cmd/bd/create.go +++ b/cmd/bd/create.go @@ -898,6 +898,16 @@ func formatTimeForRPC(t *time.Time) string { return t.Format(time.RFC3339) } +// openDryRunTargetStore opens the store a `create --dry-run --repo ` +// resolves --parent against. It is read-only on BOTH paths and must stay that +// way: newDoltStoreFromConfig runs schema initialization on whatever it opens +// and can rename a legacy hyphenated database and rewrite the target's +// metadata.json on the way (GH#3231), so using it here would have a dry-run +// mutate a repository the user only named as a lookup target — the same +// migrate-at-open trap this preview policy exists to close, one repo over. +// newPreviewStoreFromConfig is the non-mutating factory for a foreign +// project (bd-6dnrw.32), relaxed for previews exactly as the root pre-run +// relaxes the command's own store. func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltStorage, error) { if remotecache.IsRemoteURL(repoPath) { cache, err := remotecache.DefaultCache() @@ -906,7 +916,7 @@ func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltSt } // The dry-run parent lookup only reads from this cached remote store. // Do not add writes here; dry-runs must not mutate cached remotes. - store, err := cache.OpenStore(ctx, repoPath, newDoltStoreFromConfig) + store, err := cache.OpenStore(ctx, repoPath, newPreviewStoreFromConfig) if err != nil { return nil, fmt.Errorf("dry-run parent lookup requires an existing cached remote store for %s: %w", repoPath, err) } @@ -923,7 +933,7 @@ func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltSt return nil, fmt.Errorf("failed to inspect target repo %s: %w", targetPath, err) } - store, err := newDoltStoreFromConfig(ctx, beadsDir) + store, err := newPreviewStoreFromConfig(ctx, beadsDir) if err != nil { return nil, fmt.Errorf("failed to open target store for dry-run: %w", err) } diff --git a/cmd/bd/create_embedded_test.go b/cmd/bd/create_embedded_test.go index 9bc984aab..aca57759e 100644 --- a/cmd/bd/create_embedded_test.go +++ b/cmd/bd/create_embedded_test.go @@ -14,6 +14,7 @@ import ( "time" "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/storage/schema" "github.com/steveyegge/beads/internal/types" ) @@ -1117,6 +1118,278 @@ A new feature }) } +// embeddedStoreSnapshot is the "did anything write to this database?" +// tripwire the preview regression tests compare across a command run. +type embeddedStoreSnapshot struct { + schemaVersion int + head string + issueCount int +} + +func readEmbeddedStoreSnapshot(t *testing.T, beadsDir, database string) embeddedStoreSnapshot { + t.Helper() + db, cleanup, err := embeddeddolt.OpenSQL( + t.Context(), + filepath.Join(beadsDir, "embeddeddolt"), + database, + "main", + ) + if err != nil { + t.Fatalf("OpenSQL: %v", err) + } + defer func() { + if err := cleanup(); err != nil { + t.Errorf("cleanup OpenSQL: %v", err) + } + }() + + var got embeddedStoreSnapshot + if err := db.QueryRowContext(t.Context(), + "SELECT COALESCE(MAX(version), 0) FROM schema_migrations").Scan(&got.schemaVersion); err != nil { + t.Fatalf("read schema version: %v", err) + } + if err := db.QueryRowContext(t.Context(), "SELECT HASHOF('HEAD')").Scan(&got.head); err != nil { + t.Fatalf("read HEAD: %v", err) + } + if err := db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM issues").Scan(&got.issueCount); err != nil { + t.Fatalf("read issue count: %v", err) + } + return got +} + +// regressEmbeddedSchemaCursor rolls the recorded migration cursor back one +// version WITHOUT touching the physical schema. The latest migration is +// idempotent, so a writable open reapplies it, restores the cursor, and +// commits a new HEAD — which is exactly what makes the cursor a usable +// tripwire. Keeping the physical schema intact lets the preview's own reads +// still work against the older recorded version. +func regressEmbeddedSchemaCursor(t *testing.T, beadsDir, database string) { + t.Helper() + db, cleanup, err := embeddeddolt.OpenSQL( + t.Context(), + filepath.Join(beadsDir, "embeddeddolt"), + database, + "main", + ) + if err != nil { + t.Fatalf("OpenSQL for regression fixture: %v", err) + } + if _, err := db.ExecContext(t.Context(), + "DELETE FROM schema_migrations WHERE version = ?", schema.LatestVersion()); err != nil { + _ = cleanup() + t.Fatalf("regress schema cursor: %v", err) + } + if _, err := db.ExecContext(t.Context(), + "CALL DOLT_COMMIT('-am', 'test: regress schema before dry-run')"); err != nil { + _ = cleanup() + t.Fatalf("commit regressed schema cursor: %v", err) + } + if err := cleanup(); err != nil { + t.Fatalf("cleanup regression fixture: %v", err) + } +} + +func TestEmbeddedCreateDryRunDoesNotMigrate(t *testing.T) { + bd := buildEmbeddedBD(t) + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dnm") + bdCreate(t, bd, dir, "Existing issue") + + readSnapshot := func() embeddedStoreSnapshot { + return readEmbeddedStoreSnapshot(t, beadsDir, "dnm") + } + + regressEmbeddedSchemaCursor(t, beadsDir, "dnm") + + // Force the version-bump path that previously opened a second writable + // store and migrated before create.RunE reached --dry-run handling. + if err := os.WriteFile(filepath.Join(beadsDir, localVersionFile), []byte("0.9.0\n"), 0o600); err != nil { + t.Fatalf("write old local version: %v", err) + } + + before := readSnapshot() + if before.schemaVersion != schema.LatestVersion()-1 { + t.Fatalf("fixture schema version = %d, want %d", before.schemaVersion, schema.LatestVersion()-1) + } + + cmd := exec.Command(bd, "create", "--dry-run", "Preview only", "--json") + cmd.Dir = dir + cmd.Env = bdEnv(dir) + stdout, stderr, err := runCommandBuffers(t, cmd) + if err != nil { + t.Fatalf("bd create --dry-run failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String()) + } + + after := readSnapshot() + if after.schemaVersion != before.schemaVersion { + t.Errorf("schema version changed during dry-run: before=%d after=%d", before.schemaVersion, after.schemaVersion) + } + if after.head != before.head { + t.Errorf("Dolt HEAD changed during dry-run: before=%s after=%s", before.head, after.head) + } + if after.issueCount != before.issueCount { + t.Errorf("issue count changed during dry-run: before=%d after=%d", before.issueCount, after.issueCount) + } +} + +// TestEmbeddedCreateDryRunCrossRepoDoesNotMigrateTarget covers the second +// store a dry-run can reach: `create --dry-run --parent X --repo ` +// resolves the parent against the OTHER repo, and openDryRunTargetStore used +// to open it with the writable factory. The command's own store being opened +// read-only says nothing about that one — the mutation lands in a repository +// the user only named as a lookup target. +func TestEmbeddedCreateDryRunCrossRepoDoesNotMigrateTarget(t *testing.T) { + bd := buildEmbeddedBD(t) + targetDir, targetBeadsDir, _ := bdInit(t, bd, "--prefix", "xtgt") + parent := bdCreate(t, bd, targetDir, "Parent in the target repo") + if parent.ID == "" { + t.Fatal("parent issue has no ID") + } + + callerDir, callerBeadsDir, _ := bdInit(t, bd, "--prefix", "xsrc") + + // The tripwire goes in the TARGET repo: only a writable open of that repo + // restores its cursor and commits. + regressEmbeddedSchemaCursor(t, targetBeadsDir, "xtgt") + + // Force the version-bump path in the caller repo too, so this exercises + // the same post-upgrade window as the single-repo test. + if err := os.WriteFile(filepath.Join(callerBeadsDir, localVersionFile), []byte("0.9.0\n"), 0o600); err != nil { + t.Fatalf("write old local version: %v", err) + } + + before := readEmbeddedStoreSnapshot(t, targetBeadsDir, "xtgt") + if before.schemaVersion != schema.LatestVersion()-1 { + t.Fatalf("fixture schema version = %d, want %d", before.schemaVersion, schema.LatestVersion()-1) + } + + cmd := exec.Command(bd, "create", "--dry-run", + "--parent", parent.ID, "--repo", targetDir, "Preview only", "--json") + cmd.Dir = callerDir + cmd.Env = bdEnv(callerDir) + stdout, stderr, err := runCommandBuffers(t, cmd) + if err != nil { + t.Fatalf("bd create --dry-run --parent --repo failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String()) + } + + after := readEmbeddedStoreSnapshot(t, targetBeadsDir, "xtgt") + if after.schemaVersion != before.schemaVersion { + t.Errorf("target repo schema version changed during cross-repo dry-run: before=%d after=%d", before.schemaVersion, after.schemaVersion) + } + if after.head != before.head { + t.Errorf("target repo Dolt HEAD changed during cross-repo dry-run: before=%s after=%s", before.head, after.head) + } + if after.issueCount != before.issueCount { + t.Errorf("target repo issue count changed during cross-repo dry-run: before=%d after=%d", before.issueCount, after.issueCount) + } +} + +// TestEmbeddedPreviewDoesNotConsumeVersionMarker is the two-invocation +// regression for the one-shot upgrade signal: a preview run first after an +// upgrade correctly skips the version-bump reconciliation, so it must also +// leave .beads/.local_version alone. Burning the marker there would mean the +// next ordinary command sees a matching version and never reconciles — +// whichever command happened to run first would silently decide whether the +// upgrade was finished. +func TestEmbeddedPreviewDoesNotConsumeVersionMarker(t *testing.T) { + bd := buildEmbeddedBD(t) + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "pvm") + bdCreate(t, bd, dir, "Existing issue") + + localVersionPath := filepath.Join(beadsDir, localVersionFile) + if err := os.WriteFile(localVersionPath, []byte("0.9.0\n"), 0o600); err != nil { + t.Fatalf("write old local version: %v", err) + } + + // Invocation 1: preview. + preview := exec.Command(bd, "create", "--dry-run", "Preview only", "--json") + preview.Dir = dir + preview.Env = bdEnv(dir) + stdout, stderr, err := runCommandBuffers(t, preview) + if err != nil { + t.Fatalf("bd create --dry-run failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String()) + } + + raw, err := os.ReadFile(localVersionPath) + if err != nil { + t.Fatalf("read local version after preview: %v", err) + } + if got := strings.TrimSpace(string(raw)); got != "0.9.0" { + t.Fatalf("preview consumed the version marker: .local_version = %q, want %q", got, "0.9.0") + } + + // Invocation 2: an ordinary command, which must still see the upgrade. + status := exec.Command(bd, "upgrade", "status", "--json") + status.Dir = dir + status.Env = bdEnv(dir) + stdout, stderr, err = runCommandBuffers(t, status) + if err != nil { + t.Fatalf("bd upgrade status failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String()) + } + var upgradeStatus struct { + Upgraded bool `json:"upgraded"` + PreviousVersion string `json:"previous_version"` + } + if err := json.Unmarshal(stdout.Bytes(), &upgradeStatus); err != nil { + t.Fatalf("parse upgrade status: %v\nstdout:\n%s", err, stdout.String()) + } + if !upgradeStatus.Upgraded || upgradeStatus.PreviousVersion != "0.9.0" { + t.Errorf("ordinary command after a preview no longer sees the upgrade: upgraded=%v previous=%q; stdout:\n%s", + upgradeStatus.Upgraded, upgradeStatus.PreviousVersion, stdout.String()) + } + + raw, err = os.ReadFile(localVersionPath) + if err != nil { + t.Fatalf("read local version after ordinary command: %v", err) + } + if got := strings.TrimSpace(string(raw)); got == "0.9.0" { + t.Errorf("ordinary command left .local_version at %q; the marker should have been updated", got) + } +} + +func TestEmbeddedChangeDirOverridesInheritedBeadsDir(t *testing.T) { + bd := buildEmbeddedBD(t) + callerDir, callerBeadsDir, _ := bdInit(t, bd, "--prefix", "caller") + targetDir, targetBeadsDir, _ := bdInit(t, bd, "--prefix", "target") + + cmd := exec.Command(bd, "-C", targetDir, "create", "Explicit target", "--json") + cmd.Dir = callerDir + cmd.Env = append(bdEnv(callerDir), "BEADS_DIR="+callerBeadsDir) + stdout, stderr, err := runCommandBuffers(t, cmd) + if err != nil { + t.Fatalf("bd -C target create failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String()) + } + + countIssues := func(beadsDir, database string) int { + t.Helper() + db, cleanup, err := embeddeddolt.OpenSQL( + t.Context(), + filepath.Join(beadsDir, "embeddeddolt"), + database, + "main", + ) + if err != nil { + t.Fatalf("OpenSQL %s: %v", database, err) + } + defer func() { + if err := cleanup(); err != nil { + t.Errorf("cleanup OpenSQL %s: %v", database, err) + } + }() + var count int + if err := db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM issues").Scan(&count); err != nil { + t.Fatalf("count issues in %s: %v", database, err) + } + return count + } + + if got := countIssues(callerBeadsDir, "caller"); got != 0 { + t.Fatalf("inherited BEADS_DIR received %d issues, want 0", got) + } + if got := countIssues(targetBeadsDir, "target"); got != 1 { + t.Fatalf("-C target received %d issues, want 1", got) + } +} + // TestEmbeddedCreateCommitPending verifies that CommitPending works on EmbeddedDoltStore: // no-op when clean, commits when there are pending changes. func TestEmbeddedCreateCommitPending(t *testing.T) { diff --git a/cmd/bd/directory_flag_test.go b/cmd/bd/directory_flag_test.go index e2554ad30..bca9ff832 100644 --- a/cmd/bd/directory_flag_test.go +++ b/cmd/bd/directory_flag_test.go @@ -4,6 +4,8 @@ import ( "os" "path/filepath" "testing" + + "github.com/spf13/cobra" ) func TestResolveChangeDirBeadsDirDoesNotChangeCWD(t *testing.T) { @@ -63,3 +65,32 @@ func TestResolveChangeDirBeadsDirRejectsDirectoryWithoutProject(t *testing.T) { t.Fatal("expected -C target without a beads project to fail") } } + +func TestIsPreviewCommand(t *testing.T) { + tests := []struct { + name string + flag string + set string + want bool + }{ + {name: "dry run", flag: "dry-run", set: "true", want: true}, + {name: "inspect", flag: "inspect", set: "true", want: true}, + {name: "false preview flag", flag: "dry-run", set: "false", want: false}, + {name: "no preview flag", want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cmd := &cobra.Command{Use: "test"} + if tt.flag != "" { + cmd.Flags().Bool(tt.flag, false, "") + if err := cmd.Flags().Set(tt.flag, tt.set); err != nil { + t.Fatalf("set %s: %v", tt.flag, err) + } + } + if got := isPreviewCommand(cmd); got != tt.want { + t.Fatalf("isPreviewCommand() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 04e840ba8..6d554649d 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -36,6 +36,7 @@ import ( "github.com/steveyegge/beads/internal/storage/backends" "github.com/steveyegge/beads/internal/storage/dolt" dbidentifier "github.com/steveyegge/beads/internal/storage/domain/db" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" "github.com/steveyegge/beads/internal/storage/schema" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/telemetry" @@ -176,6 +177,22 @@ func isReadOnlyCommand(cmdName string) bool { return readOnlyCommands[cmdName] } +// isPreviewCommand reports whether cmd was explicitly invoked in a +// non-mutating preview mode. Preview flags are command-local rather than +// persistent, so checking them here after Cobra has parsed the selected +// command is the earliest reliable point to keep the store open read-only. +func isPreviewCommand(cmd *cobra.Command) bool { + for _, name := range []string{"dry-run", "inspect"} { + if flag := cmd.Flags().Lookup(name); flag != nil { + enabled, err := cmd.Flags().GetBool(name) + if err == nil && enabled { + return true + } + } + } + return false +} + type rootStorePolicy struct { readOnly bool disableAutoStart bool @@ -1294,19 +1311,30 @@ var rootCmd = &cobra.Command{ commandSpan.SetAttributes(attribute.String("bd.actor", actor)) } + // Check if this is a read-only command (GH#804) or an explicitly + // non-mutating preview. Both must open the store read-only: otherwise + // schema initialization runs before the command's RunE can honor + // --dry-run/--inspect or reject invalid arguments. Resolved here, + // ahead of version tracking, because that is the first step a preview + // has to change. + previewMode := isPreviewCommand(cmd) policy := effectiveRootStorePolicy(cmd.Name(), readonlyMode) + useReadOnly := policy.readOnly || previewMode // Track bd version changes unless strict readonly forbids repository mutation. // Best-effort tracking - failures are silent. + // + // A preview detects the change but must not consume it: .local_version + // is the one-shot signal autoMigrateOnVersionBump reads, and a preview + // skips that reconciliation (see below). See trackBdVersionPreview. if policy.runMaintenance { - trackBdVersion() + if previewMode { + trackBdVersionPreview() + } else { + trackBdVersion() + } } - // Check if this is a read-only command (GH#804) - // Read-only commands open the store in read-only mode to avoid modifying - // the database (which breaks file watchers). - useReadOnly := policy.readOnly - // If the operator passed --force on `bd migrate` or `bd migrate schema`, // set the programmatic gate override before both autoMigrateOnVersionBump // and the main store open — both open their own store connections and the @@ -1322,12 +1350,17 @@ var rootCmd = &cobra.Command{ schema.SetForceAllowRemoteMigrate(forcedMigrate) // Auto-migrate database on version bump (bd-jgxi). - // Runs for ALL commands (including read-only ones) because the migration - // opens its own store connection, writes the version metadata, commits it, - // and closes BEFORE the main store is opened. This ensures bd doctor and - // read-only commands see the correct version after a CLI upgrade. - - if policy.runMaintenance { + // Runs for ALL non-preview commands (including read-only ones) because + // the migration opens its own store connection, writes the version + // metadata, commits it, and closes BEFORE the main store is opened. + // This ensures bd doctor and read-only commands see the correct version + // after a CLI upgrade. + // + // Preview paths must never call this helper: it opens a separate + // writable store before the main read-only store and can therefore + // apply schema migrations before RunE validates arguments or renders a + // dry-run plan. + if policy.runMaintenance && !previewMode { autoMigrateOnVersionBump(beadsDir) } @@ -1339,6 +1372,7 @@ var rootCmd = &cobra.Command{ doltPath := doltserver.ResolveDoltDir(beadsDir) doltCfg := &dolt.Config{ ReadOnly: useReadOnly, + Preview: previewMode, DisableAutoStart: policy.disableAutoStart, BeadsDir: beadsDir, LenientOpen: isWorkingSetReconcileCommand(cmd), @@ -1446,14 +1480,23 @@ var rootCmd = &cobra.Command{ // In proxied mode the CLI short-circuits to the uowProvider path and // dispatches through the *_proxied_server.go duals. + // + // Preview commands take the same policy here as they do on the + // embedded and server paths, and for the same reason: the provider + // open runs CREATE DATABASE and schema.MigrateUpWithLock, and + // reconcileVersionProxiedServer writes version metadata — all during + // root pre-run, before --dry-run/--inspect has had any effect. Proxied + // mode is where that is least visible, not where it is acceptable. if proxiedServerMode { - p, err := newProxiedServerUOWProvider(rootCtx, beadsDir, databaseOverride) + p, err := newProxiedServerUOWProvider(rootCtx, beadsDir, databaseOverride, previewProviderOptions(previewMode)...) if err != nil { return HandleError("failed to open uow provider: %v", err) } uowProvider = p - reconcileVersionProxiedServer(rootCtx) + if !previewMode { + reconcileVersionProxiedServer(rootCtx) + } syncCommandContext() return nil @@ -1654,21 +1697,40 @@ var rootCmd = &cobra.Command{ return HandleError("dolt tip auto-commit failed: %v", err) } else if mode == doltAutoCommitOn { // Apply tip metadata writes now (deferred in recordTipShown for Dolt). + // + // A store that refuses writes by construction — the + // preview open, and strict --readonly — must not turn + // an otherwise successful command into a non-zero exit + // here. This block is deliberately not gated by the + // read-only classification, and that has been fine + // because OpenForReadOnlyCommand is "otherwise a normal + // writable store"; the write-refusing opens break that + // assumption. Tip bookkeeping is incidental and + // recordTipShown's own contract is that it may fail + // silently, so skip it and carry on. + tipWritesRefused := false for tipID := range commandTipIDsShown { key := fmt.Sprintf("tip_%s_last_shown", tipID) value := time.Now().Format(time.RFC3339) if err := store.SetLocalMetadata(rootCtx, key, value); err != nil { + if errors.Is(err, embeddeddolt.ErrReadOnly) { + debug.Logf("tip auto-commit: store is read-only, skipping tip metadata: %v", err) + tipWritesRefused = true + break + } return HandleError("dolt tip auto-commit failed: %v", err) } } - ids := make([]string, 0, len(commandTipIDsShown)) - for tipID := range commandTipIDsShown { - ids = append(ids, tipID) - } - msg := formatDoltAutoCommitMessage("tip", getActor(), ids) - if err := runPostRunAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil { - return HandleError("dolt tip auto-commit failed: %v", err) + if !tipWritesRefused { + ids := make([]string, 0, len(commandTipIDsShown)) + for tipID := range commandTipIDsShown { + ids = append(ids, tipID) + } + msg := formatDoltAutoCommitMessage("tip", getActor(), ids) + if err := runPostRunAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil { + return HandleError("dolt tip auto-commit failed: %v", err) + } } } } diff --git a/cmd/bd/store_factory.go b/cmd/bd/store_factory.go index 704c7bcef..03f95c6bc 100644 --- a/cmd/bd/store_factory.go +++ b/cmd/bd/store_factory.go @@ -55,6 +55,12 @@ func newDoltStore(ctx context.Context, cfg *dolt.Config) (storage.DoltStorage, e if cfg.ServerMode { return dolt.New(ctx, cfg) } + if cfg.Preview { + // Preview commands are stricter than ordinary read commands: they + // must not run schema initialization or permit incidental writes + // before their RunE honors --dry-run/--inspect. + return embeddeddolt.OpenForPreviewCommand(ctx, cfg.BeadsDir, cfg.Database, "main") + } if cfg.ReadOnly { if cfg.DisableAutoStart { // Strict --readonly (cfg.DisableAutoStart is the strict-only @@ -197,6 +203,22 @@ func migrateHyphenatedDB(beadsDir string, cfg *configfile.Config, oldName, newNa // only — no directory renames or metadata.json writes. This prevents cross-repo // hydration from mutating foreign projects (GH#3231). func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) { + return openNonMutatingStoreFromConfig(ctx, beadsDir, false) +} + +// newPreviewStoreFromConfig is newReadOnlyStoreFromConfig for a preview +// command (--dry-run, --inspect) reading a repository it was only pointed at: +// the same non-mutating open, but a BEHIND schema cursor is tolerated rather +// than refused, matching embeddeddolt.OpenForPreviewCommand and the preview +// policy the root pre-run applies to the command's own store. A preview that +// only reads a parent issue out of another repo should not be the thing that +// refuses because that repo has not been migrated yet — and it must certainly +// not migrate it. +func newPreviewStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) { + return openNonMutatingStoreFromConfig(ctx, beadsDir, true) +} + +func openNonMutatingStoreFromConfig(ctx context.Context, beadsDir string, preview bool) (storage.DoltStorage, error) { cfg, err := configfile.Load(beadsDir) if err != nil { // Same contract as newDoltStoreFromConfig: a present-but-unloadable @@ -231,6 +253,9 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D if sanitized := sanitizeDBName(database); sanitized != database { database = sanitized } + if preview { + return embeddeddolt.OpenForPreviewCommand(ctx, beadsDir, database, "main") + } // OpenReadOnly, not Open: a read-only open of a foreign project must not // run the remote-migrate gate (a behind, remote-backed database would fail // hard) and must not write migrations into the target's history diff --git a/cmd/bd/store_factory_nocgo.go b/cmd/bd/store_factory_nocgo.go index 8d0ce8448..2d5102f24 100644 --- a/cmd/bd/store_factory_nocgo.go +++ b/cmd/bd/store_factory_nocgo.go @@ -104,6 +104,13 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D return nil, fmt.Errorf("%s", nocgoEmbeddedErrMsg) } +// newPreviewStoreFromConfig is the non-CGO twin of the CGO build's preview +// factory. The two differ only in how they open the EMBEDDED store, and this +// build has no embedded store at all, so preview and read-only coincide here. +func newPreviewStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) { + return newReadOnlyStoreFromConfig(ctx, beadsDir) +} + const nocgoEmbeddedErrMsg = `embedded Dolt requires a CGO build, but this bd binary was built with CGO_ENABLED=0. Three options: diff --git a/cmd/bd/uow_factory.go b/cmd/bd/uow_factory.go index 7763d7512..10cc27ab5 100644 --- a/cmd/bd/uow_factory.go +++ b/cmd/bd/uow_factory.go @@ -40,12 +40,30 @@ type sqlServerUOWTopology struct { rootPassword string } +// previewProviderOptions is the CLI-side half of the preview policy: it turns +// the root pre-run's previewMode bool into the uow.ProviderOption slice the +// proxied-server provider is opened with. Extracted (rather than inlined at +// the call site) so the wiring — preview=true must produce uow.WithPreview(), +// preview=false must produce nothing — has something to unit test; the +// previous inline form had no test that would fail if a refactor dropped it. +func previewProviderOptions(preview bool) []uow.ProviderOption { + if !preview { + return nil + } + return []uow.ProviderOption{uow.WithPreview()} +} + // newProxiedServerUOWProvider opens the proxied-server provider and, in // team-server mode, asserts that the shared bts-managed database is serving // THIS workspace's project (gastownhall/beads: the proxied-path sibling of the // gateway's DoltStore.verifyProjectIdentity guard). -func newProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride string) (uow.UnitOfWorkProvider, error) { - return openProxiedServerUOWProvider(ctx, beadsDir, databaseOverride, assertWorkspaceIdentity) +// +// opts carry the open's posture that is not workspace topology — today only +// uow.WithPreview(), which the root pre-run passes for --dry-run/--inspect so +// a proxied preview does not create or migrate the database before the +// command's own RunE runs. +func newProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride string, opts ...uow.ProviderOption) (uow.UnitOfWorkProvider, error) { + return openProxiedServerUOWProvider(ctx, beadsDir, databaseOverride, assertWorkspaceIdentity, opts...) } // newProxiedServerUOWProviderAdopting skips that assertion. Only two callers @@ -53,8 +71,8 @@ func newProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride // which ADOPTS the identity the shared database already carries (asserting the // locally-minted placeholder would reject every correct init), and server-wide // database maintenance, which is not scoped to one project's database. -func newProxiedServerUOWProviderAdopting(ctx context.Context, beadsDir, databaseOverride string) (uow.UnitOfWorkProvider, error) { - return openProxiedServerUOWProvider(ctx, beadsDir, databaseOverride, adoptWorkspaceIdentity) +func newProxiedServerUOWProviderAdopting(ctx context.Context, beadsDir, databaseOverride string, opts ...uow.ProviderOption) (uow.UnitOfWorkProvider, error) { + return openProxiedServerUOWProvider(ctx, beadsDir, databaseOverride, adoptWorkspaceIdentity, opts...) } // identityPosture selects whether a proxied open asserts the workspace's @@ -66,7 +84,7 @@ const ( adoptWorkspaceIdentity identityPosture = true ) -func openProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride string, posture identityPosture) (uow.UnitOfWorkProvider, error) { +func openProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverride string, posture identityPosture, opts ...uow.ProviderOption) (uow.UnitOfWorkProvider, error) { if beadsDir == "" { return nil, fmt.Errorf("newProxiedServerUOWProvider: beadsDir must be set") } @@ -74,14 +92,14 @@ func openProxiedServerUOWProvider(ctx context.Context, beadsDir, databaseOverrid if err != nil { return nil, err } - return newSQLServerUOWProvider(ctx, beadsDir, topology) + return newSQLServerUOWProvider(ctx, beadsDir, topology, opts...) } -func newSQLServerUOWProvider(ctx context.Context, beadsDir string, topology sqlServerUOWTopology) (uow.UnitOfWorkProvider, error) { +func newSQLServerUOWProvider(ctx context.Context, beadsDir string, topology sqlServerUOWTopology, opts ...uow.ProviderOption) (uow.UnitOfWorkProvider, error) { if topology.external != nil { - return newExternalProxiedServerUOWProvider(ctx, beadsDir, topology) + return newExternalProxiedServerUOWProvider(ctx, beadsDir, topology, opts...) } - return newManagedProxiedServerUOWProvider(ctx, beadsDir, topology) + return newManagedProxiedServerUOWProvider(ctx, beadsDir, topology, opts...) } // resolveProxiedServerUOWTopology reads a proxied-server workspace's topology @@ -297,7 +315,7 @@ func resolveServerModeUOWTopologyWithTransportResolver(ctx context.Context, bead // the workspace mode: since bd-emv a server-mode workspace lands here too, and // the paths it resolves (root, log) are the same ones proxied mode uses because // both modes root their server at the same directory. -func newExternalProxiedServerUOWProvider(ctx context.Context, beadsDir string, topology sqlServerUOWTopology) (uow.UnitOfWorkProvider, error) { +func newExternalProxiedServerUOWProvider(ctx context.Context, beadsDir string, topology sqlServerUOWTopology, opts ...uow.ProviderOption) (uow.UnitOfWorkProvider, error) { rootPath, err := resolveProxiedServerRootPath(beadsDir) if err != nil { return nil, fmt.Errorf("newExternalProxiedServerUOWProvider: resolve root path: %w", err) @@ -332,10 +350,11 @@ func newExternalProxiedServerUOWProvider(ctx context.Context, beadsDir string, t topology.proxyIdle, topology.teamServer, topology.expectedProjectID, + opts..., ) } -func newManagedProxiedServerUOWProvider(ctx context.Context, beadsDir string, topology sqlServerUOWTopology) (uow.UnitOfWorkProvider, error) { +func newManagedProxiedServerUOWProvider(ctx context.Context, beadsDir string, topology sqlServerUOWTopology, opts ...uow.ProviderOption) (uow.UnitOfWorkProvider, error) { doltBin, err := exec.LookPath("dolt") if err != nil { return nil, fmt.Errorf("newProxiedServerUOWProvider: dolt is not installed (not found in PATH); install from https://docs.dolthub.com/introduction/installation: %w", err) @@ -384,5 +403,6 @@ func newManagedProxiedServerUOWProvider(ctx context.Context, beadsDir string, to topology.proxyIdle, topology.teamServer, topology.expectedProjectID, + opts..., ) } diff --git a/cmd/bd/uow_factory_test.go b/cmd/bd/uow_factory_test.go index a2a5497b7..fae22c25d 100644 --- a/cmd/bd/uow_factory_test.go +++ b/cmd/bd/uow_factory_test.go @@ -10,6 +10,29 @@ import ( "github.com/stretchr/testify/require" ) +// TestPreviewProviderOptions pins the CLI-side wiring the reviewer flagged as +// untested: the root pre-run turns previewMode into providerOpts by calling +// this function, and a refactor that dropped or inverted that could not fail +// any existing test. uow.providerOptions is unexported, so this cannot poke +// inside the returned uow.ProviderOption values (see +// internal/storage/uow/preview_provider_test.go's TestApplyProviderOptions for +// the same-package introspection); it instead pins the one thing an external +// caller can observe — that preview=true yields exactly one option and +// preview=false yields none — which is what the CLI wiring is responsible for. +func TestPreviewProviderOptions(t *testing.T) { + if got := previewProviderOptions(false); got != nil { + t.Fatalf("previewProviderOptions(false) = %#v, want nil", got) + } + + opts := previewProviderOptions(true) + if len(opts) != 1 { + t.Fatalf("previewProviderOptions(true) len = %d, want 1", len(opts)) + } + if opts[0] == nil { + t.Fatal("previewProviderOptions(true)[0] is nil, want uow.WithPreview()") + } +} + func TestNewProxiedServerUOWProvider_RoutesExternalConfigToExternalProvider(t *testing.T) { beadsDir := t.TempDir() require.NoError(t, configfile.SaveProxiedServerClientInfo(beadsDir, &configfile.ProxiedServerClientInfo{ diff --git a/cmd/bd/version_tracking.go b/cmd/bd/version_tracking.go index 7be1ae02c..8ff381629 100644 --- a/cmd/bd/version_tracking.go +++ b/cmd/bd/version_tracking.go @@ -24,6 +24,28 @@ const localVersionFile = ".local_version" // This function is best-effort - failures are silent to avoid disrupting commands. // Sets global variables versionUpgradeDetected and previousVersion if upgrade detected. func trackBdVersion() { + trackBdVersionFile(true) +} + +// trackBdVersionPreview does the same detection but leaves .local_version +// alone. +// +// The file is a ONE-SHOT signal: the version-bump reconciliation +// (autoMigrateOnVersionBump, including the pre-0.56 recovery path) fires only +// while the recorded version differs from this binary's. A preview command +// correctly skips that reconciliation — but if it had also rewritten the file, +// it would have consumed the signal on the way past, and the next ordinary +// command would see a matching version and never reconcile at all. Whichever +// command happened to be first after an upgrade would silently decide whether +// the upgrade was ever finished. +// +// Not writing is safe in the other direction too: the marker is advisory and +// the very next non-preview command writes it. +func trackBdVersionPreview() { + trackBdVersionFile(false) +} + +func trackBdVersionFile(persist bool) { // Find the beads directory beadsDir := beads.FindBeadsDir() if beadsDir == "" { @@ -46,7 +68,7 @@ func trackBdVersion() { // Update local version file (best effort) // Only write if version actually changed to minimize I/O - if lastVersion != Version { + if persist && lastVersion != Version { _ = writeLocalVersion(localVersionPath, Version) // Best effort: version tracking is advisory } diff --git a/internal/storage/dolt/store.go b/internal/storage/dolt/store.go index 818c58283..05b0c0cc2 100644 --- a/internal/storage/dolt/store.go +++ b/internal/storage/dolt/store.go @@ -361,6 +361,7 @@ type Config struct { Remote string // Default remote name (e.g., "origin") Database string // Database name within Dolt (default: "beads") ReadOnly bool // Open in read-only mode (skip schema init) + Preview bool // Non-mutating preview: embedded opens skip schema init and refuse writes // LenientOpen opens the store leniently: embedded mode only. A migration // gate refusal (#4259) or a dirty-working-set refusal (#4566) skips the diff --git a/internal/storage/embeddeddolt/preview_readonly_test.go b/internal/storage/embeddeddolt/preview_readonly_test.go new file mode 100644 index 000000000..fcf960b7b --- /dev/null +++ b/internal/storage/embeddeddolt/preview_readonly_test.go @@ -0,0 +1,57 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/steveyegge/beads/internal/storage/embeddeddolt" +) + +// TestPreviewStoreRefusesLocalMetadataWrite pins the classification the CLI's +// PersistentPostRun tip auto-commit keys on. That block writes tip metadata +// unconditionally — read-only commands have always tolerated it because +// OpenForReadOnlyCommand is deliberately writable — so the write-refusing +// preview store must return an error that errors.Is recognizes, or a +// successful dry-run exits non-zero after the fact. +func TestPreviewStoreRefusesLocalMetadataWrite(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests") + } + + ctx := t.Context() + beadsDir := filepath.Join(t.TempDir(), ".beads") + + store, err := embeddeddolt.Open(ctx, beadsDir, "previewdb", "main") + if err != nil { + t.Fatalf("Open: %v", err) + } + if err := store.SetLocalMetadata(ctx, "tip_example_last_shown", "2026-01-01T00:00:00Z"); err != nil { + t.Fatalf("SetLocalMetadata on writable store: %v", err) + } + if err := store.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + preview, err := embeddeddolt.OpenForPreviewCommand(ctx, beadsDir, "previewdb", "main") + if err != nil { + t.Fatalf("OpenForPreviewCommand: %v", err) + } + defer func() { _ = preview.Close() }() + + // Reads still work. + if _, err := preview.GetLocalMetadata(ctx, "tip_example_last_shown"); err != nil { + t.Fatalf("GetLocalMetadata on preview store: %v", err) + } + + err = preview.SetLocalMetadata(ctx, "tip_example_last_shown", "2026-02-02T00:00:00Z") + if err == nil { + t.Fatal("SetLocalMetadata on preview store = nil error, want refusal") + } + if !errors.Is(err, embeddeddolt.ErrReadOnly) { + t.Fatalf("SetLocalMetadata on preview store = %v, want an error matching embeddeddolt.ErrReadOnly", err) + } +} diff --git a/internal/storage/embeddeddolt/readonly.go b/internal/storage/embeddeddolt/readonly.go new file mode 100644 index 000000000..d01deb2b3 --- /dev/null +++ b/internal/storage/embeddeddolt/readonly.go @@ -0,0 +1,17 @@ +package embeddeddolt + +import "errors" + +// ErrReadOnly is returned when a write is attempted on a store opened +// read-only — OpenReadOnly, or OpenForPreviewCommand for a --dry-run/--inspect +// command. +// +// It is exported (and declared here, without a cgo build tag) because callers +// outside this package have to be able to tell "this store refuses writes by +// construction" apart from a real failure. The CLI's post-command +// tip-metadata write is the case that forced it: that write is incidental +// bookkeeping which read-only opens have always tolerated because +// OpenForReadOnlyCommand is deliberately writable, and a store that genuinely +// refuses it must not turn an otherwise successful command into a non-zero +// exit after the fact. +var ErrReadOnly = errors.New("embeddeddolt: store is read-only") diff --git a/internal/storage/embeddeddolt/store.go b/internal/storage/embeddeddolt/store.go index d740164c1..b71d6eafe 100644 --- a/internal/storage/embeddeddolt/store.go +++ b/internal/storage/embeddeddolt/store.go @@ -47,9 +47,10 @@ type EmbeddedDoltStore struct { branch string credentialKey []byte closed atomic.Bool - // readOnly marks a store opened via OpenReadOnly: open-time mutations - // (CREATE DATABASE, schema migrations) were skipped and write - // transactions are refused (bd-6dnrw.32). + // readOnly marks a store opened via OpenReadOnly or + // OpenForPreviewCommand: open-time mutations (CREATE DATABASE, schema + // migrations) were skipped and write transactions are refused + // (bd-6dnrw.32). readOnly bool // intent records why this store was opened, controlling how lenient // initSchema is about pending-migration refusals it would otherwise treat @@ -85,9 +86,6 @@ const ( // errClosed is returned when a method is called after Close. var errClosed = errors.New("embeddeddolt: store is closed") -// errReadOnly is returned when a write is attempted on a read-only store. -var errReadOnly = errors.New("embeddeddolt: store is read-only") - // IsClosed reports whether the store has been closed. Implements // storage.LifecycleManager so that callers (e.g., maybeAutoCommit) can // skip operations on a closed store without triggering errClosed. @@ -151,6 +149,20 @@ func newStore(ctx context.Context, beadsDir, database, branch string, intent ope // opens of the same directory keep their own lifecycle. Write transactions on // the returned store are refused. func OpenReadOnly(ctx context.Context, beadsDir, database, branch string) (*EmbeddedDoltStore, error) { + return openReadOnly(ctx, beadsDir, database, branch, true) +} + +// OpenForPreviewCommand opens an existing embedded database without any +// open-time mutation and refuses all write transactions. Unlike +// OpenReadOnly, it permits a behind schema cursor so --dry-run/--inspect can +// still validate state that is query-compatible with the current binary. A +// missing column or other genuine incompatibility is reported by the preview +// query itself; it is never repaired implicitly. +func OpenForPreviewCommand(ctx context.Context, beadsDir, database, branch string) (*EmbeddedDoltStore, error) { + return openReadOnly(ctx, beadsDir, database, branch, false) +} + +func openReadOnly(ctx context.Context, beadsDir, database, branch string, checkBehind bool) (*EmbeddedDoltStore, error) { if database == "" { return nil, fmt.Errorf("embeddeddolt: database name must not be empty (caller should default to %q)", "beads") } @@ -182,8 +194,10 @@ func OpenReadOnly(ctx context.Context, beadsDir, database, branch string) (*Embe if err := schema.CheckForwardDrift(ctx, db); err != nil { return nil, err } - if err := schema.CheckBehindDrift(ctx, db); err != nil { - return nil, err + if checkBehind { + if err := schema.CheckBehindDrift(ctx, db); err != nil { + return nil, err + } } return s, nil @@ -202,7 +216,7 @@ func (s *EmbeddedDoltStore) withConn(ctx context.Context, commit bool, fn func(t return } if commit && s.readOnly { - err = errReadOnly + err = ErrReadOnly return } @@ -246,7 +260,7 @@ func (s *EmbeddedDoltStore) ApplySchemaMigrations(ctx context.Context) (int, err return 0, errClosed } if s.readOnly { - return 0, errReadOnly + return 0, ErrReadOnly } db, cleanup, err := OpenSQL(ctx, s.dataDir, s.database, s.branch) if err != nil { diff --git a/internal/storage/embeddeddolt/store_stub.go b/internal/storage/embeddeddolt/store_stub.go index 53c0ec6a7..87b046245 100644 --- a/internal/storage/embeddeddolt/store_stub.go +++ b/internal/storage/embeddeddolt/store_stub.go @@ -26,6 +26,11 @@ func OpenReadOnly(_ context.Context, _, _, _ string) (*EmbeddedDoltStore, error) return nil, errNoCGO } +// OpenForPreviewCommand returns an error when CGO is not enabled. +func OpenForPreviewCommand(_ context.Context, _, _, _ string) (*EmbeddedDoltStore, error) { + return nil, errNoCGO +} + // OpenForReadOnlyCommand returns an error when CGO is not enabled. func OpenForReadOnlyCommand(_ context.Context, _, _, _ string) (*EmbeddedDoltStore, error) { return nil, errNoCGO diff --git a/internal/storage/embeddeddolt/version_control.go b/internal/storage/embeddeddolt/version_control.go index 6d906223d..318ee7db8 100644 --- a/internal/storage/embeddeddolt/version_control.go +++ b/internal/storage/embeddeddolt/version_control.go @@ -84,7 +84,7 @@ func (s *EmbeddedDoltStore) withPinnedDBConn(ctx context.Context, fn func(db ver // interface and must refuse them here instead (bd-578h9.12). func (s *EmbeddedDoltStore) withMutatingDBConn(ctx context.Context, fn func(db versioncontrolops.DBConn) error) error { if s.readOnly { - return errReadOnly + return ErrReadOnly } return s.withDBConn(ctx, fn) } @@ -93,7 +93,7 @@ func (s *EmbeddedDoltStore) withMutatingDBConn(ctx context.Context, fn func(db v // refusal as withMutatingDBConn (bd-578h9.12). func (s *EmbeddedDoltStore) withMutatingPinnedDBConn(ctx context.Context, fn func(db versioncontrolops.DBConn) error) error { if s.readOnly { - return errReadOnly + return ErrReadOnly } return s.withPinnedDBConn(ctx, fn) } diff --git a/internal/storage/uow/dolt_sql_provider.go b/internal/storage/uow/dolt_sql_provider.go index bf1f40d34..1233102d0 100644 --- a/internal/storage/uow/dolt_sql_provider.go +++ b/internal/storage/uow/dolt_sql_provider.go @@ -32,6 +32,42 @@ type doltSQLProvider struct { // available" (bd init, which adopts; server-wide maintenance; a workspace // predating project identity) and skips the check. expectedProjectID string + // preview: the command that opened this provider is an explicitly + // non-mutating preview (--dry-run, --inspect). The open creates no + // database and applies no migration; see providerOptions.preview. + preview bool +} + +// ProviderOption tunes how a SQL-server unit-of-work provider opens. Options +// are variadic so the existing constructor call sites — every one of which +// wants the ordinary mutating open — stay unchanged. +type ProviderOption func(*providerOptions) + +type providerOptions struct { + // preview opens for a command that promised not to mutate anything + // (--dry-run, --inspect). Such a command must reach its own RunE before + // anything writes, so the open may neither CREATE DATABASE nor run + // MigrateUpWithLock: both happen during root pre-run, before the flag the + // user passed has had any effect. An absent or behind database is + // reported by the preview's own query rather than repaired implicitly — + // the same contract embeddeddolt.OpenForPreviewCommand gives the embedded + // path. + preview bool +} + +// WithPreview opens the provider for a non-mutating preview command. +func WithPreview() ProviderOption { + return func(o *providerOptions) { o.preview = true } +} + +func applyProviderOptions(opts []ProviderOption) providerOptions { + var resolved providerOptions + for _, opt := range opts { + if opt != nil { + opt(&resolved) + } + } + return resolved } var ( @@ -128,6 +164,21 @@ func (p *doltSQLProvider) initSchema(ctx context.Context, database string) error } return nil } + if p.preview { + // Preview open: attach to the database that is already there and + // stop. No CreateDatabase, no MigrateUpWithLock — a --dry-run or + // --inspect that migrated the workspace before rendering its plan + // would be the exact side effect the flag exists to prevent. + if err := ddl.UseDatabase(ctx, database); err != nil { + if isSerializationError(err) { + return fmt.Errorf("uow: switching to database: %w", err) + } + return backoff.Permanent(fmt.Errorf( + "uow: database %q not found — preview commands (--dry-run, --inspect) never create or migrate a database; run the command without the preview flag first: %w", + database, err)) + } + return nil + } if created { // Re-assert on retries so a database dropped between attempts // (e.g. a concurrent clean-databases) is recreated rather than @@ -189,7 +240,7 @@ func openDB(ctx context.Context, dsn string) (*sql.DB, error) { return conn, nil } -func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUser, rootPassword, tlsConfigName string, teamServer bool, expectedProjectID string) (UnitOfWorkProvider, error) { +func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUser, rootPassword, tlsConfigName string, teamServer bool, expectedProjectID string, opts providerOptions) (UnitOfWorkProvider, error) { initDB, err := openDB(ctx, buildDSN(ep, "", rootUser, rootPassword, tlsConfigName)) if err != nil { return nil, err @@ -200,6 +251,7 @@ func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUse db: initDB, teamServer: teamServer, expectedProjectID: expectedProjectID, + preview: opts.preview, } if err := initProvider.initSchema(ctx, database); err != nil { @@ -221,5 +273,6 @@ func openAndInitSchema(ctx context.Context, ep proxy.Endpoint, database, rootUse db: dbConn, teamServer: teamServer, expectedProjectID: expectedProjectID, + preview: opts.preview, }, nil } diff --git a/internal/storage/uow/doltserver_provider.go b/internal/storage/uow/doltserver_provider.go index f9086b462..e13307cc7 100644 --- a/internal/storage/uow/doltserver_provider.go +++ b/internal/storage/uow/doltserver_provider.go @@ -27,6 +27,7 @@ func NewDoltServerUOWProvider( idleTimeout time.Duration, teamServer bool, expectedProjectID string, + opts ...ProviderOption, ) (UnitOfWorkProvider, error) { if idleTimeout == 0 { idleTimeout = defaultProxyIdleTimeout @@ -70,5 +71,5 @@ func NewDoltServerUOWProvider( return nil, fmt.Errorf("uow: get proxy endpoint: %w", err) } - return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, "", teamServer, expectedProjectID) + return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, "", teamServer, expectedProjectID, applyProviderOptions(opts)) } diff --git a/internal/storage/uow/external_doltserver_provider.go b/internal/storage/uow/external_doltserver_provider.go index 89f4329fd..4fb67fa0d 100644 --- a/internal/storage/uow/external_doltserver_provider.go +++ b/internal/storage/uow/external_doltserver_provider.go @@ -27,6 +27,7 @@ func NewExternalDoltServerUOWProvider( idleTimeout time.Duration, teamServer bool, expectedProjectID string, + opts ...ProviderOption, ) (UnitOfWorkProvider, error) { if idleTimeout == 0 { idleTimeout = defaultProxyIdleTimeout @@ -66,7 +67,7 @@ func NewExternalDoltServerUOWProvider( return nil, fmt.Errorf("uow: get proxy endpoint: %w", err) } - return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, tlsConfigName, teamServer, expectedProjectID) + return openAndInitSchema(ctx, ep, database, rootUser, rootPassword, tlsConfigName, teamServer, expectedProjectID, applyProviderOptions(opts)) } func registerExternalTLSConfig(external configfile.ExternalDoltConfig) (string, error) { diff --git a/internal/storage/uow/preview_provider_test.go b/internal/storage/uow/preview_provider_test.go new file mode 100644 index 000000000..6f815c55e --- /dev/null +++ b/internal/storage/uow/preview_provider_test.go @@ -0,0 +1,73 @@ +package uow + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/DATA-DOG/go-sqlmock" +) + +// TestInitSchemaPreviewDoesNotMutate is the proxied-server half of the +// preview policy: a --dry-run/--inspect command reaches this open during root +// pre-run, before its own RunE has had any chance to honor the flag, so the +// open must attach to the existing database and nothing more. sqlmock is in +// ordered mode with only USE expected, so a CREATE DATABASE or a migration +// statement fails the test rather than silently succeeding. +func TestInitSchemaPreviewDoesNotMutate(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer func() { _ = db.Close() }() + + mock.ExpectExec("USE `beads`").WillReturnResult(sqlmock.NewResult(0, 0)) + + p := &doltSQLProvider{defaultBranch: defaultBranch, db: db, preview: true} + if err := p.initSchema(context.Background(), "beads"); err != nil { + t.Fatalf("initSchema(preview): %v", err) + } + + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet or extra statements during preview open: %v", err) + } +} + +// TestInitSchemaPreviewMissingDatabaseFailsClosed pins the other half of the +// contract: a database the preview cannot attach to is reported, never +// created. The message has to say so, because "not found" on a path that +// normally creates the database reads as a bug otherwise. +func TestInitSchemaPreviewMissingDatabaseFailsClosed(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer func() { _ = db.Close() }() + + mock.ExpectExec("USE `beads`").WillReturnError(errors.New("database not found: beads")) + + p := &doltSQLProvider{defaultBranch: defaultBranch, db: db, preview: true} + err = p.initSchema(context.Background(), "beads") + if err == nil { + t.Fatal("initSchema(preview) on a missing database: got nil, want error") + } + if !strings.Contains(err.Error(), "--dry-run") { + t.Fatalf("preview open error does not explain the preview contract: %v", err) + } + + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet or extra statements during preview open: %v", err) + } +} + +// TestApplyProviderOptions keeps the option plumbing honest: the ordinary +// callers pass nothing and must stay on the mutating open. +func TestApplyProviderOptions(t *testing.T) { + if got := applyProviderOptions(nil); got.preview { + t.Fatal("applyProviderOptions(nil).preview = true, want false") + } + if got := applyProviderOptions([]ProviderOption{WithPreview()}); !got.preview { + t.Fatal("applyProviderOptions(WithPreview()).preview = false, want true") + } +}