:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phrocs): add autorestart backoff and enable for backend/celery (#64843)
Georges-Antoine Assi6efe2fd17128
diff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 7a6ddf6a4e53..69cb7cb86394 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -37,6 +37,7 @@ procs:backend:sandbox: trueshell: 'bin/wait-for-docker && ./bin/start-backend'+ autorestart: trueready_pattern: 'Listening at'groups:layer: Application@@ -46,6 +47,7 @@ procs:celery-worker:sandbox: trueshell: 'bin/wait-for-docker && ./bin/start-celery worker'+ autorestart: truecapability: celery_workersready_pattern: 'celery@'groups:@@ -55,6 +57,7 @@ procs:celery-beat:sandbox: trueshell: 'bin/wait-for-docker && ./bin/start-celery beat'+ autorestart: truecapability: celery_schedulerready_pattern: 'celery beat'groups:diff --git a/tools/phrocs/internal/process/proc.go b/tools/phrocs/internal/process/proc.goindex 225d6dbb53b3..646ee63b005d 100644--- a/tools/phrocs/internal/process/proc.go+++ b/tools/phrocs/internal/process/proc.go@@ -27,6 +27,21 @@ const flushInterval = 16 * time.Millisecondconst stopGracePeriod = 3 * time.Secondconst defaultShell = "/bin/bash"+// Autorestart backoff: when a proc with autorestart crashes, it's restarted+// after an exponential delay that grows with each consecutive rapid crash, so a+// crash-looping proc backs off instead of thrashing. After maxRestartAttempts+// consecutive crashes the proc is left dead and must be restarted manually. A+// proc that stays up longer than restartStableRunTime is considered healthy, so+// its next crash starts the count (and backoff) over from scratch.+const restartStableRunTime = 60 * time.Second++// Effectively constants, but var so tests can shrink the timings and cap.+var (+ restartBackoffBase = 1 * time.Second+ restartBackoffMax = 30 * time.Second+ maxRestartAttempts = 10+)+type Status intconst (@@ -135,6 +150,8 @@ type Process struct {exitCode *intmetrics *MetricsmetricsEnabled atomic.Bool++ restartCount int // consecutive rapid autorestarts since the last healthy run}// SetLogDir enables per-process log file teeing. When non-empty, Start opens@@ -422,11 +439,23 @@ func (p *Process) buildCmd() *exec.Cmd {// It's safe to call Start concurrently as running process is a no-opfunc (p *Process) Start(send func(tea.Msg)) error {+ return p.startInternal(send, false)+}++// startInternal starts the process. isAutoRestart distinguishes a backoff-driven+// restart (which keeps the running crash count) from a manual start (which+// resets it — the user has presumably fixed whatever was crashing). Passing it+// as a parameter keeps the decision inside the same lock acquisition, avoiding a+// race with a concurrent manual start.+func (p *Process) startInternal(send func(tea.Msg), isAutoRestart bool) error {p.mu.Lock()if p.status == StatusRunning {p.mu.Unlock()return nil}+ if !isAutoRestart {+ p.restartCount = 0+ }p.status = StatusPending// Preserve the current emulator dimensions (set by Resize) so the// child process sees the correct terminal size from the start.@@ -638,6 +667,7 @@ func (p *Process) handleExit(cmd *exec.Cmd, exitErr error, send func(tea.Msg)) {st = StatusCrashed}p.mu.Lock()+ ranFor := time.Since(p.startedAt)if p.cmd == cmd && p.status != StatusStopped {p.status = stp.metrics = nil@@ -646,6 +676,17 @@ func (p *Process) handleExit(cmd *exec.Cmd, exitErr error, send func(tea.Msg)) {}finalStatus := p.statusshouldRestart := p.cmd == cmd && p.Cfg.Autorestart && st == StatusCrashed && finalStatus != StatusStopped+ var attempt int+ if shouldRestart {+ // A proc that stayed up long enough is treated as healthy, so a later+ // crash restarts the backoff from scratch rather than inheriting a+ // stale count from an earlier crash loop.+ if ranFor >= restartStableRunTime {+ p.restartCount = 0+ }+ p.restartCount+++ attempt = p.restartCount+ }if p.logFile != nil {_ = p.logFile.Close()p.logFile = nil@@ -655,8 +696,68 @@ func (p *Process) handleExit(cmd *exec.Cmd, exitErr error, send func(tea.Msg)) {send(StatusMsg{Name: p.Name, Status: finalStatus})if shouldRestart {- _ = p.Start(send)+ p.scheduleRestart(cmd, attempt, send)+ }+}++// scheduleRestart waits out the backoff for the given attempt and then restarts+// the process, unless the attempt cap has been hit or the process was stopped or+// manually restarted while we waited. Runs on the cmd.Wait goroutine, so the+// backoff sleep here doesn't block anything else.+func (p *Process) scheduleRestart(cmd *exec.Cmd, attempt int, send func(tea.Msg)) {+ if attempt > maxRestartAttempts {+ p.writeNotice(fmt.Sprintf(+ "\r\n[phrocs] %s keeps crashing — gave up after %d restarts. Fix it and restart manually.\r\n",+ p.Name, maxRestartAttempts), send)+ return}++ backoff := restartBackoffFor(attempt)+ p.writeNotice(fmt.Sprintf(+ "\r\n[phrocs] %s crashed — restarting in %s (attempt %d/%d)…\r\n",+ p.Name, backoff.Round(time.Second), attempt, maxRestartAttempts), send)+ time.Sleep(backoff)++ // Only restart if the proc is still in the crashed state we observed. Any+ // other status means something else took over the slot while we backed off+ // — a manual restart (StatusPending/StatusRunning) or a stop (StatusStopped)+ // — and restarting now would double-start it.+ p.mu.Lock()+ canRestart := p.cmd == cmd && p.status == StatusCrashed+ p.mu.Unlock()+ if !canRestart {+ return+ }++ _ = p.startInternal(send, true)+}++// restartBackoffFor returns the exponential backoff delay for a given 1-based+// restart attempt, capped at restartBackoffMax.+func restartBackoffFor(attempt int) time.Duration {+ if attempt < 1 {+ attempt = 1+ }+ backoff := restartBackoffBase+ for i := 1; i < attempt; i++ {+ backoff *= 2+ if backoff >= restartBackoffMax {+ return restartBackoffMax+ }+ }+ return backoff+}++// writeNotice injects a phrocs-generated line into the process's output buffer+// so the user sees autorestart activity inline with the proc's own logs.+func (p *Process) writeNotice(msg string, send func(tea.Msg)) {+ p.mu.Lock()+ if p.emulator != nil {+ _, _ = p.emulator.Write([]byte(msg))+ }+ p.unread = true+ p.mu.Unlock()+ send(OutputMsg{Name: p.Name})}// readLoop reads process output, feeds it through a VT terminal emulator,diff --git a/tools/phrocs/internal/process/proc_test.go b/tools/phrocs/internal/process/proc_test.goindex 2c983e8fbc17..1d716ee222e6 100644--- a/tools/phrocs/internal/process/proc_test.go+++ b/tools/phrocs/internal/process/proc_test.go@@ -882,3 +882,148 @@ func TestProcess_logFileDisabledByDefault(t *testing.T) {t.Errorf("expected no log file when logDir unset; got err=%v", err)}}++func TestRestartBackoffFor(t *testing.T) {+ tests := []struct {+ attempt int+ want time.Duration+ }{+ {0, restartBackoffBase}, // clamped to 1+ {1, 1 * time.Second},+ {2, 2 * time.Second},+ {3, 4 * time.Second},+ {4, 8 * time.Second},+ {5, 16 * time.Second},+ {6, restartBackoffMax}, // 32s would exceed the cap+ {7, restartBackoffMax},+ {50, restartBackoffMax},+ }+ for _, tt := range tests {+ t.Run(fmt.Sprintf("attempt-%d", tt.attempt), func(t *testing.T) {+ if got := restartBackoffFor(tt.attempt); got != tt.want {+ t.Errorf("restartBackoffFor(%d) = %s, want %s", tt.attempt, got, tt.want)+ }+ })+ }+}++func TestProcess_autorestartAfterCrash(t *testing.T) {+ // Shrink the backoff so the restart happens in milliseconds, not ~1s.+ origBase, origMax := restartBackoffBase, restartBackoffMax+ restartBackoffBase = 2 * time.Millisecond+ restartBackoffMax = 5 * time.Millisecond+ t.Cleanup(func() {+ restartBackoffBase, restartBackoffMax = origBase, origMax+ })++ dir := t.TempDir()+ mark := dir + "/runs"+ // Append a line then crash, so each run leaves a trace and triggers autorestart.+ p := NewProcess("crasher", config.ProcConfig{+ Shell: `echo run >> "$MARK"; exit 1`,+ Autorestart: true,+ Env: map[string]string{"MARK": mark},+ }, 100, "")++ send, _, _ := collectMsgs()+ if err := p.Start(send); err != nil {+ t.Skipf("cannot spawn subprocess: %v", err)+ }++ // First crash restarts after the (shrunk) backoff, so a second run shows up+ // shortly after.+ deadline := time.After(5 * time.Second)+ for {+ data, _ := os.ReadFile(mark)+ if strings.Count(string(data), "run") >= 2 {+ break+ }+ select {+ case <-deadline:+ t.Fatalf("expected at least 2 runs from autorestart, got %q", string(data))+ case <-time.After(25 * time.Millisecond):+ }+ }++ // Stop the proc so the crash loop doesn't keep restarting after the test.+ p.Stop()+}++func TestProcess_autorestartGivesUpAfterCap(t *testing.T) {+ // Shrink the timings and cap so the full give-up flow runs in milliseconds.+ origBase, origMax, origCap := restartBackoffBase, restartBackoffMax, maxRestartAttempts+ restartBackoffBase = 2 * time.Millisecond+ restartBackoffMax = 5 * time.Millisecond+ maxRestartAttempts = 3+ t.Cleanup(func() {+ restartBackoffBase, restartBackoffMax, maxRestartAttempts = origBase, origMax, origCap+ })++ dir := t.TempDir()+ mark := dir + "/runs"+ p := NewProcess("crasher", config.ProcConfig{+ Shell: `echo run >> "$MARK"; exit 1`,+ Autorestart: true,+ Env: map[string]string{"MARK": mark},+ }, 100, "")++ send, _, _ := collectMsgs()+ if err := p.Start(send); err != nil {+ t.Skipf("cannot spawn subprocess: %v", err)+ }++ // Wait for the give-up notice, which is only written once the cap is hit.+ deadline := time.After(5 * time.Second)+ for !strings.Contains(strings.Join(p.Lines(), "\n"), "gave up") {+ select {+ case <-deadline:+ t.Fatalf("expected give-up notice after %d restarts", maxRestartAttempts)+ case <-time.After(10 * time.Millisecond):+ }+ }++ // Give any erroneous further restart a chance to fire, then assert the proc+ // stayed dead and ran exactly maxRestartAttempts+1 times (initial + cap).+ time.Sleep(50 * time.Millisecond)+ if p.Status() != StatusCrashed {+ t.Errorf("expected status crashed after giving up, got %s", p.Status())+ }+ data, _ := os.ReadFile(mark)+ if got, want := strings.Count(string(data), "run"), maxRestartAttempts+1; got != want {+ t.Errorf("expected %d runs before giving up, got %d", want, got)+ }+}++func TestProcess_noAutorestartWhenDisabled(t *testing.T) {+ dir := t.TempDir()+ mark := dir + "/runs"+ p := NewProcess("crasher", config.ProcConfig{+ Shell: `echo run >> "$MARK"; exit 1`,+ Env: map[string]string{"MARK": mark},+ }, 100, "")++ send, _, _ := collectMsgs()+ if err := p.Start(send); err != nil {+ t.Skipf("cannot spawn subprocess: %v", err)+ }++ // Wait for the single run to finish and the proc to settle into crashed.+ deadline := time.After(5 * time.Second)+ for p.IsRunning() {+ select {+ case <-deadline:+ t.Fatal("process did not exit in time")+ case <-time.After(25 * time.Millisecond):+ }+ }++ // Give any (erroneous) restart a chance to fire, then assert it stayed dead.+ time.Sleep(restartBackoffBase + 200*time.Millisecond)+ if p.Status() != StatusCrashed {+ t.Errorf("expected status crashed, got %s", p.Status())+ }+ data, _ := os.ReadFile(mark)+ if got := strings.Count(string(data), "run"); got != 1 {+ t.Errorf("expected exactly 1 run without autorestart, got %d", got)+ }+}