From 4d3228517f0d2ca813c9552548712f64eb7e866f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 11:48:10 -0700 Subject: [PATCH 1/3] /{cmd,internal}: get debug mode working --- cmd/bd/config.go | 11 +++ cmd/bd/config_side_effects.go | 18 ++++ cmd/bd/config_side_effects_test.go | 30 ++++++ cmd/bd/doctor/gitignore.go | 3 + cmd/bd/dolt.go | 9 ++ cmd/bd/init.go | 36 ++++++- internal/config/yaml_config.go | 6 ++ internal/config/yaml_config_test.go | 18 ++++ internal/doltserver/doltserver.go | 128 +++++++++++++++++++++++-- internal/doltserver/doltserver_test.go | 72 +++++++++++++- internal/doltserver/doltserver_unix.go | 14 ++- 11 files changed, 335 insertions(+), 10 deletions(-) diff --git a/cmd/bd/config.go b/cmd/bd/config.go index fe85d4dd7..dc46706c8 100644 --- a/cmd/bd/config.go +++ b/cmd/bd/config.go @@ -71,6 +71,7 @@ Examples: bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" bd config set doctor.suppress.pending-migrations true + bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config get export.auto bd config list bd config unset jira.url`, @@ -97,6 +98,16 @@ var configSetCmd = &cobra.Command{ os.Exit(1) } + // dolt.debug only affects the managed sql-server's argv. In embedded + // mode there is no managed server, so the write would be a no-op + // (and worse, would still appear in `bd config list`). Reject + // explicitly so the user doesn't store dead config. + if key == "dolt.debug" && !usesSQLServer() { + fmt.Fprintln(os.Stderr, "Error: dolt.debug requires a sql-server-backed project (embedded mode has no managed server).") + fmt.Fprintln(os.Stderr, " To migrate: re-init with 'bd init --server' or 'bd init --shared-server'.") + os.Exit(1) + } + // Warn on unrecognized config keys so typos don't silently become // no-ops. The custom.* namespace is exempt (user-extensible). GH#3293. if !isRecognizedConfigKey(key) { diff --git a/cmd/bd/config_side_effects.go b/cmd/bd/config_side_effects.go index c4ec5654b..9876732dd 100644 --- a/cmd/bd/config_side_effects.go +++ b/cmd/bd/config_side_effects.go @@ -35,6 +35,18 @@ func checkConfigSetSideEffects(key, value string) []configSideEffect { Command: "bd dolt server stop", }) + case key == "dolt.debug" && strings.EqualFold(value, "true"): + effects = append(effects, configSideEffect{ + Message: "Debug mode will apply on the next Dolt server start (loglevel=debug, --prof cpu).", + Command: "bd dolt stop && bd dolt start", + }) + + case key == "dolt.debug" && !strings.EqualFold(value, "true"): + effects = append(effects, configSideEffect{ + Message: "Debug mode disabled. Restart the server to drop --prof and --loglevel=debug.", + Command: "bd dolt stop && bd dolt start", + }) + case key == "routing.mode": validModes := map[string]bool{"maintainer": true, "contributor": true, "auto": true, "explicit": true} if !validModes[value] { @@ -75,6 +87,12 @@ func checkConfigUnsetSideEffects(key string) []configSideEffect { Command: "bd dolt server stop", }) + case "dolt.debug": + effects = append(effects, configSideEffect{ + Message: "Debug config removed. Restart the server to drop --prof and --loglevel=debug.", + Command: "bd dolt stop && bd dolt start", + }) + case "backup.enabled": effects = append(effects, configSideEffect{ Message: "Backup config removed. Automatic backups will no longer run.", diff --git a/cmd/bd/config_side_effects_test.go b/cmd/bd/config_side_effects_test.go index 7be99c7a7..faa53db88 100644 --- a/cmd/bd/config_side_effects_test.go +++ b/cmd/bd/config_side_effects_test.go @@ -35,6 +35,36 @@ func TestCheckConfigSetSideEffects_SharedServerFalse(t *testing.T) { } } +func TestCheckConfigSetSideEffects_DoltDebugTrue(t *testing.T) { + effects := checkConfigSetSideEffects("dolt.debug", "true") + if len(effects) != 1 { + t.Fatalf("expected 1 effect, got %d", len(effects)) + } + if effects[0].Command != "bd dolt stop && bd dolt start" { + t.Errorf("expected restart command, got %q", effects[0].Command) + } +} + +func TestCheckConfigSetSideEffects_DoltDebugFalse(t *testing.T) { + effects := checkConfigSetSideEffects("dolt.debug", "false") + if len(effects) != 1 { + t.Fatalf("expected 1 effect, got %d", len(effects)) + } + if effects[0].Command != "bd dolt stop && bd dolt start" { + t.Errorf("expected restart command, got %q", effects[0].Command) + } +} + +func TestCheckConfigUnsetSideEffects_DoltDebug(t *testing.T) { + effects := checkConfigUnsetSideEffects("dolt.debug") + if len(effects) != 1 { + t.Fatalf("expected 1 effect, got %d", len(effects)) + } + if effects[0].Command != "bd dolt stop && bd dolt start" { + t.Errorf("expected restart command, got %q", effects[0].Command) + } +} + func TestCheckConfigSetSideEffects_RoutingModeInvalid(t *testing.T) { effects := checkConfigSetSideEffects("routing.mode", "bogus") if len(effects) != 1 { diff --git a/cmd/bd/doctor/gitignore.go b/cmd/bd/doctor/gitignore.go index 2f8d307ec..85746cd4b 100644 --- a/cmd/bd/doctor/gitignore.go +++ b/cmd/bd/doctor/gitignore.go @@ -59,6 +59,9 @@ dolt-server.lock dolt-server.port dolt-server.activity +# Debug-mode pprof artifacts (written when dolt.debug: true in config.yaml) +dolt-pprof/ + # Corrupt backup directories (created by bd doctor --fix recovery) *.corrupt.backup/ diff --git a/cmd/bd/dolt.go b/cmd/bd/dolt.go index a746553d9..f53c10013 100644 --- a/cmd/bd/dolt.go +++ b/cmd/bd/dolt.go @@ -436,6 +436,11 @@ required. Use this command for explicit control or diagnostics.`, if doltserver.IsSharedServerMode() { fmt.Println(" Mode: shared server") } + if doltserver.IsDebugMode() { + fmt.Println(" Debug: on (loglevel=debug, --prof cpu)") + fmt.Printf(" Profile dir: %s\n", doltserver.DebugProfileDir(beadsDir)) + fmt.Println(" Note: cpu.pprof is written when the server exits cleanly (bd dolt stop).") + } }, } @@ -549,6 +554,10 @@ func renderLocalDoltStatus(state *doltserver.State, serverDir string) { if doltserver.IsSharedServerMode() { fmt.Println(" Mode: shared server") } + if doltserver.IsDebugMode() { + fmt.Println(" Debug: on (loglevel=debug, --prof cpu)") + fmt.Printf(" Profile dir: %s\n", doltserver.DebugProfileDir(serverDir)) + } } // shouldUseExternalDoltStatus reports whether bd dolt status should treat diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 8ce381e0e..0e53a7926 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -103,6 +103,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } sharedServer, _ := cmd.Flags().GetBool("shared-server") externalServer, _ := cmd.Flags().GetBool("external") + debugMode, _ := cmd.Flags().GetBool("debug") initProxiedServer, _ := cmd.Flags().GetBool("proxied-server") serverConfigPath, _ := cmd.Flags().GetString("proxied-server-config") serverLogPath, _ := cmd.Flags().GetString("proxied-server-log-path") @@ -225,6 +226,14 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): _ = os.Setenv("BEADS_DOLT_SHARED_SERVER", "1") } + // Propagate --debug to env so IsDebugMode() returns true for the + // server start that happens later in this same init invocation + // (before config.yaml is written). Same one-shot rationale as + // the shared-server propagation above. + if debugMode { + _ = os.Setenv("BEADS_DOLT_DEBUG", "1") + } + // Reject hyphens in --database for embedded mode. Must run AFTER // serverMode is set above — otherwise !usesSQLServer() always returns // true and incorrectly rejects server-mode names (GH#3231). @@ -782,7 +791,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // ensuring the server is reachable and the port file exists. if !externalServer && (sharedServer || doltserver.IsSharedServerMode()) { if sharedDir, err := doltserver.SharedServerDir(); err == nil { - if state, _ := doltserver.IsRunning(sharedDir); state == nil || !state.Running { + state, _ := doltserver.IsRunning(sharedDir) + if state == nil || !state.Running { if _, startErr := doltserver.Start(sharedDir); startErr != nil { fmt.Fprintf(os.Stderr, "Error: failed to start shared Dolt server: %v\n", startErr) os.Exit(1) @@ -790,6 +800,14 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if !quiet { fmt.Printf(" %s Shared Dolt server started\n", ui.RenderPass("✓")) } + } else if debugMode { + // Shared server is already up — it was started without + // the debug-mode argv we just configured. Persisting + // dolt.debug will take effect on the next restart, but + // the currently-running server keeps its existing flags. + fmt.Fprintf(os.Stderr, "Warning: shared Dolt server (PID %d, port %d) is already running without debug flags.\n", state.PID, state.Port) + fmt.Fprintf(os.Stderr, " Restart to pick up debug mode:\n") + fmt.Fprintf(os.Stderr, " bd dolt stop && bd dolt start\n") } } @@ -1037,6 +1055,21 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } } + // Persist --debug intent to config.yaml so subsequent bd commands + // that auto-start the dolt sql-server pick up the debug flags + // without requiring BEADS_DOLT_DEBUG in every shell. + if debugMode { + if err := config.SetYamlConfig("dolt.debug", "true"); err != nil { + fmt.Fprintf(os.Stderr, "Warning: failed to persist dolt.debug: %v\n", err) + } else if !quiet { + serverDir := doltserver.ResolveServerDir(beadsDir) + fmt.Printf(" %s Debug mode enabled\n", ui.RenderPass("✓")) + fmt.Printf(" Server log: %s\n", doltserver.LogPath(serverDir)) + fmt.Printf(" Profile dir: %s\n", doltserver.DebugProfileDir(beadsDir)) + fmt.Printf(" Note: cpu.pprof is written when the server exits cleanly (bd dolt stop).\n") + } + } + // In stealth mode, persist no-git-ops: true so bd prime // automatically uses stealth session-close protocol (GH#2159) if stealth { @@ -1507,6 +1540,7 @@ func init() { initCmd.Flags().String("database", "", "Use existing server database name (overrides prefix-based naming)") initCmd.Flags().Bool("shared-server", false, "Enable shared Dolt server mode (all projects share one server at ~/.beads/shared-server/)") initCmd.Flags().Bool("external", false, "Server is externally managed (skip server startup); use with --shared-server or --server") + initCmd.Flags().Bool("debug", false, "Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers.") initCmd.Flags().Bool("proxied-server", false, "[EXPERIMENTAL] Use a per-workspace proxied dolt sql-server (proxy + child dolt) rooted at .beads/proxieddb") initCmd.Flags().String("proxied-server-config", "", "[EXPERIMENTAL] Path to an existing dolt sql-server YAML config (proxied-server mode only). When set, bd uses this file instead of auto-generating one.") initCmd.Flags().String("proxied-server-log-path", "", "[EXPERIMENTAL] Path to the proxied dolt sql-server log file (proxied-server mode only). Default: /proxieddb/server.log.") diff --git a/internal/config/yaml_config.go b/internal/config/yaml_config.go index 73a768c3a..4a37901b5 100644 --- a/internal/config/yaml_config.go +++ b/internal/config/yaml_config.go @@ -66,6 +66,7 @@ var YamlOnlyKeys = map[string]bool{ // Dolt server settings "dolt.shared-server": true, // Shared Dolt server at ~/.beads/shared-server/ (GH#2377) "dolt.max-conns": true, // Connection pool size override (default 10, GH#3140) + "dolt.debug": true, // Debug-mode dolt sql-server: --loglevel=debug + --prof cpu // Secrets: tokens and API keys must NOT be stored in the Dolt database // because that data is pushed to remotes, triggering secret-scanning @@ -521,6 +522,11 @@ func validateYamlConfigValue(key, value string) error { if lower != "true" && lower != "false" { return fmt.Errorf("dolt.shared-server must be \"true\" or \"false\", got %q", value) } + case "dolt.debug": + lower := strings.ToLower(value) + if lower != "true" && lower != "false" { + return fmt.Errorf("dolt.debug must be \"true\" or \"false\", got %q", value) + } } return nil } diff --git a/internal/config/yaml_config_test.go b/internal/config/yaml_config_test.go index 6f9f2c4c5..e08823e20 100644 --- a/internal/config/yaml_config_test.go +++ b/internal/config/yaml_config_test.go @@ -544,6 +544,24 @@ func TestValidateYamlConfigValue_SharedServer(t *testing.T) { } } +func TestValidateYamlConfigValue_DoltDebug(t *testing.T) { + if err := validateYamlConfigValue("dolt.debug", "true"); err != nil { + t.Errorf("expected 'true' to be valid: %v", err) + } + if err := validateYamlConfigValue("dolt.debug", "false"); err != nil { + t.Errorf("expected 'false' to be valid: %v", err) + } + if err := validateYamlConfigValue("dolt.debug", "TRUE"); err != nil { + t.Errorf("expected 'TRUE' to be valid (case-insensitive): %v", err) + } + if err := validateYamlConfigValue("dolt.debug", "maybe"); err == nil { + t.Error("expected 'maybe' to be invalid") + } + if err := validateYamlConfigValue("dolt.debug", "1"); err == nil { + t.Error("expected '1' to be invalid (not a boolean string)") + } +} + func TestIsSecretKey(t *testing.T) { tests := []struct { key string diff --git a/internal/doltserver/doltserver.go b/internal/doltserver/doltserver.go index 2eaab9c09..a92dd2393 100644 --- a/internal/doltserver/doltserver.go +++ b/internal/doltserver/doltserver.go @@ -115,6 +115,81 @@ func IsSharedServerMode() bool { return config.GetBool("dolt.shared-server") } +// IsDebugMode returns true if the dolt sql-server should be launched in +// debug mode (--loglevel=debug plus CPU profiling via --prof cpu). +// Sources (priority order): +// 1. BEADS_DOLT_DEBUG env var ("1" or "true") +// 2. dolt.debug in config.yaml +// +// Debug mode only affects servers beads spawns. External / hosted / +// auto-start-disabled servers are unaffected — operators manage those +// argv themselves. +func IsDebugMode() bool { + if v := os.Getenv("BEADS_DOLT_DEBUG"); v == "1" || strings.EqualFold(v, "true") { + return true + } + return config.GetBool("dolt.debug") +} + +// DebugProfileDir returns the directory dolt sql-server writes pprof +// artifacts into when debug mode is enabled. The path is the canonical +// location surfaced by bd init / bd dolt start / bd dolt status so users +// know where to find cpu.pprof. +// +// Layout: +// - per-project: /dolt-pprof/ +// - shared server: ~/.beads/shared-server/dolt-pprof/ +// +// The returned path is absolute. Dolt sql-server is launched with +// cmd.Dir = , and dolt's --prof-path is resolved relative +// to that cwd via os.Stat — passing a relative path like +// ".beads/dolt-pprof" would be looked up as ".beads/dolt/.beads/dolt-pprof" +// and dolt would panic with "profile path does not exist". Absolute paths +// are immune to that cwd shift. If filepath.Abs fails for some reason, +// fall back to the joined path (best-effort; the panic case will surface +// loudly at server start). +// +// The caller is responsible for creating the directory (Start does this +// before exec because dolt --prof-path panics on a missing path even +// with an absolute argument). +func DebugProfileDir(beadsDir string) string { + p := filepath.Join(resolveServerDir(beadsDir), "dolt-pprof") + if abs, err := filepath.Abs(p); err == nil { + return abs + } + return p +} + +// debugProfileFilename is the fixed filename pkg/profile writes for +// each profile mode. We currently only use cpu profiling; if that +// changes, extend this map. +const debugProfileFilename = "cpu.pprof" + +// rotateDebugProfile renames cpu.pprof → cpu-.pprof if it +// exists, so successive server runs do not overwrite each other's +// profiles. Called from Stop after the server has exited (when +// pkg/profile's deferred .Stop() has flushed the file to disk). +// +// Best-effort: failures are logged but do not block stop, since the +// rotation is a convenience and a missing file is the common case +// (server crashed under SIGKILL before flush). +func rotateDebugProfile(beadsDir string) { + profDir := DebugProfileDir(beadsDir) + src := filepath.Join(profDir, debugProfileFilename) + info, err := os.Stat(src) + if err != nil || info.Size() == 0 { + // No profile to rotate (server killed before flush, or never started in debug). + return + } + ts := time.Now().UTC().Format("20060102T150405Z") + dst := filepath.Join(profDir, fmt.Sprintf("cpu-%s.pprof", ts)) + if err := os.Rename(src, dst); err != nil { + fmt.Fprintf(os.Stderr, "Warning: could not rotate %s → %s: %v\n", src, dst, err) + return + } + fmt.Fprintf(os.Stderr, "Debug: cpu profile rotated to %s\n", dst) +} + // IsAutoStartDisabled returns true if the dolt server should NOT be // auto-started or managed by bd. When true, KillStaleServers and // auto-start are suppressed — the server is externally managed (e.g., @@ -633,20 +708,39 @@ func EnsureRunningDetailed(beadsDir string) (port int, startedByUs bool, err err // trace, debug, info, warning, error, fatal. const doltServerLogLevel = "warning" -// buildDoltServerArgs returns the argv passed to `dolt sql-server` -// (excluding argv[0]/the binary itself). It is factored out of Start so it -// can be asserted on in unit tests without spawning a real server. +// buildDoltServerArgs returns the argv passed to `dolt` (excluding argv[0]/ +// the binary itself). It is factored out of Start so it can be asserted on +// in unit tests without spawning a real server. // // The `--loglevel` flag MUST be included here — see doltServerLogLevel for // the rationale. If you remove or reorder these args, update the tests in // doltserver_test.go accordingly. -func buildDoltServerArgs(host string, port int) []string { - return []string{ +// +// When debug is true, the argv begins with `--prof cpu --prof-path `. +// These top-level dolt flags MUST appear before the `sql-server` subcommand: +// dolt's argv loop stops scanning debug flags on the first unknown token +// (see ~/cursor_src/dolt/go/cmd/dolt/dolt.go runMain). The caller must +// ensure profDir already exists — dolt panics if it does not. +// +// Debug mode also raises --loglevel from the default warning to debug; +// the connection-log spam concern that motivated the warning floor is +// the price of opting into debug. +func buildDoltServerArgs(host string, port int, debug bool, profDir string) []string { + var args []string + if debug { + args = append(args, "--prof", "cpu", "--prof-path", profDir) + } + args = append(args, "sql-server", "-H", host, "-P", strconv.Itoa(port), - "--loglevel=" + doltServerLogLevel, + ) + if debug { + args = append(args, "--loglevel=debug") + } else { + args = append(args, "--loglevel="+doltServerLogLevel) } + return args } // Start explicitly starts a dolt sql-server for the project. @@ -711,6 +805,17 @@ func Start(beadsDir string) (*State, error) { return nil, fmt.Errorf("configuring dolt identity: %w", err) } + // Debug mode: create the pprof output dir before exec, since dolt's + // --prof-path panics on a missing directory (see dolt/dolt.go runMain). + debug := IsDebugMode() + var profDir string + if debug { + profDir = DebugProfileDir(beadsDir) + if err := os.MkdirAll(profDir, config.BeadsDirPerm); err != nil { + return nil, fmt.Errorf("creating pprof directory %s: %w", profDir, err) + } + } + // Launch dolt sql-server, retrying once after an automatic corrupt- // manifest recovery (GH#3290). var ( @@ -777,7 +882,7 @@ startupLoop: actualPort = p } - cmd := exec.Command(doltBin, buildDoltServerArgs(cfg.Host, actualPort)...) //nolint:gosec // doltBin is resolved from PATH, not user input + cmd := exec.Command(doltBin, buildDoltServerArgs(cfg.Host, actualPort, debug, profDir)...) //nolint:gosec // doltBin is resolved from PATH, not user input cmd.Dir = doltDir cmd.Stdout = logFile cmd.Stderr = logFile @@ -1033,6 +1138,15 @@ func StopWithForce(beadsDir string, force bool) error { if err := gracefulStop(state.PID, 5*time.Second); err != nil { return errors.Join(err, cleanupStateFiles(beadsDir)) } + + // In debug mode, rotate cpu.pprof → cpu-.pprof so the next + // server start does not overwrite this run's profile. Only meaningful + // after a graceful (SIGTERM) exit — SIGKILL skips pkg/profile's + // deferred flush, leaving nothing to rotate. Best-effort. + if IsDebugMode() { + rotateDebugProfile(beadsDir) + } + return cleanupStateFiles(beadsDir) } diff --git a/internal/doltserver/doltserver_test.go b/internal/doltserver/doltserver_test.go index c3d9afd3f..dbfb0d029 100644 --- a/internal/doltserver/doltserver_test.go +++ b/internal/doltserver/doltserver_test.go @@ -1618,7 +1618,7 @@ func TestBuildDoltServerArgs(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - args := buildDoltServerArgs(tc.host, tc.port) + args := buildDoltServerArgs(tc.host, tc.port, false, "") if len(args) == 0 || args[0] != "sql-server" { t.Fatalf("args[0] = %q, want %q; full args: %v", @@ -1670,6 +1670,76 @@ func TestBuildDoltServerArgs(t *testing.T) { } } +// TestBuildDoltServerArgs_DebugMode verifies argv shape when debug mode +// is enabled. The top-level dolt flags (--prof, --prof-path) MUST come +// before the sql-server subcommand — dolt's argv scanner terminates on +// the first unknown token (see ~/cursor_src/dolt/go/cmd/dolt/dolt.go +// runMain). Placing --prof after sql-server silently drops profiling. +func TestBuildDoltServerArgs_DebugMode(t *testing.T) { + const profDir = "/tmp/test-pprof" + args := buildDoltServerArgs("127.0.0.1", 3308, true, profDir) + + // --prof and --prof-path must precede sql-server. + subIdx := indexOf(args, "sql-server") + if subIdx < 0 { + t.Fatalf("missing sql-server in args: %v", args) + } + + profIdx := indexOf(args, "--prof") + if profIdx < 0 { + t.Fatalf("missing --prof in debug args: %v", args) + } + if profIdx >= subIdx { + t.Errorf("--prof at idx %d must precede sql-server at idx %d (dolt argv scanner stops at unknown tokens); got: %v", + profIdx, subIdx, args) + } + if got := args[profIdx+1]; got != "cpu" { + t.Errorf("--prof value = %q, want %q", got, "cpu") + } + + pathIdx := indexOf(args, "--prof-path") + if pathIdx < 0 { + t.Fatalf("missing --prof-path in debug args: %v", args) + } + if pathIdx >= subIdx { + t.Errorf("--prof-path at idx %d must precede sql-server at idx %d; got: %v", + pathIdx, subIdx, args) + } + if got := args[pathIdx+1]; got != profDir { + t.Errorf("--prof-path value = %q, want %q", got, profDir) + } + + // Debug forces --loglevel=debug, overriding the normal warning floor. + logLevel, ok := findLogLevel(args) + if !ok { + t.Fatalf("missing --loglevel in debug args: %v", args) + } + if logLevel != "debug" { + t.Errorf("debug mode --loglevel = %q, want %q", logLevel, "debug") + } +} + +// TestBuildDoltServerArgs_NoDebugFlagsWhenDisabled guards against a +// regression where debug-only argv leaks into a non-debug invocation. +// The warning loglevel floor is also reasserted here so a future +// refactor can't silently degrade only the non-debug path. +func TestBuildDoltServerArgs_NoDebugFlagsWhenDisabled(t *testing.T) { + args := buildDoltServerArgs("127.0.0.1", 3308, false, "") + if indexOf(args, "--prof") >= 0 { + t.Errorf("non-debug args should not contain --prof: %v", args) + } + if indexOf(args, "--prof-path") >= 0 { + t.Errorf("non-debug args should not contain --prof-path: %v", args) + } + logLevel, ok := findLogLevel(args) + if !ok { + t.Fatalf("missing --loglevel in non-debug args: %v", args) + } + if logLevel == "debug" { + t.Errorf("non-debug mode must not use --loglevel=debug; got: %v", args) + } +} + func TestWaitForReady(t *testing.T) { // Allocate an ephemeral port, then release it so we can re-bind later. tmpListener, err := net.Listen("tcp", "127.0.0.1:0") diff --git a/internal/doltserver/doltserver_unix.go b/internal/doltserver/doltserver_unix.go index 04b48d623..0ba636771 100644 --- a/internal/doltserver/doltserver_unix.go +++ b/internal/doltserver/doltserver_unix.go @@ -46,8 +46,20 @@ func findPIDOnPort(port int) int { // listDoltProcessPIDs returns PIDs of all running dolt sql-server processes. // Excludes zombies and defunct processes. Callers derive count (len) and // membership (linear scan) from the returned slice. +// +// The pgrep pattern uses `dolt.*sql-server` rather than the literal +// `dolt sql-server` so it still matches when top-level dolt flags appear +// between the binary name and the subcommand — e.g. debug mode launches +// the server as `dolt --prof cpu --prof-path /…/dolt-pprof sql-server …`, +// in which `dolt sql-server` no longer appears as a contiguous substring. +// Without this, IsRunning's isDoltProcess check would reject the PID as +// "not a dolt process" and wipe the PID/port files of a healthy server, +// breaking `bd dolt status` and auto-start reattachment. The per-PID +// substring check below still requires both "dolt" and "sql-server" in +// the cmdline, so this only widens the first-stage filter; it does not +// loosen identity validation. func listDoltProcessPIDs() []int { - out, err := exec.Command("pgrep", "-f", "dolt sql-server").Output() + out, err := exec.Command("pgrep", "-f", "dolt.*sql-server").Output() if err != nil { return nil } From b456ec58fcfde90c7941f98bb5c25e37a6debbe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 12:47:34 -0700 Subject: [PATCH 2/3] /{cmd,internal}: some cleanup --- cmd/bd/config.go | 4 --- cmd/bd/init.go | 11 --------- internal/doltserver/doltserver.go | 41 ------------------------------- 3 files changed, 56 deletions(-) diff --git a/cmd/bd/config.go b/cmd/bd/config.go index dc46706c8..55a2f06b6 100644 --- a/cmd/bd/config.go +++ b/cmd/bd/config.go @@ -98,10 +98,6 @@ var configSetCmd = &cobra.Command{ os.Exit(1) } - // dolt.debug only affects the managed sql-server's argv. In embedded - // mode there is no managed server, so the write would be a no-op - // (and worse, would still appear in `bd config list`). Reject - // explicitly so the user doesn't store dead config. if key == "dolt.debug" && !usesSQLServer() { fmt.Fprintln(os.Stderr, "Error: dolt.debug requires a sql-server-backed project (embedded mode has no managed server).") fmt.Fprintln(os.Stderr, " To migrate: re-init with 'bd init --server' or 'bd init --shared-server'.") diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 0e53a7926..6e6eb2977 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -226,10 +226,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): _ = os.Setenv("BEADS_DOLT_SHARED_SERVER", "1") } - // Propagate --debug to env so IsDebugMode() returns true for the - // server start that happens later in this same init invocation - // (before config.yaml is written). Same one-shot rationale as - // the shared-server propagation above. if debugMode { _ = os.Setenv("BEADS_DOLT_DEBUG", "1") } @@ -801,10 +797,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fmt.Printf(" %s Shared Dolt server started\n", ui.RenderPass("✓")) } } else if debugMode { - // Shared server is already up — it was started without - // the debug-mode argv we just configured. Persisting - // dolt.debug will take effect on the next restart, but - // the currently-running server keeps its existing flags. fmt.Fprintf(os.Stderr, "Warning: shared Dolt server (PID %d, port %d) is already running without debug flags.\n", state.PID, state.Port) fmt.Fprintf(os.Stderr, " Restart to pick up debug mode:\n") fmt.Fprintf(os.Stderr, " bd dolt stop && bd dolt start\n") @@ -1055,9 +1047,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } } - // Persist --debug intent to config.yaml so subsequent bd commands - // that auto-start the dolt sql-server pick up the debug flags - // without requiring BEADS_DOLT_DEBUG in every shell. if debugMode { if err := config.SetYamlConfig("dolt.debug", "true"); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to persist dolt.debug: %v\n", err) diff --git a/internal/doltserver/doltserver.go b/internal/doltserver/doltserver.go index a92dd2393..ac3257c31 100644 --- a/internal/doltserver/doltserver.go +++ b/internal/doltserver/doltserver.go @@ -115,15 +115,6 @@ func IsSharedServerMode() bool { return config.GetBool("dolt.shared-server") } -// IsDebugMode returns true if the dolt sql-server should be launched in -// debug mode (--loglevel=debug plus CPU profiling via --prof cpu). -// Sources (priority order): -// 1. BEADS_DOLT_DEBUG env var ("1" or "true") -// 2. dolt.debug in config.yaml -// -// Debug mode only affects servers beads spawns. External / hosted / -// auto-start-disabled servers are unaffected — operators manage those -// argv themselves. func IsDebugMode() bool { if v := os.Getenv("BEADS_DOLT_DEBUG"); v == "1" || strings.EqualFold(v, "true") { return true @@ -131,27 +122,6 @@ func IsDebugMode() bool { return config.GetBool("dolt.debug") } -// DebugProfileDir returns the directory dolt sql-server writes pprof -// artifacts into when debug mode is enabled. The path is the canonical -// location surfaced by bd init / bd dolt start / bd dolt status so users -// know where to find cpu.pprof. -// -// Layout: -// - per-project: /dolt-pprof/ -// - shared server: ~/.beads/shared-server/dolt-pprof/ -// -// The returned path is absolute. Dolt sql-server is launched with -// cmd.Dir = , and dolt's --prof-path is resolved relative -// to that cwd via os.Stat — passing a relative path like -// ".beads/dolt-pprof" would be looked up as ".beads/dolt/.beads/dolt-pprof" -// and dolt would panic with "profile path does not exist". Absolute paths -// are immune to that cwd shift. If filepath.Abs fails for some reason, -// fall back to the joined path (best-effort; the panic case will surface -// loudly at server start). -// -// The caller is responsible for creating the directory (Start does this -// before exec because dolt --prof-path panics on a missing path even -// with an absolute argument). func DebugProfileDir(beadsDir string) string { p := filepath.Join(resolveServerDir(beadsDir), "dolt-pprof") if abs, err := filepath.Abs(p); err == nil { @@ -160,19 +130,8 @@ func DebugProfileDir(beadsDir string) string { return p } -// debugProfileFilename is the fixed filename pkg/profile writes for -// each profile mode. We currently only use cpu profiling; if that -// changes, extend this map. const debugProfileFilename = "cpu.pprof" -// rotateDebugProfile renames cpu.pprof → cpu-.pprof if it -// exists, so successive server runs do not overwrite each other's -// profiles. Called from Stop after the server has exited (when -// pkg/profile's deferred .Stop() has flushed the file to disk). -// -// Best-effort: failures are logged but do not block stop, since the -// rotation is a convenience and a missing file is the common case -// (server crashed under SIGKILL before flush). func rotateDebugProfile(beadsDir string) { profDir := DebugProfileDir(beadsDir) src := filepath.Join(profDir, debugProfileFilename) From 4b5936df91a349784aa866bf8857ebacc56ac3ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 12:59:04 -0700 Subject: [PATCH 3/3] /{docs,website}: generate docs --- docs/CLI_REFERENCE.md | 2 ++ website/docs/cli-reference/config.md | 1 + website/docs/cli-reference/init.md | 1 + website/versioned_docs/version-1.0.0/cli-reference/config.md | 1 + website/versioned_docs/version-1.0.0/cli-reference/init.md | 1 + website/versioned_docs/version-1.0.4/cli-reference/config.md | 1 + website/versioned_docs/version-1.0.4/cli-reference/init.md | 1 + 7 files changed, 8 insertions(+) diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 7be1faf6a..d4c73d0b1 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -2609,6 +2609,7 @@ Examples: bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" bd config set doctor.suppress.pending-migrations true + bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config get export.auto bd config list bd config unset jira.url @@ -3359,6 +3360,7 @@ bd init [flags] --backend string Storage backend (default: dolt). --backend=sqlite prints deprecation notice. --contributor Run OSS contributor setup wizard --database string Use existing server database name (overrides prefix-based naming) + --debug Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers. --destroy-token string Explicit confirmation token for destructive re-init in non-interactive mode (format: 'DESTROY-') --discard-remote Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'. --external Server is externally managed (skip server startup); use with --shared-server or --server diff --git a/website/docs/cli-reference/config.md b/website/docs/cli-reference/config.md index edc9e92b0..7073ac7a4 100644 --- a/website/docs/cli-reference/config.md +++ b/website/docs/cli-reference/config.md @@ -59,6 +59,7 @@ Examples: bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" bd config set doctor.suppress.pending-migrations true + bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config get export.auto bd config list bd config unset jira.url diff --git a/website/docs/cli-reference/init.md b/website/docs/cli-reference/init.md index e6970aabd..4ac6747d4 100644 --- a/website/docs/cli-reference/init.md +++ b/website/docs/cli-reference/init.md @@ -57,6 +57,7 @@ bd init [flags] --backend string Storage backend (default: dolt). --backend=sqlite prints deprecation notice. --contributor Run OSS contributor setup wizard --database string Use existing server database name (overrides prefix-based naming) + --debug Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers. --destroy-token string Explicit confirmation token for destructive re-init in non-interactive mode (format: 'DESTROY-') --discard-remote Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'. --external Server is externally managed (skip server startup); use with --shared-server or --server diff --git a/website/versioned_docs/version-1.0.0/cli-reference/config.md b/website/versioned_docs/version-1.0.0/cli-reference/config.md index edc9e92b0..7073ac7a4 100644 --- a/website/versioned_docs/version-1.0.0/cli-reference/config.md +++ b/website/versioned_docs/version-1.0.0/cli-reference/config.md @@ -59,6 +59,7 @@ Examples: bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" bd config set doctor.suppress.pending-migrations true + bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config get export.auto bd config list bd config unset jira.url diff --git a/website/versioned_docs/version-1.0.0/cli-reference/init.md b/website/versioned_docs/version-1.0.0/cli-reference/init.md index e6970aabd..4ac6747d4 100644 --- a/website/versioned_docs/version-1.0.0/cli-reference/init.md +++ b/website/versioned_docs/version-1.0.0/cli-reference/init.md @@ -57,6 +57,7 @@ bd init [flags] --backend string Storage backend (default: dolt). --backend=sqlite prints deprecation notice. --contributor Run OSS contributor setup wizard --database string Use existing server database name (overrides prefix-based naming) + --debug Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers. --destroy-token string Explicit confirmation token for destructive re-init in non-interactive mode (format: 'DESTROY-') --discard-remote Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'. --external Server is externally managed (skip server startup); use with --shared-server or --server diff --git a/website/versioned_docs/version-1.0.4/cli-reference/config.md b/website/versioned_docs/version-1.0.4/cli-reference/config.md index edc9e92b0..7073ac7a4 100644 --- a/website/versioned_docs/version-1.0.4/cli-reference/config.md +++ b/website/versioned_docs/version-1.0.4/cli-reference/config.md @@ -59,6 +59,7 @@ Examples: bd config set jira.project "PROJ" bd config set status.custom "awaiting_review,awaiting_testing" bd config set doctor.suppress.pending-migrations true + bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu) bd config get export.auto bd config list bd config unset jira.url diff --git a/website/versioned_docs/version-1.0.4/cli-reference/init.md b/website/versioned_docs/version-1.0.4/cli-reference/init.md index e6970aabd..4ac6747d4 100644 --- a/website/versioned_docs/version-1.0.4/cli-reference/init.md +++ b/website/versioned_docs/version-1.0.4/cli-reference/init.md @@ -57,6 +57,7 @@ bd init [flags] --backend string Storage backend (default: dolt). --backend=sqlite prints deprecation notice. --contributor Run OSS contributor setup wizard --database string Use existing server database name (overrides prefix-based naming) + --debug Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers. --destroy-token string Explicit confirmation token for destructive re-init in non-interactive mode (format: 'DESTROY-') --discard-remote Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'. --external Server is externally managed (skip server startup); use with --shared-server or --server