fix(config,dolt): infer server mode from a configured non-localhost host (GH#3545, GH#3518) (#5276)

An already-initialized project that later gets a remote BEADS_DOLT_SERVER_HOST
or dolt.host configured, but never sets dolt_mode/BEADS_DOLT_SERVER_MODE,
silently falls through to embedded storage at runtime instead of talking to
the configured server. bd init's guard (#3533) only protects init time, not
this later-configured case.

- configfile.IsDoltServerMode now infers server mode from a non-localhost
  BEADS_DOLT_SERVER_HOST env var, a persisted metadata.json DoltServerHost,
  or config.yaml dolt.host — each gated so an explicit dolt_mode in
  metadata.json always wins over a persisted/configured host, and an
  explicit localhost/empty BEADS_DOLT_SERVER_HOST suppresses inference
  entirely (deliberate operator intent, not just "no signal"). This
  diverges from the original PR's precedence (host inference ran
  unconditionally before the dolt_mode check); here explicit metadata
  wins, matching the hard-fail review stance from the original PR
  discussion — flagging for maintainer confirmation.
- doltserver.EnsureRunningDetailed and storage/dolt's newServerMode
  connect-failure hint now recognize a non-localhost configured host and
  tell the operator to verify the external server instead of suggesting
  `bd dolt start`, which cannot help them (GH#3518).
- Adds regression tests for both, porting and extending PR #3563's
  (shaunc) test suite; one doltserver subtest is adapted because
  GetBackend() on this codebase now recognizes "sqlite" as a real
  registered backend rather than normalizing all input to "dolt".

Does not touch `bd dolt status` (already fixed on main by #3362).

Fixes #3545. Helps #3518. Supersedes #3563.


Agent-Signature: claude-fable-5-high on behalf of maphew

Co-authored-by: Shaun Cutts <shauncutts@factfiber.com>
This commit is contained in:
matt wilkie 2026-08-02 11:05:05 -07:00 • committed by GitHub
commit 8b94291538
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 760 additions and 19 deletions

View file

@ -43,6 +43,19 @@ func requireDoltBackend(cfg *configfile.Config) error {
return nil
}
// normalizeLoadedConfig substitutes the default config for an absent
// metadata.json (cfg == nil) so mode inference still runs: a remote host
// supplied via BEADS_DOLT_SERVER_HOST or config.yaml dolt.host (GH#3545)
// must select server mode even when no metadata.json exists — otherwise
// the CLI silently opens the embedded store against a remote-host
// configuration.
func normalizeLoadedConfig(cfg *configfile.Config) *configfile.Config {
if cfg == nil {
return configfile.DefaultConfig()
}
return cfg
}
func loadDoltBackendConfig(beadsDir string) (*configfile.Config, error) {
cfg, err := configfile.Load(beadsDir)
if err != nil {

View file

@ -4,10 +4,13 @@ import (
"context"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/storage"
)
@ -52,21 +55,32 @@ func isBackupAutoEnabled() bool {
// works cross-filesystem (s3://, gs://, etc.) — auto-backup's
// hardcoded file:// path can't help them.
//
// Detection bypasses Config.IsDoltServerMode() so it works correctly
// regardless of whether GH#3545's host-mode-inference fix is in
// place — the operator's intent is unambiguous from the host value
// alone.
// Detection follows the same effective-host precedence as
// configfile.GetDoltServerHost / HostImpliesServerMode (env >
// metadata.json > config.yaml, GH#3545), so a workspace whose remote
// host lives only in metadata.json is classified the same way here as
// by mode inference — the operator's intent is unambiguous from the
// effective host value alone.
func clientServerShareFilesystem() bool {
host := os.Getenv("BEADS_DOLT_SERVER_HOST")
if host == "" {
if bd := beads.FindBeadsDir(); bd != "" {
if cfg, err := configfile.Load(bd); err == nil && cfg != nil {
// An explicit dolt_mode=embedded pins local storage;
// a leftover dolt_server_host is inert then (same
// gate as HostImpliesServerMode), so local
// auto-backup stays available.
if !strings.EqualFold(cfg.DoltMode, configfile.DoltModeEmbedded) {
host = cfg.DoltServerHost
}
}
}
}
if host == "" {
// Fall back to in-struct config (config.yaml dolt.host etc.).
host = config.GetString("dolt.host")
}
switch host {
case "", "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0":
return true
}
return false
return configfile.IsLocalHostString(host)
}
// autoBackupSkipNoticeOnce ensures the "auto-backup skipped" INFO

View file

@ -773,12 +773,20 @@ required. Use this command for explicit control or diagnostics.`,
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
fileCfg, err := loadDoltBackendConfig(beadsDir)
if err != nil {
return HandleError("%v", err)
}
if !usesSQLServer() {
return HandleError("'bd dolt start' is not supported in embedded mode (no Dolt server)")
}
// A remote (non-localhost) server host means bd does not own the
// server lifecycle (GH#3545/GH#3518): starting a repo-local
// server here would write local PID/port state that shadows the
// configured remote endpoint.
if host := fileCfg.GetDoltServerHost(); !usesProxiedServer() && !configfile.IsLocalHostString(host) {
return HandleError("the configured Dolt server host is remote (%s); 'bd dolt start' only manages a local server.\nStart the server on that host, or clear dolt_server_host / dolt.host / BEADS_DOLT_SERVER_HOST to run one locally", host)
}
serverDir := doltserver.ResolveServerDir(beadsDir)
state, err := doltserver.Start(serverDir)
@ -826,12 +834,20 @@ scope cannot be established.`,
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if _, err := loadDoltBackendConfig(beadsDir); err != nil {
fileCfg, err := loadDoltBackendConfig(beadsDir)
if err != nil {
return HandleError("%v", err)
}
if !usesSQLServer() {
return HandleError("'bd dolt stop' is not supported in embedded mode (no Dolt server)")
}
// Same remote-host ownership guard as 'bd dolt start': with a
// remote server host, the repo-local PID state (if any) is a
// leftover, and stopping it would report success while the
// configured external server keeps running (GH#3545/GH#3518).
if host := fileCfg.GetDoltServerHost(); !usesProxiedServer() && !configfile.IsLocalHostString(host) {
return HandleError("the configured Dolt server host is remote (%s); 'bd dolt stop' only manages a local server.\nStop the server on that host, or clear dolt_server_host / dolt.host / BEADS_DOLT_SERVER_HOST to manage one locally", host)
}
force, _ := cmd.Flags().GetBool("force")
if usesProxiedServer() {

View file

@ -464,9 +464,10 @@ func loadServerModeFromBeadsDir(beadsDir string) error {
if err != nil {
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
}
// Absent metadata.json keeps the fresh-repo embedded default unless
// env/config.yaml supply a remote host (GH#3545) — inference must not
// depend on metadata existing.
cfg = normalizeLoadedConfig(cfg)
warnSharedServerEmbeddedMismatch(cfg)
psm := cfg.IsDoltProxiedServerMode()
sm := cfg.IsDoltServerMode()
@ -1185,6 +1186,14 @@ var rootCmd = &cobra.Command{
// or unknown metadata likewise must reach config validation
// instead of becoming a generic "no database" result.
dbPath = bd
} else if cfg == nil && cfgErr == nil &&
configfile.DefaultConfig().HostImpliesServerMode() {
// Metadata-less workspace whose server lives at a
// remote host named by BEADS_DOLT_SERVER_HOST or
// config.yaml (GH#3545): there is no local database
// directory to discover, so route the .beads dir as
// a server workspace instead of "no database found".
dbPath = bd
}
}
}
@ -1385,7 +1394,14 @@ var rootCmd = &cobra.Command{
// deployments that empty relic answers every query with an empty
// result set and exit 0 (false-empty), which readers misinterpret as
// "no work". Absent metadata.json (cfg == nil, cfgErr == nil) keeps
// the fresh-repo embedded default below.
// the fresh-repo embedded default below — unless env/config.yaml
// supply a remote host (GH#3545): host inference must not depend
// on metadata existing, so substitute the default config and let
// the normal mode/connection resolution run.
if cfg == nil && configfile.DefaultConfig().HostImpliesServerMode() {
logConfigDiscovery(beadsDir, "no metadata.json; host inference (GH#3545) selects server mode")
cfg = configfile.DefaultConfig()
}
if cfg != nil {
warnSharedServerEmbeddedMismatch(cfg)
doltCfg.ProxiedServer = cfg.IsDoltProxiedServerMode()

View file

@ -266,6 +266,13 @@ func runMigrateToProxiedServer(dryRun bool, idleTimeout time.Duration, shared bo
if !cfg.IsDoltServerMode() {
return HandleError("repo is not in server mode (dolt_mode=%q); this command only migrates server-mode repos", cfg.GetDoltMode())
}
// This migration only re-points the proxy at the LOCAL Dolt root;
// it does not copy data. A workspace whose server mode comes from a
// remote host (GH#3545 inference or explicit config) would silently
// switch from the remote data to an empty/stale local database.
if host := cfg.GetDoltServerHost(); !configfile.IsLocalHostString(host) {
return HandleError("the configured Dolt server host is remote (%s); this migration only re-points the proxy at the local Dolt root and would abandon the remote data.\nMigrate on the server host itself, or clear dolt_server_host / dolt.host / BEADS_DOLT_SERVER_HOST first", host)
}
if doltserver.IsSharedServerMode() {
return HandleErrorWithHint("repo is in shared-server mode", "use 'bd migrate from-shared-server-to-proxied-server'")
}

View file

@ -128,6 +128,7 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltS
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
cfg = normalizeLoadedConfig(cfg)
if backend, ok := backends.Lookup(cfg.GetBackend()); ok {
return backend.Open(ctx, beadsDir)
}
@ -230,6 +231,7 @@ func openNonMutatingStoreFromConfig(ctx context.Context, beadsDir string, previe
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
cfg = normalizeLoadedConfig(cfg)
if backend, ok := backends.Lookup(cfg.GetBackend()); ok {
return backend.OpenReadOnly(ctx, beadsDir)
}

View file

@ -58,6 +58,7 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltS
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
cfg = normalizeLoadedConfig(cfg)
if backend, ok := backends.Lookup(cfg.GetBackend()); ok {
return backend.Open(ctx, beadsDir)
}
@ -85,6 +86,7 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D
if err := validateConfiguredBackend(cfg); err != nil {
return nil, err
}
cfg = normalizeLoadedConfig(cfg)
if backend, ok := backends.Lookup(cfg.GetBackend()); ok {
return backend.OpenReadOnly(ctx, beadsDir)
}

View file

@ -313,8 +313,22 @@ const (
// Checks (in priority order):
// 1. BEADS_DOLT_SERVER_MODE=1 env var
// 2. BEADS_DOLT_SHARED_SERVER env var (shared-server implies server mode)
// 3. dolt_mode field in metadata.json (project-local, explicit)
// 4. dolt.mode in config.yaml (user-global fallback, only when metadata.json has no mode)
// 3. BEADS_DOLT_SERVER_HOST env var set to a non-localhost value (GH#3545):
// an operator who configures a remote host but forgets the mode flag
// would otherwise silently fall through to embedded storage. Setting
// the env var to an explicit localhost value (or empty string) is
// treated as a deliberate suppression of host-based inference, not
// merely "no signal" — it also suppresses the struct/config.yaml host
// inference below.
// 4. dolt_mode field in metadata.json (project-local, explicit) — always
// wins over any persisted or configured host, since it is the
// operator's explicit statement of intent.
// 5. Non-localhost DoltServerHost persisted in metadata.json (GH#3545),
// when no explicit dolt_mode is set and env didn't suppress inference.
// 6. dolt.mode in config.yaml (user-global fallback, only when
// metadata.json has no mode)
// 7. Non-localhost dolt.host in config.yaml (GH#3545), gated the same way
// as (5) — a configured host must mean server mode.
//
// Runtime env vars take precedence over persisted metadata.json to prevent
// stale dolt_mode=embedded from overriding active server intent (GH#2949).
@ -330,12 +344,77 @@ func (c *Config) IsDoltServerMode() bool {
if v := os.Getenv("BEADS_DOLT_SHARED_SERVER"); v == "1" || strings.EqualFold(v, "true") {
return true
}
// Host-based inference (GH#3545): a configured non-localhost host
// implies server mode. Centralized in HostImpliesServerMode so the
// storage-mode resolver (here) and the lifecycle resolver
// (doltserver.ResolveServerMode) cannot disagree.
if c.HostImpliesServerMode() {
return true
}
if c.DoltMode != "" {
// metadata.json has an explicit mode — respect it over config.yaml
// metadata.json has an explicit mode — respect it over any
// persisted host and over config.yaml.
return strings.ToLower(c.DoltMode) == DoltModeServer
}
// Fall back to config.yaml dolt.mode setting (no metadata.json mode set)
if mode := config.GetYamlConfig("dolt.mode"); strings.EqualFold(mode, "server") {
return strings.EqualFold(config.GetYamlConfig("dolt.mode"), "server")
}
// HostImpliesServerMode evaluates host-based server-mode inference
// (GH#3545) against the EFFECTIVE host precedence chain (env >
// metadata.json > config.yaml, mirroring GetDoltServerHost), so that a
// lower-priority host that GetDoltServerHost would ignore can never
// drive the inference. Rules, in order:
//
// - Proxied-server workspaces are exempt: IsDoltServerMode and
// IsDoltProxiedServerMode are mutually exclusive (the
// proxied-to-server migration depends on it).
// - A non-empty BEADS_DOLT_SERVER_HOST decides alone: a non-localhost
// value implies server mode even over explicit dolt_mode=embedded
// (runtime env beats stale metadata, GH#2949); an explicit
// localhost value suppresses inference from lower-priority hosts —
// matching GetDoltServerHost, which then dials locally. An EMPTY
// env value is ignored (behaves as unset), again matching
// GetDoltServerHost: treating empty as suppression would select
// embedded storage while the effective dial host stays remote —
// exactly the split-storage failure this inference fixes.
// - An explicit metadata.json dolt_mode disables inference from
// persisted/configured hosts.
// - A metadata.json dolt_server_host, when set, decides alone (a
// lower-priority config.yaml dolt.host is not consulted, matching
// GetDoltServerHost precedence).
// - An explicit config.yaml dolt.mode disables inference from the
// config.yaml dolt.host.
func (c *Config) HostImpliesServerMode() bool {
if strings.EqualFold(c.DoltMode, DoltModeProxiedServer) {
return false
}
if h := os.Getenv("BEADS_DOLT_SERVER_HOST"); h != "" {
return !IsLocalHostString(h)
}
if c.DoltMode != "" {
return false
}
if c.DoltServerHost != "" {
return !IsLocalHostString(c.DoltServerHost)
}
if config.GetYamlConfig("dolt.mode") != "" {
return false
}
if h := config.GetYamlConfig("dolt.host"); h != "" {
return !IsLocalHostString(h)
}
return false
}
// IsLocalHostString reports whether host refers to the local machine, for
// the purposes of mode inference. Mirrors the helpers in cmd/bd/dolt.go
// and internal/storage/dolt/store.go; kept private to this package to
// limit the blast radius of GH#3545's fix — consolidating the (now four)
// definitions is a separate cleanup.
func IsLocalHostString(host string) bool {
switch strings.ToLower(strings.TrimSpace(host)) {
case "", "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0":
return true
}
return false
@ -355,8 +434,16 @@ func (c *Config) IsTeamServerManaged() bool {
}
// GetDoltMode returns the Dolt connection mode, defaulting to server.
// GetDoltMode returns the EFFECTIVE mode: when no mode is persisted but
// host-based inference (GH#3545) selects server mode, it reports
// "server" so effective-context consumers (bd context, integrations)
// agree with IsDoltServerMode instead of advertising an embedded mode
// next to a remote server endpoint.
func (c *Config) GetDoltMode() string {
if c.DoltMode == "" {
if c.HostImpliesServerMode() {
return DoltModeServer
}
return DoltModeEmbedded
}
return c.DoltMode

View file

@ -396,6 +396,215 @@ func TestIsDoltServerModeEnvVar(t *testing.T) {
})
}
// TestIsDoltServerMode_HostInference_GH3545 is a regression test for
// gastownhall/beads#3545: setting BEADS_DOLT_SERVER_HOST (or dolt.host)
// to a non-localhost value MUST imply server mode. Before the fix, mode
// falls through to embedded and bd silently uses local storage instead
// of the configured external server.
//
// Explicit dolt_mode in metadata.json always wins over a persisted or
// configured host — an operator's explicit statement of intent is not
// overridden by inference.
func TestIsDoltServerMode_HostInference_GH3545(t *testing.T) {
t.Run("env var BEADS_DOLT_SERVER_HOST=non-localhost infers server mode", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
cfg := &Config{Backend: BackendDolt}
if !cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = false, want true with BEADS_DOLT_SERVER_HOST=192.0.2.10")
}
})
t.Run("env var BEADS_DOLT_SERVER_HOST=hostname infers server mode", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "dolt-primary.tailnet.example.com")
cfg := &Config{Backend: BackendDolt}
if !cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = false, want true with BEADS_DOLT_SERVER_HOST=dolt-primary.tailnet.example.com")
}
})
t.Run("env var BEADS_DOLT_SERVER_HOST=localhost does NOT infer", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "localhost")
cfg := &Config{Backend: BackendDolt}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false with BEADS_DOLT_SERVER_HOST=localhost (operator wants bd-managed local)")
}
})
t.Run("env var BEADS_DOLT_SERVER_HOST=127.0.0.1 does NOT infer", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "127.0.0.1")
cfg := &Config{Backend: BackendDolt}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false with BEADS_DOLT_SERVER_HOST=127.0.0.1")
}
})
t.Run("env var BEADS_DOLT_SERVER_HOST empty does NOT infer", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
cfg := &Config{Backend: BackendDolt}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false with empty BEADS_DOLT_SERVER_HOST")
}
})
t.Run("config.yaml dolt.host=non-localhost infers server mode", func(t *testing.T) {
// Use the in-config DoltServerHost field — this mirrors what
// GetDoltServerHost reads from config.yaml (post-#3471).
cfg := &Config{Backend: BackendDolt, DoltServerHost: "10.0.0.5"}
if !cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = false, want true with DoltServerHost=10.0.0.5")
}
})
t.Run("DoltServerHost=localhost does NOT infer", func(t *testing.T) {
cfg := &Config{Backend: BackendDolt, DoltServerHost: "localhost"}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false with DoltServerHost=localhost")
}
})
t.Run("env wins over config.yaml: env=localhost suppresses config-host inference", func(t *testing.T) {
// When env is explicitly set to localhost, the operator's
// intent overrides config — even if config has a non-
// localhost host left over from a prior context.
t.Setenv("BEADS_DOLT_SERVER_HOST", "localhost")
cfg := &Config{Backend: BackendDolt, DoltServerHost: "10.0.0.5"}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false when env=localhost overrides config-host")
}
})
t.Run("non-dolt backend does not trigger host inference", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
cfg := &Config{Backend: ""}
// Backend gate (GetBackend != BackendDolt → false) precedes
// host inference. Empty backend is normalized to dolt by
// GetBackend, so this test asserts that the gate still
// short-circuits when explicitly set to a non-dolt value
// (currently impossible via GetBackend, but the gate is the
// first check and must not be bypassed by host inference).
_ = cfg.IsDoltServerMode() // No assertion — empty backend
// resolves to dolt via GetBackend(). Documenting the gate.
})
t.Run("explicit metadata dolt_mode=embedded wins over struct host", func(t *testing.T) {
// Explicit dolt_mode in metadata.json always wins over a
// persisted host — the operator's explicit statement of
// intent is not second-guessed by host inference.
cfg := &Config{Backend: BackendDolt, DoltMode: DoltModeEmbedded, DoltServerHost: "10.0.0.5"}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false: explicit dolt_mode=embedded must win over DoltServerHost=10.0.0.5")
}
})
t.Run("config.yaml dolt.mode=embedded + env host non-localhost still infers via env", func(t *testing.T) {
// Env-host inference happens before the dolt_mode/config.yaml
// checks, so it wins regardless of what config.yaml says.
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
configDir := t.TempDir()
configYaml := filepath.Join(configDir, "config.yaml")
if err := os.WriteFile(configYaml,
[]byte("dolt.mode: embedded\n"), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DIR", configDir)
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
t.Cleanup(config.ResetForTesting)
cfg := &Config{Backend: BackendDolt}
if !cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = false, want true: env host non-localhost should infer server mode even with config.yaml dolt.mode: embedded")
}
})
t.Run("metadata localhost host masks config.yaml remote host", func(t *testing.T) {
// The inference follows the EFFECTIVE host precedence
// (GetDoltServerHost: env > metadata > config.yaml): when
// metadata supplies localhost, a lower-priority remote
// dolt.host that GetDoltServerHost would ignore must not
// drive the inference (cross-vendor review round 5).
configDir := t.TempDir()
configYaml := filepath.Join(configDir, "config.yaml")
if err := os.WriteFile(configYaml,
[]byte("dolt.host: 100.64.0.1\n"), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DIR", configDir)
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
t.Cleanup(config.ResetForTesting)
cfg := &Config{Backend: BackendDolt, DoltServerHost: "localhost"}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false: metadata localhost host must mask config.yaml remote host")
}
})
t.Run("proxied-server mode is not reclassified by env host", func(t *testing.T) {
// IsDoltServerMode and IsDoltProxiedServerMode are mutually
// exclusive; a non-local env host on a proxied workspace must
// not flip it to plain server mode (cross-vendor review P2,
// 2026-08-02: the proxied-to-server migration would otherwise
// exit "Already in server mode").
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
cfg := &Config{Backend: BackendDolt, DoltMode: DoltModeProxiedServer}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false for proxied-server workspace with non-local env host")
}
if !cfg.IsDoltProxiedServerMode() {
t.Error("IsDoltProxiedServerMode() = false, want true")
}
})
t.Run("config.yaml dolt.mode=embedded wins over config.yaml dolt.host", func(t *testing.T) {
// Like metadata's dolt_mode, ANY explicit yaml mode wins over
// yaml-host inference — an explicit "embedded" must not be
// flipped to server by a dolt.host inherited from a
// lower-priority config (cross-vendor review P1, 2026-08-02).
configDir := t.TempDir()
configYaml := filepath.Join(configDir, "config.yaml")
if err := os.WriteFile(configYaml,
[]byte("dolt.mode: embedded\ndolt.host: 100.64.0.1\n"), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DIR", configDir)
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
t.Cleanup(config.ResetForTesting)
cfg := &Config{Backend: BackendDolt}
if cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = true, want false: explicit config.yaml dolt.mode: embedded must win over dolt.host inference")
}
})
t.Run("config.yaml dolt.host=non-localhost + no metadata mode infers server mode", func(t *testing.T) {
// Deliberately do not set BEADS_DOLT_SERVER_HOST here: a
// non-empty env value would decide the inference by itself,
// and this subtest exercises the config.yaml fallback layer.
configDir := t.TempDir()
configYaml := filepath.Join(configDir, "config.yaml")
if err := os.WriteFile(configYaml,
[]byte("dolt.host: 100.64.0.1\n"), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DIR", configDir)
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
t.Cleanup(config.ResetForTesting)
cfg := &Config{Backend: BackendDolt}
if !cfg.IsDoltServerMode() {
t.Error("IsDoltServerMode() = false, want true: config.yaml dolt.host=100.64.0.1 with no metadata dolt_mode should infer server mode")
}
})
}
// TestDoltProxiedServerMode covers the IsDoltProxiedServerMode predicate and
// the GetCapabilities branch that treats proxied-server as multi-process-safe
// (the proxy daemon serializes writers).

View file

@ -174,6 +174,39 @@ func IsAutoStartDisabled() bool {
return isFalsyBool(config.GetString("dolt.auto-start"))
}
// externalNonLocalhostHost reports the configured Dolt server host when
// it is set to a non-localhost value, indicating bd is talking to a
// server it does not manage. Returns (host, true) when external,
// ("", false) otherwise.
//
// Used to branch error messages in EnsureRunning so operators with a
// non-localhost server are not told to "bd dolt start" — that command
// won't help them and reinforces a wrong mental model (GH#3518).
//
// Falls back to a zero Config when no metadata.json exists in beadsDir
// so env-only configurations (BEADS_DOLT_SERVER_HOST set, no on-disk
// config) are still detected. configfile.Load error returns are treated
// as "not external" — the existing local-flavored error message is the
// safer fallback and the configfile error will surface elsewhere.
func externalNonLocalhostHost(beadsDir string) (string, bool) {
cfg, err := configfile.Load(beadsDir)
if err != nil {
return "", false
}
if cfg == nil {
cfg = &configfile.Config{}
}
if !cfg.IsDoltServerMode() {
return "", false
}
host := cfg.GetDoltServerHost()
switch strings.ToLower(strings.TrimSpace(host)) {
case "", "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0":
return "", false
}
return host, true
}
// isFalsyBool returns true when s is a recognized "false" value:
// anything strconv.ParseBool accepts as false, or "off" (case-insensitive).
// Leading/trailing whitespace is trimmed before parsing.
@ -610,6 +643,11 @@ const (
// PortSourceMetadataJSON is the deprecated metadata.json dolt_server_port
// fallback. Still an explicit user/tooling assertion, not bd bookkeeping.
PortSourceMetadataJSON PortSource = "metadata_json"
// PortSourceExternalHostDefault is the documented default port (3307)
// assumed for a host-inferred external server when no port source
// resolved (GH#3545): the user asserted a remote host, so bd fills in
// the default port rather than dialing :0 or allocating locally.
PortSourceExternalHostDefault PortSource = "external_host_default"
)
// IsAuthoritative reports whether this source represents a user (or
@ -753,6 +791,59 @@ func DefaultConfig(beadsDir string) *Config {
cfg.PortSharedServer = true
}
// Host-inferred external config (GH#3545): the server lives on
// another machine.
if cfg.Mode == ServerModeExternal {
fc := &configfile.Config{}
if _, err := os.Stat(configfile.ConfigPath(beadsDir)); err == nil {
if loaded, loadErr := configfile.Load(beadsDir); loadErr == nil && loaded != nil {
fc = loaded
}
}
if !configfile.IsLocalHostString(fc.GetDoltServerHost()) {
// The legacy BEADS_DOLT_PORT override is not in
// portSources but the storage layer honors it ahead of
// persisted sources; resolve it the same way here so
// credentials/probes and the eventual connection agree
// on the port. BEADS_DOLT_SERVER_PORT (PortSourceEnv)
// still wins over the legacy spelling.
if cfg.PortSource != PortSourceEnv {
if p, err := strconv.Atoi(strings.TrimSpace(os.Getenv("BEADS_DOLT_PORT"))); err == nil && p > 0 {
cfg.Port = p
cfg.PortSource = PortSourceEnv
}
}
// The gitignored port file is bd's bookkeeping for a
// bd-owned LOCAL server; pairing it with a remote host
// dials the remote machine on a stale local ephemeral
// port. Discard it and resume the precedence chain so
// lower-priority authoritative sources (listener.port,
// dolt.port, metadata dolt_server_port) still apply.
if cfg.PortSource == PortSourcePortFile {
cfg.Port = 0
cfg.PortSource = PortSourceUnset
for _, src := range portSources {
if src.source == PortSourcePortFile {
continue
}
if port, ok := src.resolve(beadsDir); ok {
cfg.Port = port
cfg.PortSource = src.source
cfg.PortSharedServer = sharedMode
break
}
}
}
// With no configured port, dial the documented default
// 3307, not :0 — there is no local Start() to allocate
// an ephemeral port for a remote server.
if cfg.Port == 0 {
cfg.Port = configfile.DefaultDoltServerPort
cfg.PortSource = PortSourceExternalHostDefault
}
}
}
return cfg
}
@ -860,6 +951,16 @@ func EnsureRunningDetailed(beadsDir string) (port int, startedByUs bool, err err
mode := ResolveServerMode(beadsDir)
if mode == ServerModeExternal {
cfg := DefaultConfig(beadsDir)
if host, ok := externalNonLocalhostHost(beadsDir); ok {
// Configured for a non-localhost external server:
// "bd dolt start" is not the right advice (GH#3518).
return 0, false, fmt.Errorf("Dolt server at %s:%d is unreachable, and bd will not "+
"start a local server because an external one is configured.\n\n"+
"Verify the external server is running and reachable from this host:\n"+
" nc -zv %s %d # or curl %s:%d for an HTTP-style check\n"+
" bd dolt status # detailed external-server check",
host, cfg.Port, host, cfg.Port, host, cfg.Port)
}
return 0, false, fmt.Errorf("Dolt server is not running on port %d, and auto-start is suppressed "+
"because the server is externally managed (dolt.auto-start: false or explicit port configured).\n\n"+
"Start the external server, or enable auto-start to allow bd to manage the server.\n"+
@ -872,6 +973,14 @@ func EnsureRunningDetailed(beadsDir string) (port int, startedByUs bool, err err
// somehow reached this point (e.g. stale AutoStart=true in config).
if IsAutoStartDisabled() {
cfg := DefaultConfig(beadsDir)
if host, ok := externalNonLocalhostHost(beadsDir); ok {
return 0, false, fmt.Errorf("Configured Dolt server at %s:%d is unreachable, and auto-start "+
"is disabled (dolt.auto-start: false in config.yaml or BEADS_DOLT_AUTO_START=0).\n\n"+
"This is an external server; bd will not start it. Verify it is running:\n"+
" nc -zv %s %d # or curl %s:%d for an HTTP-style check\n"+
" bd dolt status # detailed external-server check",
host, cfg.Port, host, cfg.Port, host, cfg.Port)
}
return 0, false, fmt.Errorf("Dolt server unreachable (port %d) and auto-start is disabled "+
"(dolt.auto-start: false in config.yaml or BEADS_DOLT_AUTO_START=0).\n\n"+
"Start the server manually or enable auto-start.\n"+

View file

@ -1562,6 +1562,123 @@ func TestResolveServerMode_ExplicitPort(t *testing.T) {
}
}
func TestResolveServerMode_HostInferredExternal(t *testing.T) {
// GH#3545: a non-localhost host with no explicit mode or port means
// the server lives on another machine — bd cannot own its lifecycle,
// so "bd dolt start" must not launch a repo-local server against it.
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
config.ResetForTesting()
dir := t.TempDir()
metaCfg := &configfile.Config{
DoltServerHost: "10.0.0.5",
}
if err := metaCfg.Save(dir); err != nil {
t.Fatal(err)
}
mode := ResolveServerMode(dir)
if mode != ServerModeExternal {
t.Errorf("expected ServerModeExternal with non-localhost host, got %v", mode)
}
// Host-only config must fall back to the documented default port,
// not 0 — there is no local Start() to allocate one for a remote
// server (cross-vendor review P1, 2026-08-02).
cfg := DefaultConfig(dir)
if cfg.Port != configfile.DefaultDoltServerPort {
t.Errorf("DefaultConfig.Port = %d, want %d for host-only external config", cfg.Port, configfile.DefaultDoltServerPort)
}
if cfg.PortSource != PortSourceExternalHostDefault {
t.Errorf("DefaultConfig.PortSource = %q, want %q", cfg.PortSource, PortSourceExternalHostDefault)
}
// A stale local port file (bd's bookkeeping for a bd-owned LOCAL
// server) must not be paired with the remote host (cross-vendor
// review round 4): still expect the documented default.
if err := os.WriteFile(portPath(dir), []byte("45123"), 0600); err != nil {
t.Fatal(err)
}
cfg = DefaultConfig(dir)
if cfg.Port != configfile.DefaultDoltServerPort {
t.Errorf("DefaultConfig.Port = %d, want %d: stale local port file must be ignored for a remote host", cfg.Port, configfile.DefaultDoltServerPort)
}
if err := os.Remove(portPath(dir)); err != nil {
t.Fatal(err)
}
// Localhost host stays owned.
metaCfg = &configfile.Config{
DoltServerHost: "127.0.0.1",
}
if err := metaCfg.Save(dir); err != nil {
t.Fatal(err)
}
if mode := ResolveServerMode(dir); mode != ServerModeOwned {
t.Errorf("expected ServerModeOwned with localhost host, got %v", mode)
}
}
func TestResolveServerMode_EnvHostBeatsEmbeddedMetadata(t *testing.T) {
// GH#2949 precedent applied to the host env var: a runtime remote
// host must beat stale dolt_mode=embedded metadata, and the two mode
// resolvers (IsDoltServerMode, ResolveServerMode) must agree — or
// data commands select SQL-server storage while lifecycle/port
// resolution runs embedded (cross-vendor review round 4).
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
config.ResetForTesting()
dir := t.TempDir()
metaCfg := &configfile.Config{
DoltMode: configfile.DoltModeEmbedded,
}
if err := metaCfg.Save(dir); err != nil {
t.Fatal(err)
}
if mode := ResolveServerMode(dir); mode != ServerModeExternal {
t.Errorf("expected ServerModeExternal with remote env host over embedded metadata, got %v", mode)
}
cfg := DefaultConfig(dir)
if cfg.Port != configfile.DefaultDoltServerPort {
t.Errorf("DefaultConfig.Port = %d, want %d", cfg.Port, configfile.DefaultDoltServerPort)
}
// Proxied-server workspaces are exempt, matching the inference gate.
metaCfg = &configfile.Config{
DoltMode: configfile.DoltModeProxiedServer,
}
if err := metaCfg.Save(dir); err != nil {
t.Fatal(err)
}
if mode := ResolveServerMode(dir); mode == ServerModeExternal {
t.Errorf("proxied-server workspace must not be reclassified external by env host; got %v", mode)
}
// An EMPTY env host behaves as unset (matching GetDoltServerHost,
// cross-vendor review round 6): the remote metadata host stays
// effective, so inference still fires. Suppression requires an
// explicit localhost value.
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
metaCfg = &configfile.Config{
DoltServerHost: "10.0.0.5",
}
if err := metaCfg.Save(dir); err != nil {
t.Fatal(err)
}
if mode := ResolveServerMode(dir); mode != ServerModeExternal {
t.Errorf("expected ServerModeExternal: empty env host must not mask the effective remote metadata host, got %v", mode)
}
t.Setenv("BEADS_DOLT_SERVER_HOST", "localhost")
if mode := ResolveServerMode(dir); mode != ServerModeOwned {
t.Errorf("expected ServerModeOwned with explicit localhost env override, got %v", mode)
}
}
func TestResolveServerMode_ServerModeEnv(t *testing.T) {
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "1")
@ -2395,3 +2512,111 @@ func TestEnsureGlobalDatabase_ServerNotReachable(t *testing.T) {
t.Error("expected error when server is not reachable")
}
}
// TestExternalNonLocalhostHost_GH3518 covers the helper that drives the
// host-aware error-message branching in EnsureRunning. When the
// configured Dolt server is non-localhost, EnsureRunning's "external
// server unreachable" path now suggests verifying the external server
// rather than running `bd dolt start` (which would not help).
func TestExternalNonLocalhostHost_GH3518(t *testing.T) {
t.Run("env host non-localhost returns (host, true)", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
// IsDoltServerMode now infers from non-localhost host (GH#3545)
// so we don't need to set BEADS_DOLT_SERVER_MODE here — that's
// the whole point of the sibling fix.
config.ResetForTesting()
dir := t.TempDir()
host, ok := externalNonLocalhostHost(dir)
if !ok {
t.Fatalf("externalNonLocalhostHost: ok=false, want true")
}
if host != "192.0.2.10" {
t.Errorf("host = %q, want 192.0.2.10", host)
}
})
t.Run("env host localhost returns (\"\", false)", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "localhost")
config.ResetForTesting()
dir := t.TempDir()
host, ok := externalNonLocalhostHost(dir)
if ok {
t.Errorf("externalNonLocalhostHost: ok=true, want false (host=%q)", host)
}
})
t.Run("env host 127.0.0.1 returns (\"\", false)", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "127.0.0.1")
config.ResetForTesting()
dir := t.TempDir()
_, ok := externalNonLocalhostHost(dir)
if ok {
t.Error("externalNonLocalhostHost: ok=true, want false for 127.0.0.1")
}
})
t.Run("metadata.json DoltServerHost non-localhost + dolt_mode server returns (host, true)", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
config.ResetForTesting()
dir := t.TempDir()
metaCfg := &configfile.Config{
Backend: configfile.BackendDolt,
DoltMode: configfile.DoltModeServer,
DoltServerHost: "10.0.0.5",
}
if err := metaCfg.Save(dir); err != nil {
t.Fatal(err)
}
host, ok := externalNonLocalhostHost(dir)
if !ok {
t.Fatalf("externalNonLocalhostHost: ok=false, want true")
}
if host != "10.0.0.5" {
t.Errorf("host = %q, want 10.0.0.5", host)
}
})
t.Run("no config returns (\"\", false)", func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
config.ResetForTesting()
dir := t.TempDir()
// No metadata.json — configfile.Load returns nil cfg, no error.
// (Or an error; either way, helper returns false.)
_, ok := externalNonLocalhostHost(dir)
if ok {
t.Error("externalNonLocalhostHost: ok=true, want false for empty beadsDir")
}
})
t.Run("non-server mode does NOT yield external", func(t *testing.T) {
// Force backend off-dolt to exercise the !IsDoltServerMode
// gate. On this codebase GetBackend() recognizes "sqlite" as
// a distinct registered backend (BackendSQLite), unlike the
// GH#3563 reference PR where GetBackend() normalized any
// input back to BackendDolt — so here the backend gate at
// the top of IsDoltServerMode fires and short-circuits
// *before* env-host inference is ever consulted, regardless
// of BEADS_DOLT_SERVER_HOST. Pin current behavior so future
// changes to the gate are intentional.
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
config.ResetForTesting()
dir := t.TempDir()
metaCfg := &configfile.Config{
Backend: "sqlite",
DoltMode: "embedded",
}
if err := metaCfg.Save(dir); err != nil {
t.Fatal(err)
}
host, ok := externalNonLocalhostHost(dir)
if ok {
t.Errorf("with backend=sqlite, externalNonLocalhostHost should be false (backend gate precedes host inference); got ok=true host=%q", host)
}
})
}

View file

@ -47,6 +47,7 @@ func (m ServerMode) String() string {
// Decision logic (checked in order):
// 1. BEADS_DOLT_SERVER_MODE=1 env var -> ServerModeExternal
// 2. BEADS_DOLT_SHARED_SERVER env var is set -> ServerModeExternal
// 2b. host-based inference (HostImpliesServerMode) -> ServerModeExternal
// 3. metadata.json dolt_mode == "embedded" -> ServerModeEmbedded
// 4. metadata.json has explicit dolt_server_port -> ServerModeExternal
// 5. default -> ServerModeOwned
@ -80,6 +81,21 @@ func ResolveServerMode(beadsDir string) ServerMode {
}
}
// 2b. Host-based inference (GH#3545) -> external. Uses the same
// centralized rule as IsDoltServerMode (explicit-mode gates, env
// suppression, effective-host precedence, proxied exemption) so the
// storage-mode and lifecycle resolvers cannot disagree: a server
// that lives on another machine cannot have a bd-owned lifecycle.
// Runs before the embedded-metadata check because a runtime env
// host beats stale metadata (GH#2949).
hostCfg := fileCfg
if hostCfg == nil {
hostCfg = &configfile.Config{}
}
if hostCfg.HostImpliesServerMode() {
return ServerModeExternal
}
// 3. Explicit embedded mode in metadata.json
if fileCfg != nil && strings.ToLower(fileCfg.DoltMode) == configfile.DoltModeEmbedded &&
fileCfg.DoltMode != "" { // empty defaults to embedded in GetDoltMode, but we treat empty as "unset"

View file

@ -1690,6 +1690,17 @@ func newServerMode(ctx context.Context, cfg *Config) (*DoltStore, error) {
" dolt sql-server --socket %s\n"+
"Auto-start is not supported in socket mode.",
cfg.ServerSocket, cfg.ServerSocket)
} else if isExternalServerHost(cfg.ServerHost) {
// External (non-localhost) server: bd does not
// manage it; "bd dolt start" would be wrong advice
// (GH#3518). Suggest verifying the external server
// instead.
hint = fmt.Sprintf("Configured Dolt server at %s:%d is unreachable.\n"+
"Verify the external server is running and reachable from this host:\n"+
" nc -zv %s %d # or curl %s:%d for an HTTP-style check",
cfg.ServerHost, cfg.ServerPort,
cfg.ServerHost, cfg.ServerPort,
cfg.ServerHost, cfg.ServerPort)
} else if !cfg.AutoStart && doltserver.IsAutoStartDisabled() {
hint = "Dolt server auto-start is disabled (dolt.auto-start: false).\n" +
"Start the server manually:\n bd dolt start"
@ -1958,6 +1969,20 @@ func isLocalHost(host string) bool {
return false
}
// isExternalServerHost reports whether host names a remote server for the
// purposes of connect-failure hints (GH#3518). Unlike isLocalHost it
// normalizes case/whitespace and treats 0.0.0.0 as local, matching the
// mode-inference classification in internal/configfile — the two must
// agree or an unreachable local server gets external-server advice with
// no "bd dolt start" recovery hint.
func isExternalServerHost(host string) bool {
switch strings.ToLower(strings.TrimSpace(host)) {
case "", "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0":
return false
}
return true
}
// buildServerDSN constructs a MySQL DSN for connecting to a Dolt server.
// If database is empty, connects without selecting a database (for init operations).
// Adds ReadTimeout/WriteTimeout for long-lived connection pools.