fix(storage): scope metadata.json fail-loud to store-selecting paths

Maintainer follow-up on the fail-loud contract: the hard error must fire
where a store is actually selected (store init, store factories), but the
initial patch also fataled in the two pre-run contexts that serve no-DB
commands. That bricked the repair path for the very corruption being
reported: bd doctor, bd init, bd version, bootstrap, context all exited 1
on a corrupt metadata.json, while the fatal's own message says to "fix or
restore metadata.json and retry".

- prepareSelectedCommandContext and the skipsStoreInit pre-run branch now
  warn-and-continue on a metadata load failure; data commands remain
  protected by the store-init fatal and the factory errors.
- Reword the loadServerModeFromBeadsDir error so it reads correctly in
  warn context (mode detection skipped, data commands will refuse to run).
- Drop a comment describing the now-unreachable cfgErr != nil fallthrough.
- Add an end-to-end regression test: with corrupt metadata.json, version
  and doctor run, list fails loud naming the file, bd init repairs, list
  works again with data intact. Add a nocgo variant covering the factory
  error message.

Found in maintainer review of #4366; two independent reviewers flagged
the repair-path regression.

Agent-Signature: claude-fable-5-high on behalf of matt wilkie
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
matt wilkie 2026-07-06 13:19:07 -07:00
commit 64cdff3921
3 changed files with 110 additions and 7 deletions

View file

@ -284,7 +284,7 @@ func loadServerModeFromBeadsDir(beadsDir string) error {
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
return fmt.Errorf("load %s: %w (refusing to guess the storage mode; the embedded fallback would mask server-backed data)", configfile.ConfigPath(beadsDir), err)
return fmt.Errorf("load %s: %w (storage mode unknown; data commands will refuse to run rather than fall back to the embedded store)", configfile.ConfigPath(beadsDir), err)
}
if cfg == nil {
return nil
@ -426,7 +426,11 @@ func prepareSelectedCommandContext(beadsDir string, loadEnv bool) {
}
config.CheckBeadsDirPermissions(beadsDir)
if err := loadServerModeFromBeadsDir(beadsDir); err != nil {
FatalError("%v", err)
// Warn, don't fatal: this context also serves no-DB commands —
// doctor, init, bootstrap, config — which are exactly the repair
// paths for a corrupt metadata.json. Data commands stay protected
// by the hard error at store init and in the store factories.
fmt.Fprintf(os.Stderr, "warning: %v\n", err)
}
}
@ -886,7 +890,11 @@ var rootCmd = &cobra.Command{
if beadsDir := os.Getenv("BEADS_DIR"); beadsDir == "" {
loadEnvironment()
if err := loadServerModeFromConfig(); err != nil {
FatalError("%v", err)
// Warn, don't fatal: skipsStoreInit commands (doctor,
// init, bootstrap, version, ...) never select a store,
// and several of them are the repair path for the very
// corruption being reported.
fmt.Fprintf(os.Stderr, "warning: %v\n", err)
}
}
if _, err := getDoltAutoCommitMode(); err != nil {
@ -1099,10 +1107,8 @@ var rootCmd = &cobra.Command{
cmdCtx.ServerMode = doltCfg.ServerMode
}
}
// If config parse failed (cfgErr != nil), still default the database
// name so the store-open error is about the real problem (the parse
// failure warning already printed) rather than a confusing "database
// name must not be empty" downstream.
// Defensive: embeddeddolt.New rejects an empty database name, so
// default it even on paths that never set one.
if doltCfg.Database == "" {
doltCfg.Database = configfile.DefaultDoltDatabase
}

View file

@ -0,0 +1,44 @@
//go:build !cgo
package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// The nocgo factories must also fail loud on a present-but-unloadable
// metadata.json — naming the real cause instead of the misleading
// "embedded requires CGO" fallback message.
func TestNocgoStoreFactoriesCorruptMetadataFailLoud(t *testing.T) {
beadsDir := filepath.Join(t.TempDir(), ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"dolt_mode":"serv`), 0o600); err != nil {
t.Fatalf("write corrupt metadata.json: %v", err)
}
for name, open := range map[string]func() (interface{ Close() error }, error){
"newDoltStoreFromConfig": func() (interface{ Close() error }, error) {
return newDoltStoreFromConfig(context.Background(), beadsDir)
},
"newReadOnlyStoreFromConfig": func() (interface{ Close() error }, error) {
return newReadOnlyStoreFromConfig(context.Background(), beadsDir)
},
} {
store, err := open()
if err == nil {
if store != nil {
_ = store.Close()
}
t.Fatalf("%s: want error for corrupt metadata.json, got nil", name)
}
if !strings.Contains(err.Error(), "metadata.json") {
t.Fatalf("%s: error should name metadata.json, got: %v", name, err)
}
}
}

View file

@ -5,7 +5,9 @@ package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
@ -62,6 +64,57 @@ func TestLoadServerModeFromBeadsDirCorruptMetadataReturnsError(t *testing.T) {
}
}
// End-to-end contract for a corrupt metadata.json, exercised through the
// real binary: diagnostic and repair commands still run (warn-and-continue),
// data commands fail loud instead of answering false-empty from the embedded
// fallback, and bd init can rewrite the file — after which data commands work
// again. Guards the scoping of the fail-loud behavior: fatal only where a
// store is actually selected, never on the repair path itself.
func TestCorruptMetadataDiagnosticsRunAndDataFailsLoud(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "cm")
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"dolt_mode":"serv`), 0o600); err != nil {
t.Fatalf("corrupt metadata.json: %v", err)
}
run := func(args ...string) (string, error) {
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
return string(out), err
}
// Diagnostic / repair-path commands must keep working.
for _, args := range [][]string{{"version"}, {"doctor"}} {
if out, err := run(args...); err != nil {
t.Errorf("bd %s with corrupt metadata.json: want success, got %v\n%s", strings.Join(args, " "), err, out)
}
}
// Data commands must fail loud, naming the file — not answer false-empty.
out, err := run("list", "--json")
if err == nil {
t.Fatalf("bd list with corrupt metadata.json: want loud failure, got success:\n%s", out)
}
if !strings.Contains(out, "metadata.json") {
t.Fatalf("bd list error should name metadata.json:\n%s", out)
}
// bd init is the documented repair path: it must run, rewrite the file,
// and restore data commands.
runBDInit(t, bd, dir, "--prefix", "cm")
if out, err := run("list", "--json"); err != nil {
t.Fatalf("bd list after bd init repair: %v\n%s", err, out)
}
}
// Absent metadata.json stays a legitimate fresh-repo default: no error.
func TestLoadServerModeFromBeadsDirAbsentMetadataIsFine(t *testing.T) {
beadsDir := filepath.Join(t.TempDir(), ".beads")