Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(cli): fail daemon start without matching child health (#10207)

Bohan Jiang78dd3a2aec2e
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index d1f4ac89e7..61884311c1 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -684,25 +684,38 @@ func runDaemonBackground(cmd *cobra.Command) error {
fmt.Fprintf(os.Stderr, "Warning: could not write PID file: %v\n", err)
}
+ started, err := waitForDaemonStartup(waitCh, pid, profile, 45*time.Second, daemonStartupLogs{
+ logPath: logPath,
+ logOffset: logOffset,
+ errLogPath: errLogPath,
+ errLogOffset: errLogOffset,
+ }, resolveDaemonServerURL(cmd, profile))
+ if err != nil || !started {
+ return err
+ }
+
+ if profile != "" {
+ fmt.Fprintf(os.Stderr, "Daemon [%s] started (pid %d, version %s)\n", profile, pid, version)
+ } else {
+ fmt.Fprintf(os.Stderr, "Daemon started (pid %d, version %s)\n", pid, version)
+ }
+ fmt.Fprintf(os.Stderr, "Logs: %s\n", logPath)
+ return nil
+}
+
+func waitForDaemonStartup(waitCh <-chan error, pid int, profile string, startupTimeout time.Duration, logs daemonStartupLogs, serverURL string) (bool, error) {
// Poll the health endpoint until the daemon reports ready ("running") or we
// time out. The daemon binds the health port almost immediately but reports
// status:"starting" until preflight finishes (PAT renew + initial workspace
// sync, which exec's every configured agent for version detection and can
// take ~20s on a cold cache). Wait long enough to cover that so a healthy
// cold start is not misreported as a failure.
- const startupTimeout = 45 * time.Second
deadline := time.Now().Add(startupTimeout)
- started := false
lastStatus := ""
for time.Now().Before(deadline) {
select {
case waitErr := <-waitCh:
- return daemonStartupFailureError(daemonStartupLogs{
- logPath: logPath,
- logOffset: logOffset,
- errLogPath: errLogPath,
- errLogOffset: errLogOffset,
- }, waitErr, profile, resolveDaemonServerURL(cmd, profile))
+ return false, daemonStartupFailureError(logs, waitErr, profile, serverURL)
case <-time.After(500 * time.Millisecond):
}
// The child publishes the port only after it has bound the listener.
@@ -712,30 +725,25 @@ func runDaemonBackground(cmd *cobra.Command) error {
continue
}
hctx, hcancel := context.WithTimeout(context.Background(), 2*time.Second)
- health = checkDaemonHealthOnPort(hctx, record.Port)
+ health := checkDaemonHealthOnPort(hctx, record.Port)
hcancel()
+ // Only this child's responses can establish readiness or earn the
+ // slow-start grace period. Keep the last verified status if a later
+ // probe fails or the port answers for a different daemon.
+ if health["profile"] != profile || health["pid"] != float64(pid) {
+ continue
+ }
lastStatus, _ = health["status"].(string)
- if lastStatus == "running" && health["profile"] == profile && health["pid"] == float64(pid) {
- started = true
- break
+ if lastStatus == "running" {
+ return true, nil
}
}
- if !started {
- if lastStatus == "starting" {
- fmt.Fprintf(os.Stderr, "Daemon is still starting after %s (agent detection / workspace sync is taking longer than expected). Check logs:\n %s\n", startupTimeout, logPath)
- } else {
- fmt.Fprintf(os.Stderr, "Daemon may not have started successfully. Check logs:\n %s\n %s (crash output)\n", logPath, errLogPath)
- }
- return nil
+ if lastStatus == "starting" {
+ fmt.Fprintf(os.Stderr, "Daemon is still starting after %s (agent detection / workspace sync is taking longer than expected). Check logs:\n %s\n", startupTimeout, logs.logPath)
+ return false, nil
}
- if profile != "" {
- fmt.Fprintf(os.Stderr, "Daemon [%s] started (pid %d, version %s)\n", profile, pid, version)
- } else {
- fmt.Fprintf(os.Stderr, "Daemon started (pid %d, version %s)\n", pid, version)
- }
- fmt.Fprintf(os.Stderr, "Logs: %s\n", logPath)
- return nil
+ return false, fmt.Errorf("daemon startup timed out after %s without a matching health response. Check logs:\n %s\n %s (crash output)", startupTimeout, logs.logPath, logs.errLogPath)
}
// resolveDaemonServerURL resolves the server URL the daemon will talk to,
diff --git a/server/cmd/multica/cmd_daemon_startup_test.go b/server/cmd/multica/cmd_daemon_startup_test.go
new file mode 100644
index 0000000000..774353d296
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_startup_test.go
@@ -0,0 +1,114 @@
+package main
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestWaitForDaemonStartup(t *testing.T) {
+ const pid = 12345
+ cases := []struct {
+ name string
+ profile string
+ recordPID int
+ responses []string
+ wantReady bool
+ wantError bool
+ }{
+ {name: "no port record", profile: "startup", wantError: true},
+ {name: "stale port record", profile: "startup", recordPID: pid + 1,
+ responses: []string{`{"status":"starting","profile":"startup","pid":12346}`}, wantError: true},
+ {name: "no health response", profile: "startup", recordPID: pid,
+ responses: []string{"unavailable"}, wantError: true},
+ {name: "starting", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":"startup","pid":12345}`}},
+ {name: "running", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"running","profile":"startup","pid":12345}`}, wantReady: true},
+ {name: "starting with wrong profile", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":"other","pid":12345}`}, wantError: true},
+ {name: "starting with wrong PID", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":"startup","pid":12346}`}, wantError: true},
+ {name: "starting without profile", recordPID: pid,
+ responses: []string{`{"status":"starting","pid":12345}`}, wantError: true},
+ {name: "starting without PID", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":"startup"}`}, wantError: true},
+ {name: "starting with unreadable profile", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":null,"pid":12345}`}, wantError: true},
+ {name: "running with wrong profile", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"running","profile":"other","pid":12345}`}, wantError: true},
+ {name: "running with wrong PID", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"running","profile":"startup","pid":12346}`}, wantError: true},
+ {name: "default profile starting", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":"","pid":12345}`}},
+ {name: "default profile running", recordPID: pid,
+ responses: []string{`{"status":"running","profile":"","pid":12345}`}, wantReady: true},
+ {name: "starting then temporary health failure", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":"startup","pid":12345}`, "unavailable"}},
+ {name: "starting then running", profile: "startup", recordPID: pid,
+ responses: []string{`{"status":"starting","profile":"startup","pid":12345}`, `{"status":"running","profile":"startup","pid":12345}`}, wantReady: true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ clearDaemonTaskEnv(t)
+ mkProfiles(t, "startup")
+ var requests atomic.Int32
+ if tc.recordPID != 0 {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/health" {
+ t.Errorf("unexpected request to %s", r.URL.Path)
+ http.NotFound(w, r)
+ return
+ }
+ index := min(int(requests.Add(1))-1, len(tc.responses)-1)
+ fmt.Fprint(w, tc.responses[index])
+ }))
+ t.Cleanup(server.Close)
+ if err := publishDaemonPort(tc.profile, daemonPortRecord{
+ Port: server.Listener.Addr().(*net.TCPAddr).Port,
+ PID: tc.recordPID,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ logs := daemonStartupLogs{
+ logPath: filepath.Join(daemonDirForProfile(tc.profile), "daemon.log"),
+ errLogPath: filepath.Join(daemonDirForProfile(tc.profile), "daemon.err.log"),
+ }
+ timeout := 100 * time.Millisecond
+ if len(tc.responses) > 1 {
+ timeout = 750 * time.Millisecond
+ }
+ stderr := captureStderr(t)
+ defer stderr.restore()
+ // An open channel models a child that stays alive. No daemon is
+ // launched or signalled; all health endpoints belong to this test.
+ ready, err := waitForDaemonStartup(make(chan error), pid, tc.profile, timeout, logs, "")
+ out := stderr.read()
+ if ready != tc.wantReady || (err != nil) != tc.wantError {
+ t.Fatalf("waitForDaemonStartup = (%v, %v), want ready=%v error=%v", ready, err, tc.wantReady, tc.wantError)
+ }
+ if tc.wantError {
+ for _, hint := range []string{"timed out", timeout.String(), logs.logPath, logs.errLogPath} {
+ if !strings.Contains(err.Error(), hint) {
+ t.Errorf("error %q missing %q", err, hint)
+ }
+ }
+ } else if !tc.wantReady && !strings.Contains(out, "Daemon is still starting") {
+ t.Errorf("stderr = %q, want slow-start warning", out)
+ }
+ if tc.recordPID != pid && requests.Load() != 0 {
+ t.Errorf("probed a stale port record %d times", requests.Load())
+ }
+ if tc.recordPID == pid && int(requests.Load()) < len(tc.responses) {
+ t.Errorf("health requests = %d, want at least %d", requests.Load(), len(tc.responses))
+ }
+ })
+ }
+}