Repository navigation
fix(gateway): prevent Tailscale orphan crash loops on launchd restart - #126457
PollyBot13 wants to merge 5 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 5, 2026, 5:54 AM ET / 09:54 UTC. ClawSweeper reviewWhat this changesThe PR bounds macOS Gateway shutdown using the running LaunchAgent’s timeout and preserves that deadline through draining, cleanup, startup, and restart handoffs. Merge readiness⛔ Blocked before merge - 4 items remain This remains useful work for an unresolved main-branch failure. No blocking code finding was identified; the outstanding gate is the intentional compatibility change for unreadable launchd timeouts. Priority: P1 Review scores
Verification
How this fits togetherThe Gateway run loop receives operating-system signals and coordinates active work, resource cleanup, and replacement processes. Finishing before launchd forcibly terminates it allows the Tailscale listener to be released for the next Gateway. flowchart TD
A[Stop or restart request] --> B[Launchd sends SIGTERM]
B --> C[Read loaded timeout]
C --> D[Shared shutdown deadline]
D --> E[Drain work and release listener]
E --> F[Exit or restart handoff]
D -->|Deadline expires| F
F -->|Restart requested| G[Replacement Gateway]
Decision needed
Why: Both choices trade supervisor deadline certainty against interrupted work and cleanup; the contributor explicitly leaves this choice open, and the native trace covers only a readable timeout. Before merge
Agent review detailsSecurityNone. PR surfaceSource +371, Tests +751. Total +1122 across 6 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep one lifecycle-owned deadline with an owner-approved bounded cleanup policy for unreadable jobs; no net-neutral repair was established for the missing coordination across startup, draining, and handoff. Do we have a high-confidence way to reproduce the issue? Yes, from source: active work can keep current main draining beyond the generated LaunchAgent’s 20-second timeout. This review did not execute a current-main reproduction. Is this the best way to solve the issue? Unclear overall: the run loop is the correct deadline owner, and increasing the generated plist timeout would not repair already-loaded jobs, but the unreadable-budget policy still needs a lifecycle decision. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against f4fa8a6798cb. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (41 earlier review cycles; latest 8 shown)
|
2776d1f to
cbc85f2
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Current-main conflict resolved on The two conflict sites combined both lifecycle invariants:
Post-merge verification:
The PR body now distinguishes the current merged-head test evidence from the earlier exact patch-head macOS process-boundary proof. |
c8c3906 to
26e68a3
Compare
26e68a3 to
a3c475a
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
The orphaning path is confirmed, and a small prevention rewrite is preserved in d42ae5d4803578c714e3c96ef4b01d605672a867, crediting @PollyBot13. Nothing has been merged and no replacement PR has been opened. The root cause is the process-group split: the Gateway and IPC cleanup worker share a group, while the foreground Tailscale CLI is detached. A launchd group kill therefore removes the cleanup worker while leaving the claimant alive. The rewrite detaches the cleanup worker, handles IPC loss during initialization, and removes redundant Promise-settlement state. Production LOC is +6/−7 (net −1); tests and fixtures are +114/−7 (net +107). The contributor's launchd deadline machinery is not included, so its unreadable-timeout policy/rank-up decision is not introduced by this branch. Validation: all seven focused macOS process tests pass, including PID-only SIGKILL, whole-group SIGKILL, same-port replacement, early IPC loss, and graceful cleanup. The saved pre-fix reproduction fails the whole-group case because the claimant remains alive. Independent review found no actionable P0–P2 defects in the prevention patch; formatting passes. The full changed gate is incomplete: typechecking rejects this worktree's external declaration dependency path. A fresh Blacksmith Testbox was acquired, but its local source preparation had not reached remote execution when the attempt was stopped; this is not fresh remote or authenticated Tailscale proof. The remaining maintainer decision is historical foreground-orphan recovery. Once an older Gateway and its cleanup worker are dead, the claimant has lost its ancestry and points to an ephemeral backend. The route PID was held only in the dead parent's memory; Tailscale's foreground session has no OpenClaw ownership identifier. A matching command, PPID 1, or dead loopback port cannot distinguish another application's route. Current main safely adopts narrowly recognized legacy background mappings, but that is a different case. Automatically killing or clearing ambiguous foreground claims would expand the ownership policy; new durable ownership metadata also requires a persistence design decision and cannot retroactively identify old orphans. Recommendation: accept prevention with explicit operator-assisted recovery for already-orphaned foreground claims, or decide the stronger ownership policy before automatic recovery is implemented. Also track the existing recovery diagnostic: |
|
Superseded by the smaller ownership repair in #139261, merged as eb08c36. Thanks @PollyBot13 for the report and contribution; the replacement retains contributor credit. The cleanup worker now survives a POSIX Gateway process-group kill and releases its foreground claimant through IPC-loss cleanup. Fresh Crabbox proof with real built Gateways and a synthetic Tailscale TCP claimant reproduced the old orphan/exit-78 restart failure, then verified claimant release within 31 ms and a healthy same-port replacement within 1.976 seconds. All 55 focused tests, independent review, and exact-head CI passed. Commands, traces, source identities and proof limitations are in the replacement PR. This closes the reported new-orphan crash-loop path without adding shutdown-deadline policy. Already-orphaned foreground processes from older Gateways remain operator-assisted recovery; the replacement deliberately does not infer ownership of unrelated routes. Any separate shutdown-budget proposal should be based on evidence beyond the claimant-lifetime defect now repaired. |
|
The recovery follow-up is now on Foreground conflicts now identify the observed session and route and direct operators to stop only their confirmed owning process. The Tailscale guide covers one-time recovery for claims left by older Gateways. There is no automatic reclamation or new persistence design. All 63 tests across the five Tailscale owner/helper/Gateway/upgrade files and the full changed gate passed on Crabbox against the final head; exact-head CI and independent review also passed. The PR records the source receipt, commands, and the authenticated-Tailscale limitation. Both landing commits are verified ancestors of current Thanks again @PollyBot13; contributor credit is preserved. FYI @Patrick-Erichsen — this completes the named follow-up, and the existing assignment is unchanged. |
Fixes #126445
What Problem This Solves
Fixes a macOS launchd restart crash loop where active Gateway work can outlive launchd's loaded
ExitTimeOut. launchd may then SIGKILL the Gateway before Tailscale cleanup, leaving the old claimant on port 443 so the replacement cannot start.Why This Change Was Made
Launchd-managed SIGTERM restarts now read the active loaded job's
ExitTimeOutat signal receipt and share one monotonic absolute deadline across restart-intent classification, active-work draining, server/resource cleanup, managed-update handoff parking/cancellation/commit, startup before a close handle exists, final log flushing, and in-process recovery.A positive loaded timeout reserves the last five seconds for launchd. An explicit loaded value of zero remains unbounded. If the loaded job cannot be read or has no valid timeout, the path fails closed with an immediate deadline because no generated/default value proves how soon launchd may hard-kill the process. Repeated signals may tighten but never extend an existing cutoff.
The foreground Tailscale claimant remains detached from its cleanup worker, allowing cleanup to target the claimant's process group. This does not imply that the worker survives a hard Gateway process-group kill. The live proof below covers graceful claimant shutdown and replacement, not that hard-kill path. Generic unmanaged, systemd, Windows, and SIGUSR1-only restart behavior is unchanged.
User Impact
LaunchAgent restarts reserve enough time to release the Tailscale listener, allowing the replacement Gateway to start instead of entering a KeepAlive crash loop.
Evidence
5817467d30a50e4fadfbfeed0b7b5bfaefaa1235; merge base:903980a972d4ea2652290bcd7bc9a8f71ef7624a.main:66fa0bd2be4f811a6c6dbee8bd5dd102dae8e544; it has zero changes on the six PR paths since the merge base, and a local merge-tree reports no conflict.check-changed: passed formatting, production/test typecheck, lint, dead-export, import-cycle, dependency, boundary, and structural guards.ExitTimeOut=20; old Gateway/wrapper/claimant exited; replacement listener was reacquired; health was true before and after; temporary label/plist/state/listeners and all proof processes were removed; production Gateway, real Tailscale, and public port 443 were untouched. Result SHA-256:041305bc6825244fd54f90a0167b64d695fccad321b3d49d50f5249da2bed9f1.Inspectable exact-head macOS LaunchAgent trace (redacted)
Captured from
candidate.sha, the generated plist,launchctlbefore/after snapshots, stalled-provider events, fake-claimant events, listener snapshots, lifecycle log, health snapshots, and uninstall readback. Redaction replaces only the local user/path, temporary label/profile, and isolated loopback ports; the SHA, UTC timestamps, PIDs, states, and timing are unchanged.Owner acceptance
ExitTimeOut, or require a bounded graceful compatibility path. The patch intentionally chooses fail-closed because no fallback value proves the supervisor's remaining kill budget.Worked on by
AI-assisted: yes.