Fix ResolveServerMode ambient port-var handling and the KillStaleServers regression it introduced (#5934)

* test(doltserver): red — ResolveServerMode ignores BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT (refs be-9i0yq.1)

* feat(doltserver): green — ResolveServerMode honors BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT (refs be-9i0yq.1)

* test(doltserver): isolate BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT in ambient-blind tests (refs be-lbnk8)

TestResolveServerMode_Default, _EmbeddedMode, and _EmbeddedHonoredWithoutServerEnv
cleared BEADS_DOLT_SHARED_SERVER/BEADS_DOLT_SERVER_MODE via t.Setenv but never
cleared BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT, so they silently depended on
ambient absence of those two vars. That held in clean CI but not in this rig
(BEADS_DOLT_SERVER_PORT=28231 ambient), where round-1's new env-port-aware
step 2c in ResolveServerMode correctly fired and these three regressed.

servermode.go is unchanged: its precedence logic was already correct, and the
round-1 tests (EnvPortImpliesExternal, EnvPortOverridesStaleEmbedded) already
prove it. This is a test-hermeticity fix matching the isolation pattern those
two tests already follow.

* fix(doltserver): green — killStaleServersForDir ignores ambient BEADS_DOLT_SERVER_PORT (refs be-lbnk8)

killStaleServersForDir's orphan-cleanup guard (GH#2430) called the public
ResolveServerMode, which treats an ambient BEADS_DOLT_SERVER_PORT/
BEADS_DOLT_PORT (set fleet-wide on multi-agent rigs purely to route bd's
own client connections) the same as a genuine "not my server" declaration
(explicit shared-server/host/port config). That collapsed connection-
routing into lifecycle-ownership, so the guard silently skipped orphan
cleanup for directories beads still owns whenever the ambient var was set.

Split ResolveServerMode into a shared resolveServerMode(dir, honorPortEnv)
implementation:
- ResolveServerMode(dir) = resolveServerMode(dir, true) — unchanged
  behavior for all existing callers.
- resolveServerModeIgnoringPortEnv(dir) = resolveServerMode(dir, false) —
  skips only the ambient-port-var check, used solely by
  killStaleServersForDir's guard.

Audited the other three production ResolveServerMode call sites
(internal/storage/dolt/open.go:47+182, cmd/bd/bootstrap.go:914); all three
correctly want the ambient port var included (auto-start suppression and
clone-strategy selection both need to route to an already-running server),
so they are left calling the public ResolveServerMode unchanged. A fourth
call site (internal/storage/dolt/store.go:1602) already independently
short-circuits on the same env vars before it would ever reach
ResolveServerMode, so it was unaffected by construction. Audit findings
recorded in be-lbnk8's notes.

TestKillStaleServersPreservesOtherRepoServers (added in the prior round)
now passes; TestResolveServerMode_HostInferredExternal and
TestResolveServerMode_EnvHostBeatsEmbeddedMetadata remain the same two
pre-existing/unrelated failures confirmed at the parent commit (tracked
as be-wbyau).

* docs(release-gates): record be-lbnk8 gate PASS (ambient serverport scoping fix)

Deploy gate for be-mob5e (source review be-lbnk8, deploy commit
f5328d863153ecef94df9713ca2e3ed5e0ab0a95). 7/7 criteria PASS, with
two named non-blocking exceptions in the policy/lint lane (stale
.githooks/commit-msg marker check, and a stale golangci-lint
result-cache artifact referencing a deleted worktree) — both
environmental, independently verified, unrelated to the diff.

* fix(doltserver): exempt proxied-server from the port-env check, gate the carve-out

Check 2c classified any workspace with BEADS_DOLT_SERVER_PORT set as external
without either guard HostImpliesServerMode applies. The proxied-server
exemption is the one that bites: a proxied workspace reaches its server through
the proxy, so an ambient port does not describe its lifecycle, and our own
constellation runs dolt_mode: proxied-server with that variable set. 2c now
mirrors 2b's exemption.

The second HostImpliesServerMode guard -- any explicit non-empty DoltMode
suppresses inference -- is deliberately NOT mirrored, because
TestResolveServerMode_EnvPortOverridesStaleEmbedded pins the opposite for
dolt_mode=embedded on GH#2949 grounds. configfile.IsDoltServerMode has no port
check at all, so for that one combination the storage-mode and lifecycle
resolvers still disagree. That is a precedence question above this change, not
something to settle by picking whichever makes the tests green; the code says
so and it is tracked separately.

Adds TestKillStaleServersReapsOrphanUnderAmbientServerPort, the missing gate on
the resolveServerModeIgnoringPortEnv carve-out: it sets the port variable
itself rather than relying on the host exporting one, so it catches a
re-disabled GH#2430 anywhere. Red/green confirmed -- pointing the guard back at
the naive ResolveServerMode gives killed=[], want [222].

Two mode tests also stopped inheriting an ambient Dolt port.
TestResolveServerMode_EnvHostBeatsEmbeddedMetadata and
TestResolveServerMode_HostInferredExternal neutralize SHARED_SERVER,
SERVER_MODE and SERVER_HOST but never the port vars, so on a host that exports
one they asserted against it. The latter fails that way on origin/main too. The
whole internal/doltserver package now passes under this rig's real ambient
BEADS_DOLT_SERVER_PORT, which the previous body claimed and did not do.

Adds the CHANGELOG entry this user-visible auto-start change was missing.
(refs be-lbnk8)

* refactor(configfile): centralize the port-implies-server-mode rule

doltserver kept a private doltServerPortFromEnv plus an inline proxied-server
exemption -- a second copy of a rule that belongs beside HostImpliesServerMode.
Extract Config.PortImpliesServerMode with the same shape (proxied exemption,
then BEADS_DOLT_SERVER_PORT and the legacy BEADS_DOLT_PORT) and have
resolveServerMode's check 2c call it. No resolver changes behaviour.

Also corrects check 2c's doc comment, which was the actual defect the review
found rather than the code. It claimed the "explicit non-empty DoltMode
suppresses inference" guard was deliberately unmirrored and called that an
unresolved precedence question. HostImpliesServerMode does not work that way:
it reads BEADS_DOLT_SERVER_HOST at configfile.go:421-423 and can return there,
before the DoltMode suppression at :424-426 is ever reached. Real precedence is
env > explicit dolt_mode > persisted host, and 2c already mirrors every tier
with a port-side counterpart -- there is no persisted-port tier to guard,
because an explicit dolt_mode=embedded returns at check 3 before check 4 reads
metadata.json's dolt_server_port. Settled as be-yb2ai;
TestResolveServerMode_EnvPortOverridesStaleEmbedded keeps pinning it.

IsDoltServerMode deliberately does NOT consult the new predicate: it selects the
storage backend for every data command, a far wider blast radius than this
lifecycle-only change, and extending it needs its own call-site audit. The two
resolvers therefore still disagree for an unset/embedded dolt_mode plus a bare
port env var and no other server signal. That gap is documented at both sites
and owned by be-2nolj.

TestPortImpliesServerMode covers the new predicate directly: 14 cases over env
precedence, invalid/zero/negative ports, env-beats-explicit-dolt_mode, and the
proxied-server exemption including case-insensitivity. (refs be-lbnk8)

* docs(changelog): say the ambient port marks external, not "no longer suppresses auto-start"

The headline claimed an ambient BEADS_DOLT_SERVER_PORT "no longer suppresses
auto-start". This PR does the opposite: check 2c yields ServerModeExternal for
that var, resolveAutoStart (internal/storage/dolt/open.go:223) returns false on
External, and ensureServerRunning (internal/doltserver/doltserver.go:969-985)
refuses to start with "auto-start is suppressed because the server is
externally managed".

Only the reap clause was true. The headline now states both halves as they
behave, matching the entry's own body text.

Review round 3 blocking point 1 (bee-ghosttrack).

* docs(dolt): note that an ambient server port marks the workspace external

docs/architecture/dolt.md presented BEADS_DOLT_SERVER_PORT purely as the port
knob, in both the server-mode connection table and the environment-variable
table. Since check 2c it is also a lifecycle assertion: on a plain
non-shared, non-proxied workspace it resolves ServerModeExternal, so
auto-start is suppressed and PortSourceEnv -- documented at
internal/doltserver/doltserver.go:630 as an authoritative user assertion --
is unreachable for a bd-owned auto-start. A user setting it to pick a port
gets the "externally managed" refusal instead of a server.

Both sites now say so. proxied-server is called out as exempt; shared-server
already resolves external at check 2, before 2c is reached.

Review round 3 non-blocking point 2 (bee-ghosttrack).

* docs(servermode): cite GH#6181 for the IsDoltServerMode gap, not an invisible bead

Both cross-references for the deferred resolver-precedence gap pointed at
be-2nolj, an internal bead id maintainers cannot see -- the reason review
round 3 asked for a GitHub issue. bee-ghosttrack opened GH#6181
("doltserver: ResolveServerMode and configfile.IsDoltServerMode must share
one inference gate") from this review, which is exactly that tracker, so the
comments now name it.

Comment-only; no behavior change.

Review round 3 point 2 follow-up (bee-ghosttrack).

* feat: green — Fix: PR #5934's env-port check reclassifies bd's own server as shared, so it refuses to migrate (refs be-4yy5e)

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-lbnk8-serverport-ambient-scope-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jim Wordelman 2026-09-30 07:13:57 -07:00 • committed by GitHub
commit 0950db0658
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 398 additions and 12 deletions

View file

@ -9,6 +9,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **An ambient `BEADS_DOLT_SERVER_PORT` now marks a workspace externally
managed — suppressing auto-start — and no longer stops bd reaping its own
orphaned server**
([#5934](https://github.com/gastownhall/beads/pull/5934)). Setting
`BEADS_DOLT_SERVER_PORT` (or the legacy `BEADS_DOLT_PORT`) now makes
`ResolveServerMode` classify a workspace as an externally-managed server, so
bd stops trying to own a lifecycle it does not own. The stale-server cleanup
path is deliberately carved out of that rule: it keeps resolving the mode
without the port var, so bd still reaps a same-repo orphan it started
(GH#2430) instead of declining because the environment named a port. A
`proxied-server` workspace is exempt from the new rule entirely — it reaches
its server through the proxy, so an ambient port does not describe its
lifecycle.
- **`bd doctor` no longer flags a `.local_version` that starts with `v`.** The
canonical spelling of a Go module version — and the string a build stamped
from a Go pseudo-version reports and writes into `.local_version` itself —

View file

@ -204,6 +204,17 @@ Configure the connection with flags or environment variables:
| `--server-user` | `BEADS_DOLT_SERVER_USER` | `root` |
| | `BEADS_DOLT_PASSWORD` | (none) |
**`BEADS_DOLT_SERVER_PORT` also declares the server externally managed.**
Setting it — or the legacy `BEADS_DOLT_PORT` — makes `ResolveServerMode`
classify the workspace as an externally-managed server, so bd will not
auto-start a server for it: if nothing is listening on that port you get
`auto-start is suppressed because the server is externally managed` rather
than a server started on it. Use these vars to point bd at a server you
already run; they are not a way to choose the port of a bd-owned server. A
`dolt_mode: proxied-server` workspace is exempt — it reaches its server
through the proxy, so an ambient port does not describe its lifecycle — and
a shared-server workspace is already classified external on its own.
**Unix domain sockets:** Use `--server-socket` to connect via a Unix socket
instead of TCP. This avoids port conflicts between concurrent projects and is
useful in sandboxed environments (e.g., Claude Code) where file-level access
@ -565,6 +576,11 @@ dolt:
| `DOLT_REMOTE_PASSWORD` | Clone/push/pull auth password |
| `BD_DOLT_AUTO_COMMIT` | Override auto-commit setting |
**Note:** `BEADS_DOLT_SERVER_PORT` (and the legacy `BEADS_DOLT_PORT`) do more
than name a port — setting either also marks the workspace as an
externally-managed server and suppresses auto-start. See **Server Mode**
above.
### Credentials File
For multi-server setups, you can store passwords in an INI-style credentials file

View file

@ -385,6 +385,14 @@ func (c *Config) IsDoltServerMode() bool {
// persisted host and over config.yaml.
return strings.ToLower(c.DoltMode) == DoltModeServer
}
// NOTE: deliberately no PortImpliesServerMode call here. This resolver
// selects the storage backend for every data command, so honoring a bare
// BEADS_DOLT_SERVER_PORT here has a materially wider blast radius than the
// lifecycle-only question doltserver.resolveServerMode's check 2c answers.
// The two therefore still disagree for an unset/embedded dolt_mode plus a
// bare port env var and no other server signal. That gap is real, narrow
// and tracked: GH#6181 owns whether this resolver should extend to the
// port signal, after the call-site audit such a change needs.
// Fall back to config.yaml dolt.mode setting (no metadata.json mode set)
return strings.EqualFold(config.GetYamlConfig("dolt.mode"), "server")
}
@ -436,6 +444,54 @@ func (c *Config) HostImpliesServerMode() bool {
return false
}
// PortImpliesServerMode evaluates port-based server-mode inference: an
// explicitly named server port means an orchestrator is pointing this
// workspace at a server address it manages, so beads cannot own that
// server's lifecycle. Rules, in order, mirroring HostImpliesServerMode:
//
// - Proxied-server workspaces are exempt. A proxied workspace reaches its
// server through the proxy, so an ambient port does not describe its
// lifecycle and must not reclassify it.
// - Otherwise the env vars decide, BEADS_DOLT_SERVER_PORT first and the
// legacy BEADS_DOLT_PORT second, matching GetDoltServerPort's own
// precedence. A live env var in the current process outranks an explicit
// dolt_mode, exactly as the host env var does in HostImpliesServerMode --
// the env check there also runs before the DoltMode suppression and can
// return first (GH#2949: runtime env beats stale persisted metadata).
//
// There is deliberately no persisted-port tier here. HostImpliesServerMode
// suppresses its weaker persisted/config.yaml host signals on an explicit
// DoltMode; the port equivalent, metadata.json's dolt_server_port, is read by
// a later check in doltserver.resolveServerMode that an explicit
// dolt_mode=embedded already returns before. There is nothing for a
// downstream guard to protect.
//
// NOTE: IsDoltServerMode does NOT consult this predicate. See the note there.
func (c *Config) PortImpliesServerMode() bool {
if strings.EqualFold(c.DoltMode, DoltModeProxiedServer) {
return false
}
return doltServerPortFromEnv() > 0
}
// doltServerPortFromEnv returns the server port named by
// BEADS_DOLT_SERVER_PORT or, failing that, the legacy BEADS_DOLT_PORT --
// mirroring Config.GetDoltServerPort's env precedence without needing a
// loaded Config. Returns 0 when neither names a valid positive integer.
func doltServerPortFromEnv() int {
if p := os.Getenv("BEADS_DOLT_SERVER_PORT"); p != "" {
if port, err := strconv.Atoi(p); err == nil && port > 0 {
return port
}
}
if p := os.Getenv("BEADS_DOLT_PORT"); p != "" {
if port, err := strconv.Atoi(p); err == nil && port > 0 {
return port
}
}
return 0
}
// 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

View file

@ -1341,3 +1341,52 @@ func TestGlobalDoltDatabase_OmittedFromJSON(t *testing.T) {
t.Error("global_dolt_database should be omitted from JSON when empty")
}
}
// TestPortImpliesServerMode covers the predicate doltserver's check 2c
// delegates to. The precedence it encodes -- proxied exemption first, then a
// live env var outranking an explicit dolt_mode -- is deliberate and mirrors
// HostImpliesServerMode, whose own env check runs before its DoltMode
// suppression and can return first (be-yb2ai).
func TestPortImpliesServerMode(t *testing.T) {
tests := []struct {
name string
cfg *Config
serverPort string
legacyPort string
want bool
}{
{"no env, no mode", &Config{}, "", "", false},
{"BEADS_DOLT_SERVER_PORT set", &Config{}, "3307", "", true},
{"legacy BEADS_DOLT_PORT set", &Config{}, "", "3307", true},
{"SERVER_PORT wins over legacy", &Config{}, "3307", "9999", true},
{"legacy used when SERVER_PORT empty", &Config{}, "", "3307", true},
{"non-numeric port ignored", &Config{}, "notaport", "", false},
{"zero port ignored", &Config{}, "0", "", false},
{"negative port ignored", &Config{}, "-1", "", false},
{"falls back to legacy when SERVER_PORT invalid", &Config{}, "notaport", "3307", true},
// A live env var outranks an explicit dolt_mode, matching
// HostImpliesServerMode's env tier (GH#2949).
{"env beats explicit embedded", &Config{DoltMode: DoltModeEmbedded}, "3307", "", true},
{"env beats explicit server", &Config{DoltMode: DoltModeServer}, "3307", "", true},
// ...except for proxied-server, which is exempt outright: it reaches
// its server through the proxy, so an ambient port does not describe
// its lifecycle.
{"proxied-server exempt even with env port", &Config{DoltMode: DoltModeProxiedServer}, "3307", "", false},
{"proxied-server exempt, legacy port", &Config{DoltMode: DoltModeProxiedServer}, "", "3307", false},
{"proxied-server exempt, case-insensitive", &Config{DoltMode: "Proxied-Server"}, "3307", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_PORT", tt.serverPort)
t.Setenv("BEADS_DOLT_PORT", tt.legacyPort)
if got := tt.cfg.PortImpliesServerMode(); got != tt.want {
t.Errorf("PortImpliesServerMode() = %v, want %v (dolt_mode=%q SERVER_PORT=%q PORT=%q)",
got, tt.want, tt.cfg.DoltMode, tt.serverPort, tt.legacyPort)
}
})
}
}

View file

@ -1843,7 +1843,8 @@ func LockPath(beadsDir string) string {
// eligible for cleanup. Externally-managed servers are never killed.
//
// A process is considered "external" (never kill) when any of:
// - ResolveServerMode() returns ServerModeExternal (explicit port, shared server, etc.)
// - ResolveServerModeIgnoringPortEnv() returns ServerModeExternal (explicit
// port/shared server declaration, embedded, etc.)
// - No PID file exists (beads has no record of starting a server)
func killStaleServersForDir(beadsDir string, allPIDs []int, inDir func(int, string) bool, kill func(int) error) ([]int, error) {
if len(allPIDs) == 0 {
@ -1853,9 +1854,19 @@ func killStaleServersForDir(beadsDir string, allPIDs []int, inDir func(int, stri
// If auto-start is disabled the server is externally managed (e.g., by
// systemd or a manual bd dolt start), so we must not kill any processes.
// IsAutoStartDisabled covers the BEADS_DOLT_AUTO_START env var and
// dolt.auto-start config; ResolveServerMode covers explicit port/shared
// server/embedded configurations. Both indicate "not our server" (GH#2641).
if IsAutoStartDisabled() || ResolveServerMode(beadsDir) == ServerModeExternal {
// dolt.auto-start config; resolveServerModeIgnoringPortEnv covers explicit
// port/shared server/embedded configurations. Both indicate "not our
// server" (GH#2641).
//
// This deliberately uses ResolveServerModeIgnoringPortEnv, not the public
// ResolveServerMode: BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT are also set
// ambiently on multi-agent rigs purely to route bd's own client
// connections to a shared coordination server, which says nothing about
// who owns beadsDir's own local server lifecycle. Honoring that env var
// here would make this guard skip orphan cleanup for a directory beads
// still owns, defeating the GH#2430 protection below for every process
// on such a rig.
if IsAutoStartDisabled() || ResolveServerModeIgnoringPortEnv(beadsDir) == ServerModeExternal {
return nil, nil
}

View file

@ -824,6 +824,53 @@ func TestKillStaleServersPreservesOtherRepoServers(t *testing.T) {
}
}
// TestKillStaleServersReapsOrphanUnderAmbientServerPort is the regression gate
// for the ResolveServerModeIgnoringPortEnv carve-out. killStaleServersForDir
// must keep reaping a same-repo orphan (GH#2430) even when an ambient
// BEADS_DOLT_SERVER_PORT is set: without the carve-out the port var makes the
// dir resolve external, the kill path treats the server as somebody else's and
// declines to reap, and GH#2430 silently regresses.
//
// The existing TestKillStaleServersPreservesOtherRepoServers does not cover
// this -- it never sets the variable, so it only catches the regression on a
// host that happens to export one.
func TestKillStaleServersReapsOrphanUnderAmbientServerPort(t *testing.T) {
t.Setenv("BEADS_DOLT_AUTO_START", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "3308")
t.Setenv("BEADS_DOLT_PORT", "")
dir := t.TempDir()
canonicalPID := 111
sameRepoOrphanPID := 222
otherRepoPID := 333
if err := os.WriteFile(pidPath(dir), []byte(strconv.Itoa(canonicalPID)), 0600); err != nil {
t.Fatal(err)
}
var killed []int
got, err := killStaleServersForDir(
dir,
[]int{canonicalPID, sameRepoOrphanPID, otherRepoPID},
func(pid int, _ string) bool {
return pid == canonicalPID || pid == sameRepoOrphanPID
},
func(pid int) error {
killed = append(killed, pid)
return nil
},
)
if err != nil {
t.Fatalf("killStaleServersForDir error: %v", err)
}
if len(got) != 1 || got[0] != sameRepoOrphanPID {
t.Fatalf("killed=%v, want [%d] -- an ambient BEADS_DOLT_SERVER_PORT must not stop the orphan reap (GH#2430)", got, sameRepoOrphanPID)
}
if len(killed) != 1 || killed[0] != sameRepoOrphanPID {
t.Fatalf("kill callback got %v, want [%d]", killed, sameRepoOrphanPID)
}
}
func TestKillStaleServersWithoutCanonicalPIDIsNoop(t *testing.T) {
// Without a PID file, beads has no record of starting a server.
// killStaleServersForDir should be a no-op to avoid killing
@ -1554,6 +1601,8 @@ func TestDefaultConfig_SharedModeBeadsDir(t *testing.T) {
func TestResolveServerMode_Default(t *testing.T) {
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
config.ResetForTesting()
dir := t.TempDir()
@ -1601,6 +1650,13 @@ func TestResolveServerMode_HostInferredExternal(t *testing.T) {
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
// Same ambient-inheritance fix as TestResolveServerMode_EnvHostBeatsEmbeddedMetadata:
// this asserts the host-only DEFAULT port, so an inherited
// BEADS_DOLT_SERVER_PORT silently becomes the expected value's competitor.
// Pre-dates check 2c -- it fails on origin/main too, on any host that
// exports one.
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
config.ResetForTesting()
dir := t.TempDir()
@ -1662,6 +1718,15 @@ func TestResolveServerMode_EnvHostBeatsEmbeddedMetadata(t *testing.T) {
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_HOST", "192.0.2.10")
// This test is about HOST inference; the port env vars are a different
// input and must be neutralized rather than inherited. Without these two
// lines the test reads whatever the developer's shell exports: on a rig
// with BEADS_DOLT_SERVER_PORT set it failed at the DefaultConfig.Port
// assertion below (that failure predates the port-env work and reproduces
// on origin/main) and, once check 2c existed, at the proxied-server and
// localhost-override assertions too.
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
config.ResetForTesting()
dir := t.TempDir()
@ -1690,6 +1755,17 @@ func TestResolveServerMode_EnvHostBeatsEmbeddedMetadata(t *testing.T) {
if mode := ResolveServerMode(dir); mode == ServerModeExternal {
t.Errorf("proxied-server workspace must not be reclassified external by env host; got %v", mode)
}
// Same exemption, the other inference input: an ambient server port must
// not reclassify a proxied workspace either. Check 2c originally lacked
// this guard, so a proxied constellation with BEADS_DOLT_SERVER_PORT set
// -- ours -- resolved external.
func() {
t.Setenv("BEADS_DOLT_SERVER_PORT", "3308")
defer t.Setenv("BEADS_DOLT_SERVER_PORT", "")
if mode := ResolveServerMode(dir); mode == ServerModeExternal {
t.Errorf("proxied-server workspace must not be reclassified external by an ambient server port; got %v", mode)
}
}()
// An EMPTY env host behaves as unset (matching GetDoltServerHost,
// cross-vendor review round 6): the remote metadata host stays
@ -1726,6 +1802,8 @@ func TestResolveServerMode_ServerModeEnv(t *testing.T) {
func TestResolveServerMode_EmbeddedMode(t *testing.T) {
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
config.ResetForTesting()
dir := t.TempDir()
@ -1743,6 +1821,39 @@ func TestResolveServerMode_EmbeddedMode(t *testing.T) {
}
}
func TestResolveServerMode_EnvPortImpliesExternal(t *testing.T) {
// A port arriving via env var (BEADS_DOLT_SERVER_PORT or the legacy
// BEADS_DOLT_PORT) is the orchestrator's signal that the server address
// is externally managed — GetDoltServerPort() already treats both as
// first-class port signals ("orchestrator sets this"). ResolveServerMode
// must agree, or a deployment whose port arrives via env var resolves
// owned even though bd never launched the server and ensureDoltInit
// never ran for it (be-9i0yq.1).
tests := []struct {
name string
envVar string
}{
{"BEADS_DOLT_SERVER_PORT", "BEADS_DOLT_SERVER_PORT"},
{"BEADS_DOLT_PORT", "BEADS_DOLT_PORT"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
t.Setenv(tc.envVar, "13307")
config.ResetForTesting()
dir := t.TempDir()
mode := ResolveServerMode(dir)
if mode != ServerModeExternal {
t.Errorf("expected ServerModeExternal with %s set and no metadata.json, got %v", tc.envVar, mode)
}
})
}
}
func TestServerMode_String(t *testing.T) {
tests := []struct {
mode ServerMode
@ -1848,6 +1959,8 @@ func TestResolveServerMode_EmbeddedHonoredWithoutServerEnv(t *testing.T) {
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
t.Setenv("BEADS_DOLT_PORT", "")
config.ResetForTesting()
got := ResolveServerMode(beadsDir)
@ -1856,6 +1969,37 @@ func TestResolveServerMode_EmbeddedHonoredWithoutServerEnv(t *testing.T) {
}
}
func TestResolveServerMode_EnvPortOverridesStaleEmbedded(t *testing.T) {
// GH#2949 precedent applied to the port env var: a runtime
// BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT must beat stale
// dolt_mode=embedded metadata, same as the shared-server, explicit
// server-mode, and host env vars above (be-9i0yq.1).
dir := t.TempDir()
beadsDir := filepath.Join(dir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatal(err)
}
cfg := &configfile.Config{
Database: "dolt",
Backend: "dolt",
DoltMode: configfile.DoltModeEmbedded,
}
if err := cfg.Save(beadsDir); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "13307")
t.Setenv("BEADS_DOLT_PORT", "")
config.ResetForTesting()
got := ResolveServerMode(beadsDir)
if got != ServerModeExternal {
t.Errorf("ResolveServerMode with env port + stale embedded = %v, want ServerModeExternal", got)
}
}
func TestReadyTimeout(t *testing.T) {
tests := []struct {
name string

View file

@ -48,17 +48,52 @@ func (m ServerMode) String() string {
// 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
// 2c. BEADS_DOLT_SERVER_PORT / BEADS_DOLT_PORT env var -> ServerModeExternal
// 3. metadata.json dolt_mode == "embedded" -> ServerModeEmbedded
// 4. metadata.json has explicit dolt_server_port -> ServerModeExternal
// 5. default -> ServerModeOwned
//
// Runtime env vars (1, 2) take precedence over persisted metadata.json
// Runtime env vars (1, 2, 2c) take precedence over persisted metadata.json
// to prevent stale dolt_mode=embedded from silently overriding an active
// shared-server or server-mode configuration (GH#2949).
// shared-server, server-mode, or env-supplied-port configuration (GH#2949).
//
// The function loads metadata.json only if the file exists, to avoid
// triggering the legacy config.json -> metadata.json migration side effect.
func ResolveServerMode(beadsDir string) ServerMode {
return resolveServerMode(beadsDir, true)
}
// ResolveServerModeIgnoringPortEnv is ResolveServerMode with check 2c
// (BEADS_DOLT_SERVER_PORT / BEADS_DOLT_PORT) skipped.
//
// Those env vars are also set ambiently on multi-agent rigs purely to route
// bd's own client connections to a shared coordination server; setting them
// does not disclaim beads' ownership of beadsDir's own local dolt server
// process the way checks 1/2/2b (and metadata.json check 4) genuinely do.
// Callers asking "should I auto-start a server" or "which server should I
// talk to" want the full ResolveServerMode — an ambient port var correctly
// means "route there instead of spawning a redundant one". Callers asking
// "am I allowed to manage/kill OS processes for this directory's server
// lifecycle" — killStaleServersForDir's orphan-cleanup guard (GH#2430) —
// must use this instead, or the ambient routing var falsely disables
// cleanup for a directory beads still owns.
//
// Exported for internal/storage/dolt's sharedServerDatabase (GH#6169):
// once ManagesLiveServerOnPort has PROVEN bd started and tracks the live
// server on cfg.ServerPort for cfg.BeadsDir, an ambient
// BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT set purely for multi-agent
// connection routing must not override that proof and reclassify bd's own
// server as shared -- the same reasoning as the kill-guard above, applied
// to the migrate-on-open decision instead of the process-reaping one.
func ResolveServerModeIgnoringPortEnv(beadsDir string) ServerMode {
return resolveServerMode(beadsDir, false)
}
// resolveServerMode is the shared implementation behind ResolveServerMode
// and ResolveServerModeIgnoringPortEnv. honorPortEnv controls whether check
// 2c (BEADS_DOLT_SERVER_PORT / BEADS_DOLT_PORT) participates; see
// ResolveServerModeIgnoringPortEnv for why a caller would want it excluded.
func resolveServerMode(beadsDir string, honorPortEnv bool) ServerMode {
// 1. BEADS_DOLT_SERVER_MODE=1 env var -> external (explicit server mode)
if os.Getenv("BEADS_DOLT_SERVER_MODE") == "1" {
return ServerModeExternal
@ -96,6 +131,35 @@ func ResolveServerMode(beadsDir string) ServerMode {
return ServerModeExternal
}
// 2c. Explicit server port via env var (BEADS_DOLT_SERVER_PORT, then
// the legacy BEADS_DOLT_PORT) -> external. Mirrors the deprecated
// GetDoltServerPort()'s own env precedence: the orchestrator sets
// these to signal a server address it manages, port included, so
// ResolveServerMode must agree instead of defaulting a
// port-only deployment to owned (ensureDoltInit would never run for
// it). Runs before the metadata.json checks for the same GH#2949
// reason as 1/2/2b: a runtime env var beats stale persisted metadata.
//
// Skipped when honorPortEnv is false — see resolveServerModeIgnoringPortEnv.
//
// Delegates to the same centralized rule as 2b rather than keeping a
// private copy: PortImpliesServerMode is shaped like HostImpliesServerMode
// (proxied exemption, then the env vars), so the storage-mode and
// lifecycle resolvers read one definition of the port rule.
//
// That a bare port env var outranks an explicit dolt_mode is deliberate
// and settled (be-yb2ai), not an asymmetry with 2b: HostImpliesServerMode
// checks BEADS_DOLT_SERVER_HOST *before* its DoltMode suppression and can
// return on it, so the real precedence there is env > explicit dolt_mode >
// persisted host. 2c mirrors every tier that has a port-side counterpart.
// TestResolveServerMode_EnvPortOverridesStaleEmbedded pins it.
//
// configfile.IsDoltServerMode deliberately does NOT consult this predicate
// — see the note there and GH#6181.
if honorPortEnv && hostCfg.PortImpliesServerMode() {
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

@ -287,6 +287,28 @@ func TestSharedServerDatabaseOwnershipProof(t *testing.T) {
t.Fatal("nothing in bd writes dolt's config.yaml as proof of ownership")
}
})
// GH#6169 regression guard, the other direction from "env port that bd
// itself bound still migrates" above: that fix must not be over-applied.
// ResolveServerModeIgnoringPortEnv skips check 2c entirely, so taken
// alone on an unmanagedWorkspace it now falls through to its own default
// of ServerModeOwned -- it is the ManagesLiveServerOnPort proof gate
// earlier in sharedServerDatabase that must still catch this case. Mirrors
// "dolt config.yaml port without a live bd server is shared" immediately
// above, for the env source instead of the config.yaml one.
t.Run("env port at a workspace bd does not manage is still shared", func(t *testing.T) {
clearPredicateEnv(t)
t.Setenv("BEADS_DOLT_SERVER_PORT", strconv.Itoa(port))
cfg := &Config{
BeadsDir: unmanagedWorkspace(t),
ServerHost: "127.0.0.1",
ServerPort: port,
ServerPortSource: doltserver.PortSourceEnv,
}
if !sharedServerDatabase(cfg) {
t.Fatal("no bd-managed server proof for this workspace; ignoring the port env var must not turn an external server into 'owned'")
}
})
}
// TestSharedServerDatabaseThroughResolvedConfig closes the gap between the unit

View file

@ -3138,12 +3138,22 @@ func sharedServerDatabase(cfg *Config) bool {
if !doltserver.ManagesLiveServerOnPort(cfg.BeadsDir, cfg.ServerPort) {
return true
}
// Proof of a bd-managed server does not override an explicit declaration
// that the lifecycle is external (metadata dolt_server_port, host
// inference, BEADS_DOLT_SERVER_MODE). Keeping this last means the change
// above can only ever ADD shared classifications to what #5920/#6048
// already gated, never remove one.
return doltserver.ResolveServerMode(cfg.BeadsDir) != doltserver.ServerModeOwned
// Proof of a bd-managed server does not override a genuine external
// declaration (metadata dolt_server_port, host inference,
// BEADS_DOLT_SERVER_MODE, IsSharedServerMode). Keeping this last means
// the change above can only ever ADD shared classifications to what
// #5920/#6048 already gated, never remove one.
//
// Uses ResolveServerModeIgnoringPortEnv, not the public ResolveServerMode
// (GH#6169): BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT are also set
// ambiently on multi-agent rigs purely to route bd's own client
// connections to a shared coordination server, and say nothing about who
// owns cfg.BeadsDir's own server -- that question was just answered,
// above, by proof rather than inference. Honoring the ambient port env
// var here would let it override that proof and reclassify bd's own
// just-started server as shared, so a normal `bd init`/first-write on a
// multi-agent rig would refuse to migrate its own workspace database.
return doltserver.ResolveServerModeIgnoringPortEnv(cfg.BeadsDir) != doltserver.ServerModeOwned
}
func (s *DoltStore) initSchema(ctx context.Context, bootstrapHeal *schema.FreshBootstrapHealCapability) (int, error) {