From b13fab0151724a75f636e94295c3eba9efbcf149 Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Fri, 28 Aug 2026 23:27:39 -0700 Subject: [PATCH] =?UTF-8?q?fix(storage):=20truthful=20legacy-backend=20tom?= =?UTF-8?q?bstone=20rejection=20=E2=80=94=20detect=20present=20Dolt=20data?= =?UTF-8?q?,=20give=20the=20exact=20heal=20(D-8)=20(#6044)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(configfile): detect present Dolt data and give the exact metadata heal (D-8) A workspace whose metadata.json names sqlite/postgres/mysql stays fail-closed, but the rejection text was not truthful for the common case. bd v1.2.x opened those workspaces as Dolt regardless of the "backend" value, so for them the stale field is the only problem — and the old remedy sent the user to export and reinitialize, destroying a database that is one JSON edit from healthy. ExistingDoltDataDir stats the embedded (.beads/embeddeddolt) and server-mode (.beads/dolt, dolt_data_dir, BEADS_DOLT_DATA_DIR) layouts for a .dolt directory, either at the root or one level down. Detection is stat/readdir only — every caller is on a path that has promised not to touch storage. The detection approach is ported from the obsolete PR #4740. The removed- and unknown-backend messages now branch on it: with Dolt data present they name metadata.json and the exact edit ("backend": "dolt", or drop the field); without it they keep today's export/reinitialize path, so the substrings existing tests pin are unchanged. GetDoltDataDir becomes nil-safe like GetBackend, since rejection paths resolve it for configs that may be nil. Co-authored-by: Steve Yegge * fix(storage): thread beadsDir into every legacy-backend rejection (D-8) All three rejection surfaces now branch on whether the workspace actually holds a Dolt database: cmd/bd's validateConfiguredBackend (12 call sites, every one already had beadsDir in scope), internal/storage/dolt's requireDoltBackend, and the public beads.OpenBestAvailable path. Widening the signatures rather than adding parallel *At helpers is deliberate — it makes each site state which workspace it is rejecting, so none can silently keep the generic message. Behavior is unchanged for workspaces with no Dolt data; test call sites take the new argument but no assertion changes. * test(storage): cover the tombstone heal branch and its round-trip (D-8) The headline test is the round-trip: init a real Dolt workspace, hand-edit metadata.json to backend:"sqlite", watch bd list exit 1 with the heal message, apply exactly the edit that message prescribes, and confirm bd list opens the workspace with its issue intact. The message's stated alternative — deleting the "backend" field — is exercised too, so both remedies it offers are proven rather than asserted. The same test pins the fail-closed guarantee at a level a stat loop could not: metadata.json stays byte-identical and the whole embedded Dolt tree is unchanged in paths and sizes after the refusal. Around it: the ExistingDoltDataDir layout matrix (embedded and server layouts at both depths, relative and absolute dolt_data_dir, BEADS_DOLT_DATA_DIR, decoys, no workspace dir), string-level branch coverage in internal/configfile, a public OpenBestAvailable case proving beadsDir reaches the library refusal, and an explicit assertion that the no-Dolt-data branch still refuses to suggest a heal that would open an empty store. --------- Co-authored-by: Steve Yegge --- beads.go | 11 +- beads_cgo.go | 2 +- beads_nocgo.go | 2 +- cmd/bd/backend_registry_contract_test.go | 4 +- cmd/bd/backend_support.go | 17 +- cmd/bd/bootstrap.go | 8 +- cmd/bd/bootstrap_registered_backend_test.go | 4 +- cmd/bd/doctor.go | 2 +- cmd/bd/dolt.go | 4 +- cmd/bd/init.go | 2 +- cmd/bd/legacy_upgrade_guard.go | 2 +- cmd/bd/main.go | 2 +- cmd/bd/removed_backend_heal_embedded_test.go | 282 ++++++++++++++++++ cmd/bd/store_factory.go | 4 +- cmd/bd/store_factory_nocgo.go | 4 +- .../store_selection_removed_backend_test.go | 11 +- internal/configfile/backend_messages.go | 143 ++++++++- internal/configfile/backend_messages_test.go | 219 ++++++++++++++ internal/configfile/configfile.go | 7 +- internal/storage/dolt/open.go | 12 +- open_backend_selection_test.go | 41 +++ 21 files changed, 737 insertions(+), 46 deletions(-) create mode 100644 cmd/bd/removed_backend_heal_embedded_test.go create mode 100644 internal/configfile/backend_messages_test.go diff --git a/beads.go b/beads.go index ea26654a5..83aab1b02 100644 --- a/beads.go +++ b/beads.go @@ -36,12 +36,17 @@ import ( // safe to repeat. type Storage = beads.Storage -func configuredBackendUnavailable(backend string) error { +// configuredBackendUnavailable is the public open path's fail-closed refusal for +// metadata naming a removed or unrecognized backend. beadsDir and cfg let the +// refusal detect an already-present Dolt database and name the exact +// metadata.json edit that heals the workspace, instead of the export-and- +// reinitialize path that would destroy it. +func configuredBackendUnavailable(backend, beadsDir string, cfg *configfile.Config) error { switch backend { case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite: - return configfile.RemovedBackendError(backend) + return configfile.RemovedBackendErrorAt(backend, beadsDir, cfg) default: - return configfile.UnknownBackendError(backend) + return configfile.UnknownBackendErrorAt(backend, beadsDir, cfg) } } diff --git a/beads_cgo.go b/beads_cgo.go index a43a56d46..60936982c 100644 --- a/beads_cgo.go +++ b/beads_cgo.go @@ -31,7 +31,7 @@ func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) { cfg = configfile.DefaultConfig() } if !configfile.IsSupportedBackend(cfg.Backend) { - return nil, configuredBackendUnavailable(cfg.Backend) + return nil, configuredBackendUnavailable(cfg.Backend, beadsDir, cfg) } // Dispatch to a registered extension backend before any Dolt path, mirroring diff --git a/beads_nocgo.go b/beads_nocgo.go index e63b12e5c..6867daf84 100644 --- a/beads_nocgo.go +++ b/beads_nocgo.go @@ -25,7 +25,7 @@ func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) { cfg = configfile.DefaultConfig() } if !configfile.IsSupportedBackend(cfg.Backend) { - return nil, configuredBackendUnavailable(cfg.Backend) + return nil, configuredBackendUnavailable(cfg.Backend, beadsDir, cfg) } // Dispatch to a registered extension backend before any Dolt path, mirroring diff --git a/cmd/bd/backend_registry_contract_test.go b/cmd/bd/backend_registry_contract_test.go index c9ec83cda..61f5761a1 100644 --- a/cmd/bd/backend_registry_contract_test.go +++ b/cmd/bd/backend_registry_contract_test.go @@ -43,7 +43,7 @@ func TestRegisteredBackendDispatchesReadWriteAndReadOnly(t *testing.T) { registerContractBackend(t, name) beadsDir := writeContractBackendConfig(t, name) - if err := validateConfiguredBackend(&configfile.Config{Backend: name}); err != nil { + if err := validateConfiguredBackend(&configfile.Config{Backend: name}, beadsDir); err != nil { t.Fatalf("validateConfiguredBackend() rejected registered backend: %v", err) } if _, err := newDoltStoreFromConfig(t.Context(), beadsDir); !errors.Is(err, errRegistryReadWrite) { @@ -78,7 +78,7 @@ func TestOSSRegistersNoRemovedBackends(t *testing.T) { if backends.Registered(name) { t.Errorf("OSS unexpectedly registered removed backend %q", name) } - if err := validateConfiguredBackend(&configfile.Config{Backend: name}); err == nil { + if err := validateConfiguredBackend(&configfile.Config{Backend: name}, t.TempDir()); err == nil { t.Errorf("OSS unexpectedly accepted removed backend %q", name) } } diff --git a/cmd/bd/backend_support.go b/cmd/bd/backend_support.go index 8b073efd0..6ef060c7f 100644 --- a/cmd/bd/backend_support.go +++ b/cmd/bd/backend_support.go @@ -7,7 +7,12 @@ import ( "github.com/steveyegge/beads/internal/storage/backends" ) -func validateConfiguredBackend(cfg *configfile.Config) error { +// validateConfiguredBackend fails closed on metadata that selects a removed or +// unrecognized backend. beadsDir is the workspace whose metadata cfg came from; +// the rejection inspects it (read-only) so a workspace that already holds a Dolt +// database is told to fix the stale "backend" value rather than to export and +// reinitialize. Pass "" only where there is genuinely no workspace directory. +func validateConfiguredBackend(cfg *configfile.Config, beadsDir string) error { if cfg == nil { return nil } @@ -16,11 +21,11 @@ func validateConfiguredBackend(cfg *configfile.Config) error { } switch cfg.Backend { case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite: - return configfile.RemovedBackendError(cfg.Backend) + return configfile.RemovedBackendErrorAt(cfg.Backend, beadsDir, cfg) case "", configfile.BackendDolt: return nil default: - return configfile.UnknownBackendError(cfg.Backend) + return configfile.UnknownBackendErrorAt(cfg.Backend, beadsDir, cfg) } } @@ -33,8 +38,8 @@ func registeredBackendWorkspaceIsBeadsDir(cfg *configfile.Config) bool { return backends.WorkspaceIsBeadsDir(cfg.GetBackend()) } -func requireDoltBackend(cfg *configfile.Config) error { - if err := validateConfiguredBackend(cfg); err != nil { +func requireDoltBackend(cfg *configfile.Config, beadsDir string) error { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return err } if cfg != nil && cfg.GetBackend() != configfile.BackendDolt { @@ -64,7 +69,7 @@ func loadDoltBackendConfig(beadsDir string) (*configfile.Config, error) { if cfg == nil { cfg = configfile.DefaultConfig() } - if err := requireDoltBackend(cfg); err != nil { + if err := requireDoltBackend(cfg, beadsDir); err != nil { return nil, err } return cfg, nil diff --git a/cmd/bd/bootstrap.go b/cmd/bd/bootstrap.go index 423d7dd6b..2e3f8856b 100644 --- a/cmd/bd/bootstrap.go +++ b/cmd/bd/bootstrap.go @@ -211,7 +211,7 @@ Examples: if cfg == nil { cfg = configfile.DefaultConfig() } - if err := requireBootstrapDoltBackend(cfg); err != nil { + if err := requireBootstrapDoltBackend(cfg, beadsDir); err != nil { return HandleError("%v", err) } @@ -287,8 +287,8 @@ func noWorkspaceBootstrapPayload() map[string]interface{} { } } -func requireBootstrapDoltBackend(cfg *configfile.Config) error { - if err := validateConfiguredBackend(cfg); err != nil { +func requireBootstrapDoltBackend(cfg *configfile.Config, beadsDir string) error { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return err } // A registered extension backend passes validateConfiguredBackend so its @@ -574,7 +574,7 @@ func confirmPrompt(message string, nonInteractive bool) bool { } func executeBootstrapPlan(plan BootstrapPlan, cfg *configfile.Config, nonInteractive bool) error { - if err := requireBootstrapDoltBackend(cfg); err != nil { + if err := requireBootstrapDoltBackend(cfg, plan.BeadsDir); err != nil { return err } if !confirmPrompt("Proceed?", nonInteractive) { diff --git a/cmd/bd/bootstrap_registered_backend_test.go b/cmd/bd/bootstrap_registered_backend_test.go index 8bc80aa02..170606c0b 100644 --- a/cmd/bd/bootstrap_registered_backend_test.go +++ b/cmd/bd/bootstrap_registered_backend_test.go @@ -21,7 +21,7 @@ func TestRequireBootstrapDoltBackendRejectsRegisteredBackend(t *testing.T) { const name = "registry-bootstrap" registerContractBackend(t, name) - err := requireBootstrapDoltBackend(&configfile.Config{Backend: name}) + err := requireBootstrapDoltBackend(&configfile.Config{Backend: name}, t.TempDir()) if err == nil { t.Fatal("requireBootstrapDoltBackend accepted a registered backend; want fail-closed rejection") } @@ -40,7 +40,7 @@ func TestRequireBootstrapDoltBackendRejectsRegisteredBackend(t *testing.T) { {"empty backend", &configfile.Config{}}, {"explicit dolt", &configfile.Config{Backend: configfile.BackendDolt}}, } { - if err := requireBootstrapDoltBackend(tc.cfg); err != nil { + if err := requireBootstrapDoltBackend(tc.cfg, t.TempDir()); err != nil { t.Errorf("requireBootstrapDoltBackend rejected the %s config: %v", tc.label, err) } } diff --git a/cmd/bd/doctor.go b/cmd/bd/doctor.go index 7654905b0..875a12a2d 100644 --- a/cmd/bd/doctor.go +++ b/cmd/bd/doctor.go @@ -371,7 +371,7 @@ func validateDoctorWorkspaceBackend(path string) error { if err != nil { return fmt.Errorf("failed to load %s: %w; no storage database was opened or modified; fix or restore metadata.json and retry", configfile.ConfigPath(beadsDir), err) } - return validateConfiguredBackend(cfg) + return validateConfiguredBackend(cfg, beadsDir) } // printLegacyUpgradeDiagnostic preserves doctor as a store-free repair path: diff --git a/cmd/bd/dolt.go b/cmd/bd/dolt.go index af3366959..174748254 100644 --- a/cmd/bd/dolt.go +++ b/cmd/bd/dolt.go @@ -1080,7 +1080,7 @@ endpoint via SQL and reports reachability, server version, and database.`, if cfg == nil { cfg = configfile.DefaultConfig() } - if err := validateConfiguredBackend(cfg); err != nil { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return HandleError("%v", err) } // A non-Dolt backend (SQLite or a removed-backend tombstone) has no Dolt engine; @@ -1920,7 +1920,7 @@ func showDoltConfig(testConnection bool) error { if cfg == nil { cfg = configfile.DefaultConfig() } - if err := validateConfiguredBackend(cfg); err != nil { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return HandleError("%v", err) } diff --git a/cmd/bd/init.go b/cmd/bd/init.go index dc4ee929b..19ea255a3 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -2463,7 +2463,7 @@ func checkExistingBeadsDataAt(beadsDir string, prefix string) error { return fmt.Errorf("failed to load %s: %w; refusing to reinitialize automatically (restore the metadata or use --reinit-local after safeguarding existing data)", configfile.ConfigPath(beadsDir), cfgErr) } if cfg != nil { - if guardErr := validateConfiguredBackend(cfg); guardErr != nil { + if guardErr := validateConfiguredBackend(cfg, beadsDir); guardErr != nil { return guardErr } } diff --git a/cmd/bd/legacy_upgrade_guard.go b/cmd/bd/legacy_upgrade_guard.go index 4d2e8b58f..2d6b4c579 100644 --- a/cmd/bd/legacy_upgrade_guard.go +++ b/cmd/bd/legacy_upgrade_guard.go @@ -36,7 +36,7 @@ func guardLegacyUpgradeWorkspace(beadsDir string) error { // Validate read-only discovery metadata before any caller can use Load, // which migrates legacy config.json to metadata.json. Removed and unknown // backends must fail without changing the only pointer to their data. - if err := validateConfiguredBackend(cfg); err != nil { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return err } serverMode := cfg != nil && strings.EqualFold(cfg.DoltMode, configfile.DoltModeServer) diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 84e805151..57184e778 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -1357,7 +1357,7 @@ var rootCmd = &cobra.Command{ if cfgErr != nil { return HandleError("failed to load beads config from %s: %v (refusing to fall back to the embedded store; fix or restore metadata.json and retry)", beadsDir, cfgErr) } - if backendErr := validateConfiguredBackend(cfg); backendErr != nil { + if backendErr := validateConfiguredBackend(cfg, beadsDir); backendErr != nil { return HandleError("%v", backendErr) } if readonlyMode && !backendSupportsStrictReadonly(cfg) { diff --git a/cmd/bd/removed_backend_heal_embedded_test.go b/cmd/bd/removed_backend_heal_embedded_test.go new file mode 100644 index 000000000..9f8eacbb5 --- /dev/null +++ b/cmd/bd/removed_backend_heal_embedded_test.go @@ -0,0 +1,282 @@ +//go:build cgo + +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/types" +) + +// setLegacyBackend rewrites metadata.json's "backend" field the way a stale +// pre-rollback workspace carries it, preserving every other field. +func setLegacyBackend(t *testing.T, beadsDir, backend string) { + t.Helper() + path := filepath.Join(beadsDir, configfile.ConfigFileName) + raw, err := os.ReadFile(path) // #nosec G304 -- test-controlled path + if err != nil { + t.Fatalf("read metadata.json: %v", err) + } + var fields map[string]any + if err := json.Unmarshal(raw, &fields); err != nil { + t.Fatalf("parse metadata.json: %v", err) + } + fields["backend"] = backend + updated, err := json.MarshalIndent(fields, "", " ") + if err != nil { + t.Fatalf("encode metadata.json: %v", err) + } + if err := os.WriteFile(path, updated, 0o600); err != nil { + t.Fatalf("write metadata.json: %v", err) + } +} + +// snapshotTree records the relative path and size of every file beneath root, so +// a test can prove a rejected command neither opened nor grew the Dolt database. +func snapshotTree(t *testing.T, root string) map[string]int64 { + t.Helper() + tree := map[string]int64{} + err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + rel, relErr := filepath.Rel(root, path) + if relErr != nil { + return relErr + } + if info.IsDir() { + tree[rel+"/"] = 0 + return nil + } + tree[rel] = info.Size() + return nil + }) + if err != nil { + t.Fatalf("walk %s: %v", root, err) + } + return tree +} + +// beadsDirEntries lists the names directly under .beads, skipping the advisory +// workspace-gate lock files bd creates before it reaches the backend check. +// Those are not storage, and they are the only entries a rejected run may add. +func beadsDirEntries(t *testing.T, beadsDir string) []string { + t.Helper() + entries, err := os.ReadDir(beadsDir) + if err != nil { + t.Fatalf("read %s: %v", beadsDir, err) + } + var names []string + for _, entry := range entries { + if strings.Contains(entry.Name(), ".gate.lock") { + continue + } + names = append(names, entry.Name()) + } + sort.Strings(names) + return names +} + +// runBDExpectingRejection runs bd in dir and requires it to exit 1 (the +// documented removed-backend exit code), returning the combined output. +func runBDExpectingRejection(t *testing.T, bd, dir string, args ...string) string { + t.Helper() + cmd := exec.Command(bd, args...) + cmd.Dir = dir + cmd.Env = bdEnv(dir) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("bd %s unexpectedly succeeded:\n%s", strings.Join(args, " "), out) + } + exitErr, ok := err.(*exec.ExitError) + if !ok { + t.Fatalf("bd %s failed without an exit status: %v\n%s", strings.Join(args, " "), err, out) + } + if code := exitErr.ExitCode(); code != 1 { + t.Fatalf("bd %s exit code = %d, want 1\n%s", strings.Join(args, " "), code, out) + } + return string(out) +} + +// TestRemovedBackendHealRoundTrip is the headline D-8 test: a workspace whose +// metadata.json picked up a stale legacy "backend" value still holds its Dolt +// database, so the rejection must name the exact edit that heals it — and +// following that edit verbatim must make the workspace open again with its +// issues intact. Before D-8 the message sent this user to export the data with +// an old bd release and reinitialize, destroying a live database. +func TestRemovedBackendHealRoundTrip(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") + } + + bd := buildEmbeddedBD(t) + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "heal") + created := bdCreate(t, bd, dir, "issue that must survive the rejection", "--type", "task") + + doltDir := filepath.Join(beadsDir, "embeddeddolt") + setLegacyBackend(t, beadsDir, configfile.BackendSQLite) + + metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName) + metadataBefore, err := os.ReadFile(metadataPath) // #nosec G304 -- test-controlled path + if err != nil { + t.Fatalf("read metadata.json: %v", err) + } + doltBefore := snapshotTree(t, doltDir) + entriesBefore := beadsDirEntries(t, beadsDir) + + out := runBDExpectingRejection(t, bd, dir, "list", "--json") + for _, want := range []string{ + "no longer supported", + metadataPath, + `"backend": "sqlite"`, + `"backend": "dolt"`, + doltDir, + configfile.BackendNotOpenedGuarantee, + } { + if !strings.Contains(out, want) { + t.Errorf("rejection missing %q:\n%s", want, out) + } + } + if strings.Contains(strings.ToLower(out), "export") { + t.Errorf("rejection offered the destructive export path for a workspace with live Dolt data:\n%s", out) + } + + // Fail-closed means exactly that: the refusal read the workspace and wrote + // nothing — not the metadata that named the wrong backend, not the database. + metadataAfter, err := os.ReadFile(metadataPath) // #nosec G304 -- test-controlled path + if err != nil { + t.Fatalf("read metadata.json after rejection: %v", err) + } + if !bytes.Equal(metadataAfter, metadataBefore) { + t.Errorf("rejection rewrote metadata.json:\nbefore:\n%s\nafter:\n%s", metadataBefore, metadataAfter) + } + if diff := treeDiff(doltBefore, snapshotTree(t, doltDir)); diff != "" { + t.Errorf("rejection touched the Dolt database:\n%s", diff) + } + if got := beadsDirEntries(t, beadsDir); !equalStrings(got, entriesBefore) { + t.Errorf("rejection added workspace entries: before %v, after %v", entriesBefore, got) + } + if _, statErr := os.Stat(filepath.Join(beadsDir, "beads.db")); !os.IsNotExist(statErr) { + t.Errorf("rejection provisioned a SQLite database (stat error: %v)", statErr) + } + + // Now apply exactly the edit the message prescribes. + setLegacyBackend(t, beadsDir, configfile.BackendDolt) + issues := bdListJSON(t, bd, dir) + if !containsIssue(issues, created.ID) { + t.Fatalf("after the prescribed heal, bd list does not show %s: %+v", created.ID, issues) + } + + // The message's stated alternative — dropping the field entirely — must work + // just as well, since Dolt is the default. + removeBackendField(t, beadsDir) + issues = bdListJSON(t, bd, dir) + if !containsIssue(issues, created.ID) { + t.Fatalf("after deleting the backend field, bd list does not show %s: %+v", created.ID, issues) + } +} + +// TestRemovedBackendHealRejectionPerBackend proves every removed-backend +// tombstone — not just sqlite — reaches the heal message when Dolt data is +// present. Only sqlite runs the full round-trip above; here we pin the rejection. +func TestRemovedBackendHealRejectionPerBackend(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") + } + + bd := buildEmbeddedBD(t) + for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL} { + t.Run(backend, func(t *testing.T) { + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "hl"+backend[:2]) + setLegacyBackend(t, beadsDir, backend) + + out := runBDExpectingRejection(t, bd, dir, "list", "--json") + for _, want := range []string{ + "no longer supported", + filepath.Join(beadsDir, configfile.ConfigFileName), + fmt.Sprintf(`"backend": %q`, backend), + `"backend": "dolt"`, + configfile.BackendNotOpenedGuarantee, + } { + if !strings.Contains(out, want) { + t.Errorf("%s rejection missing %q:\n%s", backend, want, out) + } + } + if strings.Contains(strings.ToLower(out), "export") { + t.Errorf("%s rejection offered the destructive export path despite live Dolt data:\n%s", backend, out) + } + }) + } +} + +// removeBackendField deletes the "backend" key from metadata.json, the +// alternative the heal message offers. +func removeBackendField(t *testing.T, beadsDir string) { + t.Helper() + path := filepath.Join(beadsDir, configfile.ConfigFileName) + raw, err := os.ReadFile(path) // #nosec G304 -- test-controlled path + if err != nil { + t.Fatalf("read metadata.json: %v", err) + } + var fields map[string]any + if err := json.Unmarshal(raw, &fields); err != nil { + t.Fatalf("parse metadata.json: %v", err) + } + delete(fields, "backend") + updated, err := json.MarshalIndent(fields, "", " ") + if err != nil { + t.Fatalf("encode metadata.json: %v", err) + } + if err := os.WriteFile(path, updated, 0o600); err != nil { + t.Fatalf("write metadata.json: %v", err) + } +} + +func containsIssue(issues []*types.IssueWithCounts, id string) bool { + for _, issue := range issues { + if issue != nil && issue.Issue != nil && issue.Issue.ID == id { + return true + } + } + return false +} + +func equalStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// treeDiff describes how two snapshots differ, or "" when they match. +func treeDiff(before, after map[string]int64) string { + var lines []string + for path, size := range after { + if prev, ok := before[path]; !ok { + lines = append(lines, "added: "+path) + } else if prev != size { + lines = append(lines, fmt.Sprintf("resized: %s (%d -> %d)", path, prev, size)) + } + } + for path := range before { + if _, ok := after[path]; !ok { + lines = append(lines, "removed: "+path) + } + } + sort.Strings(lines) + return strings.Join(lines, "\n") +} diff --git a/cmd/bd/store_factory.go b/cmd/bd/store_factory.go index 86a30af50..74c27f5a7 100644 --- a/cmd/bd/store_factory.go +++ b/cmd/bd/store_factory.go @@ -152,7 +152,7 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.Dol // metadata.json (cfg == nil, err == nil) keeps the embedded default. return nil, fmt.Errorf("load %s: %w (refusing to fall back to the embedded store)", configfile.ConfigPath(beadsDir), err) } - if err := validateConfiguredBackend(cfg); err != nil { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return nil, err } cfg = normalizeLoadedConfig(cfg) @@ -260,7 +260,7 @@ func openNonMutatingStoreFromConfig(ctx context.Context, beadsDir string, previe // "database not found" the embedded open would produce. return nil, fmt.Errorf("load %s: %w (refusing to fall back to the embedded store)", configfile.ConfigPath(beadsDir), err) } - if err := validateConfiguredBackend(cfg); err != nil { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return nil, err } cfg = normalizeLoadedConfig(cfg) diff --git a/cmd/bd/store_factory_nocgo.go b/cmd/bd/store_factory_nocgo.go index f0599fdca..3266e1aa9 100644 --- a/cmd/bd/store_factory_nocgo.go +++ b/cmd/bd/store_factory_nocgo.go @@ -75,7 +75,7 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.Dol // message below. return nil, fmt.Errorf("load %s: %w", configfile.ConfigPath(beadsDir), err) } - if err := validateConfiguredBackend(cfg); err != nil { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return nil, err } cfg = normalizeLoadedConfig(cfg) @@ -106,7 +106,7 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D if err != nil { return nil, fmt.Errorf("load %s: %w", configfile.ConfigPath(beadsDir), err) } - if err := validateConfiguredBackend(cfg); err != nil { + if err := validateConfiguredBackend(cfg, beadsDir); err != nil { return nil, err } cfg = normalizeLoadedConfig(cfg) diff --git a/cmd/bd/store_selection_removed_backend_test.go b/cmd/bd/store_selection_removed_backend_test.go index 8933cdd4b..0e16bf9d2 100644 --- a/cmd/bd/store_selection_removed_backend_test.go +++ b/cmd/bd/store_selection_removed_backend_test.go @@ -378,6 +378,12 @@ func TestStoreFactoriesRemovedBackendsFailLoud(t *testing.T) { if !strings.Contains(guidance, "export") || !strings.Contains(guidance, "dolt") { t.Fatalf("error should provide safe migration guidance: %v", err) } + // With no Dolt data on disk the configured database really is + // the only copy, so the export path is right and the D-8 heal + // must not be offered — that edit would open an empty store. + if strings.Contains(guidance, "to heal") { + t.Fatalf("error offered a metadata heal for a workspace with no Dolt data: %v", err) + } for _, name := range []string{"embeddeddolt", "dolt", "beads.db"} { path := filepath.Join(beadsDir, name) if _, statErr := os.Stat(path); !os.IsNotExist(statErr) { @@ -391,14 +397,15 @@ func TestStoreFactoriesRemovedBackendsFailLoud(t *testing.T) { } func TestRequireDoltBackend(t *testing.T) { + beadsDir := t.TempDir() for _, cfg := range []*configfile.Config{nil, {}, {Backend: configfile.BackendDolt}} { - if err := requireDoltBackend(cfg); err != nil { + if err := requireDoltBackend(cfg, beadsDir); err != nil { t.Fatalf("Dolt config %#v rejected: %v", cfg, err) } } for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} { - err := requireDoltBackend(&configfile.Config{Backend: backend}) + err := requireDoltBackend(&configfile.Config{Backend: backend}, beadsDir) if err == nil || !strings.Contains(err.Error(), "no longer supported") || !strings.Contains(err.Error(), "export") { t.Fatalf("removed backend %q guard error = %v, want rollback and migration guidance", backend, err) } diff --git a/internal/configfile/backend_messages.go b/internal/configfile/backend_messages.go index 74dba9310..68b48bb4c 100644 --- a/internal/configfile/backend_messages.go +++ b/internal/configfile/backend_messages.go @@ -1,12 +1,24 @@ package configfile -import "fmt" +import ( + "fmt" + "os" + "path/filepath" +) // This file is the single source of truth for the user-facing removed-backend // and unknown-backend messages. cmd/bd, the public beads package, and the Dolt // store must all fail closed with the same text, so the wording is deliberately -// centralized here. The framing of these messages is pending a separate -// maintainer decision — reword them here, in one place, once that lands. +// centralized here. +// +// Rejection is fail-closed and stays that way: bd never rewrites metadata.json +// on an open path. But a workspace whose metadata names a removed backend often +// holds a live Dolt database — bd v1.2.x opened these workspaces as Dolt no +// matter what the "backend" field said, so the field is the only stale thing +// about them. Sending those users down the export-and-reinitialize path would +// destroy a database that is one JSON edit from healthy, so the messages below +// branch on whether Dolt data is actually present and, when it is, name the +// exact edit instead (D-8). // RemovedBackendRationale explains why direct PostgreSQL/MySQL support was // removed. Shortened site-specific messages (e.g. bd init flag guidance) @@ -31,21 +43,134 @@ func removedBackendRationale(backend string) string { return RemovedBackendRationale } -// RemovedBackendDetail returns the shared body of every removed-backend error: -// the rationale, the untouched-data guarantee, and the migration path. Callers -// prepend a site-specific lead-in; RemovedBackendError carries the standard one. +// ExistingDoltDataDir returns the path of a Dolt database directory already +// present in the workspace beneath beadsDir, or "" when there is none. It +// checks the embedded layout (.beads/embeddeddolt) and the server-mode data dir +// (.beads/dolt by default, or the dolt_data_dir / BEADS_DOLT_DATA_DIR override, +// absolute or relative to beadsDir); under either root a database lives +// directly at /.dolt or one level down at //.dolt. +// +// It stats and reads directories only — never opens or writes storage — because +// every caller is on a rejection path that has promised not to touch the data. +// An empty beadsDir returns "", so callers without a workspace directory fall +// back to the generic message. +// +// The detection approach is ported from PR #4740 by Steve Yegge. +func ExistingDoltDataDir(beadsDir string, cfg *Config) string { + if beadsDir == "" { + return "" + } + + doltDir := filepath.Join(beadsDir, "dolt") + if custom := cfg.GetDoltDataDir(); custom != "" { + if filepath.IsAbs(custom) { + doltDir = custom + } else { + doltDir = filepath.Join(beadsDir, custom) + } + } + + for _, root := range []string{filepath.Join(beadsDir, "embeddeddolt"), doltDir} { + if isDoltRepository(root) { + return root + } + entries, err := os.ReadDir(root) + if err != nil { + continue + } + for _, entry := range entries { + if !entry.IsDir() { + continue + } + if db := filepath.Join(root, entry.Name()); isDoltRepository(db) { + return db + } + } + } + return "" +} + +// isDoltRepository reports whether dir is a Dolt database root, i.e. holds a +// .dolt directory. +func isDoltRepository(dir string) bool { + info, err := os.Stat(filepath.Join(dir, ".dolt")) + return err == nil && info.IsDir() +} + +// RemovedBackendDetail returns the shared body of a removed-backend error for a +// caller with no workspace directory to inspect: the rationale, the +// untouched-data guarantee, and the export/reinitialize recovery path. Callers +// that know the workspace should use RemovedBackendDetailAt, which can offer the +// metadata heal when the workspace already holds Dolt data. func RemovedBackendDetail(backend string) string { - return fmt.Sprintf("%s; the configured %s database was not opened or modified; export it with a bd version that supports %s, then follow bd help init-safety to reinitialize with Dolt and import the exported data", removedBackendRationale(backend), backend, backend) + return removedBackendRecoveryDetail(backend, "") +} + +// RemovedBackendDetailAt returns the body of a removed-backend error for a known +// workspace: the metadata heal when beadsDir already holds a Dolt database, and +// the export/reinitialize recovery path otherwise. Callers prepend a +// site-specific lead-in; RemovedBackendErrorAt carries the standard one. +func RemovedBackendDetailAt(backend, beadsDir string, cfg *Config) string { + if doltDir := ExistingDoltDataDir(beadsDir, cfg); doltDir != "" { + return removedBackendHealDetail(backend, beadsDir, doltDir) + } + return removedBackendRecoveryDetail(backend, beadsDir) +} + +// removedBackendHealDetail is the branch for a workspace that already has Dolt +// data: the stale metadata value is the whole problem, so the message names the +// exact edit that fixes it rather than a destructive rebuild. +func removedBackendHealDetail(backend, beadsDir, doltDir string) string { + return fmt.Sprintf("%s; however, this workspace already has a Dolt database at %s, and bd v1.2.x opened workspaces like this as Dolt — the stale \"backend\" value is the only problem; to heal, edit %s and change \"backend\": %q to \"backend\": %q (or delete the \"backend\" field entirely; Dolt is the default), then rerun the command; %s", + removedBackendRationale(backend), doltDir, ConfigPath(beadsDir), + backend, BackendDolt, BackendNotOpenedGuarantee) +} + +// removedBackendRecoveryDetail is the branch for a workspace with no Dolt data: +// the configured database really is the only copy, so recovery runs through an +// export from a bd release that still has the backend. +func removedBackendRecoveryDetail(backend, beadsDir string) string { + absent := "" + if beadsDir != "" { + absent = fmt.Sprintf(", and no Dolt database was found under %s", beadsDir) + } + return fmt.Sprintf("%s; the configured %s database was not opened or modified%s; to recover the data, export it to JSONL with a bd release that still includes the %s backend, then follow 'bd help init-safety' to reinitialize this workspace with Dolt and import the exported data", + removedBackendRationale(backend), backend, absent, backend) } // RemovedBackendError is the standard fail-closed error for metadata that -// selects a backend whose direct support was removed. +// selects a backend whose direct support was removed, for callers with no +// workspace directory to inspect. Prefer RemovedBackendErrorAt. func RemovedBackendError(backend string) error { return fmt.Errorf("storage backend %q is no longer supported: %s", backend, RemovedBackendDetail(backend)) } +// RemovedBackendErrorAt is RemovedBackendError for a known workspace: when +// beadsDir already holds a Dolt database the error names metadata.json as the +// one thing to fix, because that is the truth for every workspace bd v1.2.x +// opened as Dolt despite the stale "backend" value. +func RemovedBackendErrorAt(backend, beadsDir string, cfg *Config) error { + if doltDir := ExistingDoltDataDir(beadsDir, cfg); doltDir != "" { + return fmt.Errorf("storage backend %q in %s is no longer supported: %s", + backend, ConfigPath(beadsDir), removedBackendHealDetail(backend, beadsDir, doltDir)) + } + return fmt.Errorf("storage backend %q is no longer supported: %s", backend, removedBackendRecoveryDetail(backend, beadsDir)) +} + // UnknownBackendError is the standard fail-closed error for metadata that // names a backend this build does not recognize. func UnknownBackendError(backend string) error { - return fmt.Errorf("storage backend %q in metadata.json is not recognized or supported; %s; the supported backend is %q; fix or restore metadata.json and retry", backend, BackendNotOpenedGuarantee, BackendDolt) + return UnknownBackendErrorAt(backend, "", nil) +} + +// UnknownBackendErrorAt is UnknownBackendError enriched with the metadata heal +// when the workspace already holds a Dolt database — the same truth the +// removed-backend branch tells, for a value bd never recognized at all. +func UnknownBackendErrorAt(backend, beadsDir string, cfg *Config) error { + remedy := "fix or restore metadata.json and retry" + if doltDir := ExistingDoltDataDir(beadsDir, cfg); doltDir != "" { + remedy = fmt.Sprintf("a Dolt database exists at %s — edit %s and set \"backend\": %q (or delete the \"backend\" field), then rerun", + doltDir, ConfigPath(beadsDir), BackendDolt) + } + return fmt.Errorf("storage backend %q in metadata.json is not recognized or supported; %s; the supported backend is %q; %s", backend, BackendNotOpenedGuarantee, BackendDolt, remedy) } diff --git a/internal/configfile/backend_messages_test.go b/internal/configfile/backend_messages_test.go new file mode 100644 index 000000000..dc2c5dddd --- /dev/null +++ b/internal/configfile/backend_messages_test.go @@ -0,0 +1,219 @@ +package configfile + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// plantDoltRepository creates the .dolt marker that makes dir look like a Dolt +// database root, creating parents as needed, and returns dir. +func plantDoltRepository(t *testing.T, dir string) string { + t.Helper() + if err := os.MkdirAll(filepath.Join(dir, ".dolt"), 0o755); err != nil { + t.Fatalf("plant dolt repository at %s: %v", dir, err) + } + return dir +} + +// TestExistingDoltDataDir covers the layouts a workspace's Dolt data can live +// in. Detection drives the removed-backend message's branch, so a miss sends a +// user with a live database down the destructive export/reinitialize path. +func TestExistingDoltDataDir(t *testing.T) { + // Each case seeds a workspace and returns the config to detect with plus the + // directory detection must find ("" for none). + tests := []struct { + name string + setup func(t *testing.T, beadsDir string) (*Config, string) + }{ + { + name: "embedded layout, database one level down", + setup: func(t *testing.T, beadsDir string) (*Config, string) { + return &Config{}, plantDoltRepository(t, filepath.Join(beadsDir, "embeddeddolt", "beads")) + }, + }, + { + name: "embedded layout, database at the root", + setup: func(t *testing.T, beadsDir string) (*Config, string) { + return &Config{}, plantDoltRepository(t, filepath.Join(beadsDir, "embeddeddolt")) + }, + }, + { + name: "server layout at the root", + setup: func(t *testing.T, beadsDir string) (*Config, string) { + return &Config{}, plantDoltRepository(t, filepath.Join(beadsDir, "dolt")) + }, + }, + { + name: "server layout, database one level down", + setup: func(t *testing.T, beadsDir string) (*Config, string) { + return &Config{}, plantDoltRepository(t, filepath.Join(beadsDir, "dolt", "beads")) + }, + }, + { + name: "relative dolt_data_dir", + setup: func(t *testing.T, beadsDir string) (*Config, string) { + return &Config{DoltDataDir: "custom-data"}, plantDoltRepository(t, filepath.Join(beadsDir, "custom-data", "beads")) + }, + }, + { + name: "absolute dolt_data_dir", + setup: func(t *testing.T, _ string) (*Config, string) { + dir := plantDoltRepository(t, filepath.Join(t.TempDir(), "elsewhere")) + return &Config{DoltDataDir: dir}, dir + }, + }, + { + name: "BEADS_DOLT_DATA_DIR overrides the configured data dir", + setup: func(t *testing.T, _ string) (*Config, string) { + dir := plantDoltRepository(t, filepath.Join(t.TempDir(), "env-data")) + t.Setenv("BEADS_DOLT_DATA_DIR", dir) + return &Config{DoltDataDir: "ignored-when-env-is-set"}, dir + }, + }, + { + name: "nil config still finds the default layouts", + setup: func(t *testing.T, beadsDir string) (*Config, string) { + return nil, plantDoltRepository(t, filepath.Join(beadsDir, "dolt")) + }, + }, + { + name: "nothing present", + setup: func(t *testing.T, beadsDir string) (*Config, string) { + // A directory without a .dolt marker is not a database, a .dolt + // that is a regular file is not one either, and neither is a + // data-dir root that is itself a file. + if err := os.MkdirAll(filepath.Join(beadsDir, "embeddeddolt", "beads"), 0o755); err != nil { + t.Fatalf("create decoy database dir: %v", err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "embeddeddolt", "beads", ".dolt"), []byte("not a dir"), 0o600); err != nil { + t.Fatalf("create decoy .dolt file: %v", err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "dolt"), []byte("not a dir"), 0o600); err != nil { + t.Fatalf("create decoy data dir file: %v", err) + } + return &Config{}, "" + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + beadsDir := t.TempDir() + cfg, want := tt.setup(t, beadsDir) + if got := ExistingDoltDataDir(beadsDir, cfg); got != want { + t.Errorf("ExistingDoltDataDir() = %q, want %q", got, want) + } + }) + } +} + +// TestExistingDoltDataDirWithoutBeadsDir pins the degradation contract: a caller +// with no workspace directory gets "" (and so the generic message) rather than +// a guess rooted at the process working directory. +func TestExistingDoltDataDirWithoutBeadsDir(t *testing.T) { + if got := ExistingDoltDataDir("", &Config{}); got != "" { + t.Errorf("ExistingDoltDataDir(\"\") = %q, want \"\"", got) + } + if got := ExistingDoltDataDir("", nil); got != "" { + t.Errorf("ExistingDoltDataDir(\"\", nil) = %q, want \"\"", got) + } +} + +// TestRemovedBackendErrorHealBranch pins the message a workspace with live Dolt +// data gets: metadata.json is the only thing wrong, so the error must name the +// file, the exact edit, and the untouched-data guarantee — and must NOT send the +// user to export and reinitialize a database that is one JSON edit from healthy. +func TestRemovedBackendErrorHealBranch(t *testing.T) { + for _, backend := range []string{BackendSQLite, BackendPostgres, BackendMySQL} { + t.Run(backend, func(t *testing.T) { + beadsDir := t.TempDir() + doltDir := plantDoltRepository(t, filepath.Join(beadsDir, "embeddeddolt", "beads")) + + message := RemovedBackendErrorAt(backend, beadsDir, &Config{Backend: backend}).Error() + for _, want := range []string{ + "no longer supported", + removedBackendRationale(backend), + doltDir, + ConfigPath(beadsDir), + `"backend": "` + backend + `"`, + `"backend": "dolt"`, + BackendNotOpenedGuarantee, + } { + if !strings.Contains(message, want) { + t.Errorf("heal-branch message missing %q:\n%s", want, message) + } + } + if strings.Contains(strings.ToLower(message), "export") { + t.Errorf("heal-branch message must not offer the destructive export path:\n%s", message) + } + }) + } +} + +// TestRemovedBackendErrorRecoveryBranch pins the no-Dolt-data message: the +// configured database really is the only copy, so the export/reinitialize path +// stays — along with every substring the existing rejection tests match on. +func TestRemovedBackendErrorRecoveryBranch(t *testing.T) { + for _, backend := range []string{BackendSQLite, BackendPostgres, BackendMySQL} { + t.Run(backend, func(t *testing.T) { + beadsDir := t.TempDir() + message := RemovedBackendErrorAt(backend, beadsDir, &Config{Backend: backend}).Error() + + wants := []string{"no longer supported", "was not opened", "export", "dolt", beadsDir, "no Dolt database was found"} + if backend == BackendSQLite { + wants = append(wants, "single engine") + } else { + wants = append(wants, "general-purpose server databases", "simple and resource-light") + } + lowered := strings.ToLower(message) + for _, want := range wants { + if !strings.Contains(lowered, strings.ToLower(want)) { + t.Errorf("recovery-branch message missing %q:\n%s", want, message) + } + } + if strings.Contains(message, "to heal") { + t.Errorf("recovery-branch message must not offer a metadata heal when there is no Dolt data:\n%s", message) + } + }) + } +} + +// TestRemovedBackendErrorWithoutWorkspace pins the beadsDir-less fallback: the +// recovery branch without the "no Dolt database was found" clause, which is what +// the old RemovedBackendError said and what callers with no directory still get. +func TestRemovedBackendErrorWithoutWorkspace(t *testing.T) { + message := RemovedBackendError(BackendSQLite).Error() + for _, want := range []string{"no longer supported", "single engine", "was not opened", "export"} { + if !strings.Contains(message, want) { + t.Errorf("workspace-less message missing %q:\n%s", want, message) + } + } + if strings.Contains(message, "no Dolt database was found") { + t.Errorf("workspace-less message must not claim a search it never ran:\n%s", message) + } +} + +// TestUnknownBackendErrorHealBranch covers the same enrichment for a value bd +// never recognized at all: with Dolt data present, say so and name the edit. +func TestUnknownBackendErrorHealBranch(t *testing.T) { + beadsDir := t.TempDir() + doltDir := plantDoltRepository(t, filepath.Join(beadsDir, "dolt")) + + message := UnknownBackendErrorAt("mystery", beadsDir, &Config{Backend: "mystery"}).Error() + for _, want := range []string{"not recognized", BackendNotOpenedGuarantee, doltDir, ConfigPath(beadsDir), `"backend": "dolt"`} { + if !strings.Contains(message, want) { + t.Errorf("unknown-backend heal message missing %q:\n%s", want, message) + } + } + + // Without Dolt data the text is exactly today's. + plain := UnknownBackendErrorAt("mystery", t.TempDir(), &Config{Backend: "mystery"}).Error() + if plain != UnknownBackendError("mystery").Error() { + t.Errorf("unknown-backend message changed for a workspace with no Dolt data:\n got %s\nwant %s", plain, UnknownBackendError("mystery").Error()) + } + if !strings.Contains(plain, "fix or restore metadata.json and retry") { + t.Errorf("unknown-backend message lost its original remedy:\n%s", plain) + } +} diff --git a/internal/configfile/configfile.go b/internal/configfile/configfile.go index fff16210c..8df2f3890 100644 --- a/internal/configfile/configfile.go +++ b/internal/configfile/configfile.go @@ -623,11 +623,16 @@ func (c *Config) GetDoltServerTLS() bool { // When set, dolt stores its data in this directory instead of .beads/dolt/. // This is useful on WSL where the project lives on a slow NTFS mount (9P) // but dolt data can be placed on native ext4 for significantly better I/O. -// Checks BEADS_DOLT_DATA_DIR env var first, then config. +// Checks BEADS_DOLT_DATA_DIR env var first, then config. Nil-safe, like +// GetBackend: rejection paths resolve the data dir for workspaces whose config +// may not have loaded, and the env override still applies to those. func (c *Config) GetDoltDataDir() string { if d := os.Getenv("BEADS_DOLT_DATA_DIR"); d != "" { return d } + if c == nil { + return "" + } return c.DoltDataDir } diff --git a/internal/storage/dolt/open.go b/internal/storage/dolt/open.go index a79f62ea8..25e6c477c 100644 --- a/internal/storage/dolt/open.go +++ b/internal/storage/dolt/open.go @@ -80,11 +80,13 @@ func ApplyResolvedServerPort(beadsDir string, cfg *Config) { // requireDoltBackend keeps metadata-driven callers from bypassing the storage // factory and interpreting another backend's workspace as Dolt. Removed backend // identifiers deliberately remain recognizable in metadata so this check can fail -// closed instead of opening a new, empty Dolt database. -func requireDoltBackend(fileCfg *configfile.Config) error { +// closed instead of opening a new, empty Dolt database. beadsDir is the workspace +// the config came from, so the refusal can offer the metadata heal when that +// workspace already holds a Dolt database. +func requireDoltBackend(fileCfg *configfile.Config, beadsDir string) error { switch fileCfg.Backend { case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite: - return fmt.Errorf("configured storage backend %q is no longer supported and cannot be opened as Dolt: %s", fileCfg.Backend, configfile.RemovedBackendDetail(fileCfg.Backend)) + return fmt.Errorf("configured storage backend %q is no longer supported and cannot be opened as Dolt: %s", fileCfg.Backend, configfile.RemovedBackendDetailAt(fileCfg.Backend, beadsDir, fileCfg)) } if !configfile.IsSupportedBackend(fileCfg.Backend) { return fmt.Errorf("configured storage backend %q in metadata.json is not recognized and cannot be opened as Dolt; %s", fileCfg.Backend, configfile.BackendNotOpenedGuarantee) @@ -114,7 +116,7 @@ func NewFromConfigWithCLIOptions(ctx context.Context, beadsDir string, cfg *Conf if fileCfg == nil { fileCfg = configfile.DefaultConfig() } - if err := requireDoltBackend(fileCfg); err != nil { + if err := requireDoltBackend(fileCfg, beadsDir); err != nil { return nil, err } @@ -144,7 +146,7 @@ func NewFromConfigWithOptions(ctx context.Context, beadsDir string, cfg *Config) if fileCfg == nil { fileCfg = configfile.DefaultConfig() } - if err := requireDoltBackend(fileCfg); err != nil { + if err := requireDoltBackend(fileCfg, beadsDir); err != nil { return nil, err } diff --git a/open_backend_selection_test.go b/open_backend_selection_test.go index af03aaa24..1ffbaa449 100644 --- a/open_backend_selection_test.go +++ b/open_backend_selection_test.go @@ -102,6 +102,47 @@ func TestOpenBestAvailableRejectsRemovedBackends(t *testing.T) { } } +// TestOpenBestAvailableOffersHealWhenDoltDataExists covers the public open path +// for the case D-8 exists for: metadata names a removed backend, but the +// workspace holds a Dolt database that bd v1.2.x opened happily. The library +// error must carry the same metadata heal the CLI gives — proving beadsDir and +// the config reach configuredBackendUnavailable in both the cgo and non-cgo +// builds — instead of the export/reinitialize path that destroys the database. +func TestOpenBestAvailableOffersHealWhenDoltDataExists(t *testing.T) { + for _, backend := range []string{"postgres", "mysql", "sqlite"} { + t.Run(backend, func(t *testing.T) { + beadsDir := writeBackendMetadata(t, backend) + doltDir := filepath.Join(beadsDir, "embeddeddolt", "beads") + if err := os.MkdirAll(filepath.Join(doltDir, ".dolt"), 0o750); err != nil { + t.Fatalf("plant dolt database: %v", err) + } + + store, err := beads.OpenBestAvailable(context.Background(), beadsDir) + if store != nil { + _ = store.Close() + t.Fatalf("removed backend %q returned a store", backend) + } + if err == nil { + t.Fatal("removed backend with live Dolt data unexpectedly opened") + } + for _, want := range []string{ + "no longer supported", + filepath.Join(beadsDir, "metadata.json"), + `"backend": "dolt"`, + doltDir, + "no storage database was opened or modified", + } { + if !strings.Contains(err.Error(), want) { + t.Errorf("public open error missing %q: %v", want, err) + } + } + if strings.Contains(strings.ToLower(err.Error()), "export") { + t.Errorf("public open error offered the destructive export path despite live Dolt data: %v", err) + } + }) + } +} + func TestOpenBestAvailableRejectsUnknownBackend(t *testing.T) { beadsDir := writeBackendMetadata(t, "mystery") store, err := beads.OpenBestAvailable(context.Background(), beadsDir)