Skip to content

fix(gateway): prevent Tailscale orphan crash loops on launchd restart - #126457

Closed
PollyBot13 wants to merge 5 commits into
openclaw:mainfrom
PollyBot13:fix/launchd-tailscale-owner-lifecycle
Closed

PollyBot13 wants to merge 5 commits into
openclaw:mainfrom
PollyBot13:fix/launchd-tailscale-owner-lifecycle

Conversation

@PollyBot13

@PollyBot13 PollyBot13 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

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 ExitTimeOut at 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

  • Exact head: 5817467d30a50e4fadfbfeed0b7b5bfaefaa1235; merge base: 903980a972d4ea2652290bcd7bc9a8f71ef7624a.
  • Current main: 66fa0bd2be4f811a6c6dbee8bd5dd102dae8e544; it has zero changes on the six PR paths since the merge base, and a local merge-tree reports no conflict.
  • Scope: 6 files, +1204/-82: production +444/-73 and focused tests +760/-9.
  • Scope decision: keep one PR. Loaded-deadline discovery, signal/request ownership, bounded timers, hard-exit fallback, and the race regressions are one launchd restart-availability invariant. Independent review found no materially removable scope without weakening that boundary.
  • Focused tests: 125/125 passed (run-loop 99, managed-handoff single-flight 18, loaded-timeout parser 7, hard-exit process 1).
  • check-changed: passed formatting, production/test typecheck, lint, dead-export, import-cycle, dependency, boundary, and structural guards.
  • Full build: passed runtime/plugin builds, CLI bootstrap, SDK declarations/exports, postbuild checks, and Control UI.
  • Independent exact-head P0-P3 review: no actionable defect, 0.88 confidence; specifically confirmed that managed takeover cancels an inherited generic watchdog, while launchd absolute deadlines remain non-extending and survive handoff, recovery, and final log flushing.
  • Hosted exact-head CI: pending publication of this SHA; local changed-surface checks and the full build are green.
  • Real macOS LaunchAgent proof on this exact head: active work observed; restart completed in 11.542s under loaded 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, launchctl before/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.

$ git rev-parse HEAD
5817467d30a50e4fadfbfeed0b7b5bfaefaa1235

$ plutil -p <generated-isolated-plist> | grep ExitTimeOut
"ExitTimeOut" => 20

$ launchctl print <isolated-label>  # before restart
state = running
exit timeout = 20
runs = 1
pid = 13430
last exit code = (never exited)

$ jq '{ok,ts,durationMs}' health.before.json
{"ok":true,"ts":1788564951205,"durationMs":1}

$ tail provider.events.jsonl
{"at":"2026-09-04T23:35:52.197Z","event":"request-stalled","method":"POST","url":"/v1/responses","bytes":8183}

$ lsof -nP -iTCP:<isolated-route-port> -sTCP:LISTEN  # before restart
node  13486  ...  TCP 127.0.0.1:<isolated-route-port> (LISTEN)

$ openclaw gateway restart --json
{"action":"restart","ok":true,"result":"restarted","service":{"label":"LaunchAgent","loaded":true}}
restart.elapsed_ms=11542

$ cat gateway-restart.log
[2026-09-04T23:35:53.204Z] openclaw gateway lifecycle source=cli action=restart mode=enable interactive=0
[2026-09-04T23:36:00Z] openclaw restart attempt source=handoff mode=start-after-exit target=<isolated-label> pid=13430 interactive=0
[2026-09-04T23:36:01.939Z] openclaw gateway lifecycle source=cli action=restart mode=kickstart interactive=0
[2026-09-04T23:36:02Z] openclaw restart done source=handoff mode=start-after-exit interactive=0

$ grep -E 'claimant-(ready|signal)|wrapper-child-exit' fake-tailscale.events.jsonl
{"at":"2026-09-04T23:35:50.060Z","event":"claimant-ready","pid":13486,"ppid":13484,"pgid":13484,"routePort":"<isolated-route-port>"}
{"at":"2026-09-04T23:35:58.297Z","event":"claimant-signal","pid":13486,"ppid":13484,"pgid":13484,"signal":"SIGTERM"}
{"at":"2026-09-04T23:35:58.302Z","event":"wrapper-child-exit","pid":13484,"ppid":13483,"pgid":13484,"childPid":13486,"code":0,"signal":null}
{"at":"2026-09-04T23:36:03.631Z","event":"claimant-ready","pid":13852,"ppid":13850,"pgid":13850,"routePort":"<isolated-route-port>"}

$ launchctl print <isolated-label>  # after restart
state = running
exit timeout = 20
runs = 2
pid = 13733
last exit code = 0

$ lsof -nP -iTCP:<isolated-route-port> -sTCP:LISTEN  # after restart
node  13852  ...  TCP 127.0.0.1:<isolated-route-port> (LISTEN)

$ jq '{ok,ts,durationMs}' health.after.json
{"ok":true,"ts":1788564964548,"durationMs":2}

$ cat agent.stdout
{"status":"timeout","summary":"aborted","stopReason":"restart","timeoutPhase":"gateway_draining"}

$ openclaw gateway uninstall --json
{"action":"uninstall","ok":true,"result":"uninstalled","service":{"label":"LaunchAgent","loaded":false}}

$ teardown-readback
launchagent=absent plist=absent state_dir=absent isolated_listeners=0 proof_processes=0

Owner acceptance

  • Assurance: Elevated; blast radius is launchd-managed Gateway restart availability.
  • Maintainer decision: accept the current fail-closed immediate cutoff when the loaded job is unreadable or lacks a valid 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.
  • Falsifier: restart exceeds the loaded supervisor budget; an old claimant survives; replacement cannot reacquire the listener; signal classification delays enforcement; a later signal weakens a stricter cutoff; or deadline enforcement is disarmed during cleanup, handoff, recovery, or log flushing.
  • Rollback: revert this PR; no persisted-state or public API migration.

Worked on by

  • PollyBot13

AI-assisted: yes.

@clawsweeper

clawsweeper Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes size: M labels Aug 19, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 19, 2026
@clawsweeper

clawsweeper Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 5, 2026, 5:54 AM ET / 09:54 UTC.

ClawSweeper review

What this changes

The 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
Reviewed head: 5817467d30a50e4fadfbfeed0b7b5bfaefaa1235
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent lifecycle repair with useful race coverage and concrete native restart evidence.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The captured exact-head terminal trace exercises the production Gateway under real macOS launchd with stalled work and an isolated claimant: restart finishes in 11.542 seconds, the old listener exits, and replacement health succeeds. It supports the graceful deadline repair; unreadable-job and bootout compatibility remain separate unresolved risks.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured exact-head terminal trace exercises the production Gateway under real macOS launchd with stalled work and an isolated claimant: restart finishes in 11.542 seconds, the old listener exits, and replacement health succeeds. It supports the graceful deadline repair; unreadable-job and bootout compatibility remain separate unresolved risks.
Evidence reviewed 11 items Introduced patch and merge ownership: The merge-base comparison identifies only the six lifecycle and timeout files. The inspected test merge has the pinned base followed by the exact PR head as parents; its comparison against that base contains the same six paths.
Current main still needs the repair: Current main retains the 300,000ms restart drain and 325,000ms shutdown budget, without loaded-launchd-timeout discovery. All six PR paths are unchanged between the merge base and fetched main.
Shipped supervisor budget: The latest release’s LaunchAgent generator sets ExitTimeOut to 20 seconds. Its run-loop blob was unavailable locally and could not be retrieved because DNS failed; no shipped-fix claim is made.
Findings None None.
Security None None.

How this fits together

The 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]
Loading

Decision needed

Question Recommendation
Should an unreadable loaded LaunchAgent timeout force immediate exit, or retain a bounded opportunity for graceful cleanup? Preserve bounded graceful cleanup: Choose a bounded cleanup policy for unreadable jobs and validate stop and managed-update recovery on an existing LaunchAgent.

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

  • Resolve merge risk (P1) - When loaded-job inspection fails, existing LaunchAgents receive an immediate shutdown cutoff that can interrupt active work and resource cleanup.
  • Resolve merge risk (P1) - The native trace does not demonstrate recovery from that cutoff during stop or managed-update bootout, where the service may already be disabled.
  • Complete next step (P2) - Resolve the unreadable-timeout policy with the lifecycle owner and validate the chosen behavior during existing-LaunchAgent stop and managed-update bootout.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +371, Tests +751. Total +1122 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 444 73 +371
Tests 2 760 9 +751
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 1204 82 +1122

Review metrics

Metric Value Why it matters
Production versus test growth Production net +371 lines; tests net +751 lines The stated growth implements missing deadline ownership across lifecycle stages, with signal-order regressions rather than generated or dependency churn.
Shutdown policy 1 failure policy changed; 0 configuration keys added Unreadable loaded timeouts now trigger immediate cutoff for launchd-managed SIGTERM.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #126445
Summary: This PR is the candidate repair for the open launchd/Tailscale lifecycle report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Resolve the unreadable-job policy (recommended)
    Retain the deadline repair while selecting and validating bounded graceful behavior for existing LaunchAgents whose loaded timeout cannot be read.
  2. Own immediate-exit behavior
    Accept the compatibility change explicitly after confirming stop and managed-update recovery when inspection fails.

Technical review

Best 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.

Labels

Label justifications:

  • P1: The linked report establishes a managed restart failure that can prevent the Gateway and its channels from recovering.
  • merge-risk: 🚨 compatibility: Existing LaunchAgents lose their graceful shutdown window when loaded-timeout inspection fails.
  • merge-risk: 🚨 availability: Immediate cutoff during disabled-service update parking relies on recovery behavior not demonstrated by the native trace.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The captured exact-head terminal trace exercises the production Gateway under real macOS launchd with stalled work and an isolated claimant: restart finishes in 11.542 seconds, the old listener exits, and replacement health succeeds. It supports the graceful deadline repair; unreadable-job and bootout compatibility remain separate unresolved risks.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured exact-head terminal trace exercises the production Gateway under real macOS launchd with stalled work and an isolated claimant: restart finishes in 11.542 seconds, the old listener exits, and replacement health succeeds. It supports the graceful deadline repair; unreadable-job and bootout compatibility remain separate unresolved risks.

Evidence

What I checked:

  • Introduced patch and merge ownership: The merge-base comparison identifies only the six lifecycle and timeout files. The inspected test merge has the pinned base followed by the exact PR head as parents; its comparison against that base contains the same six paths. (a92aca6371f6)
  • Current main still needs the repair: Current main retains the 300,000ms restart drain and 325,000ms shutdown budget, without loaded-launchd-timeout discovery. All six PR paths are unchanged between the merge base and fetched main. (src/cli/gateway-cli/run-loop.ts:513, f4fa8a6798cb)
  • Shipped supervisor budget: The latest release’s LaunchAgent generator sets ExitTimeOut to 20 seconds. Its run-loop blob was unavailable locally and could not be retrieved because DNS failed; no shipped-fix claim is made. (src/daemon/launchd-plist.ts:9, ad6fe23aecb9)
  • Owner and cleanup boundary: The CLI grants the run loop exclusive process ownership at run.ts:1115. Server close invokes Tailscale cleanup at server-close.ts:599; the existing claimant worker handles stop messages, signals, and IPC disconnect. The patch changes deadline coordination rather than route ownership or authentication. (src/cli/gateway-cli/run.ts:1115, 5817467d30a5)
  • Intentional compatibility change: Missing or invalid loaded-job timeout becomes a deadline at signal receipt. This applies to managed SIGTERM stops and restarts, not only Tailscale-enabled Gateways. (src/cli/gateway-cli/run-loop.ts:1278, 5817467d30a5)
  • Managed-update recovery boundary: Update parking disables the LaunchAgent before starting bootout. The helper restores the service when the parent exits without committing the update, making this sequence relevant to the unreadable-timeout decision. (src/infra/update-managed-service-handoff.ts:825, 5817467d30a5)

Likely related people:

  • Peter Steinberger: Raw commit 07a0b51 adds src/cli/gateway-cli/shutdown-hard-exit.ts:7 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 07a0b5170343; files: src/cli/gateway-cli/shutdown-hard-exit.ts)
  • Josh Avant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record the lifecycle owner’s unreadable-timeout choice and validate that policy on an existing LaunchAgent, including managed-update bootout.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (41 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-04T13:30:04.482Z sha 9b25c8589f13dd716cbcedf2bab87fcab81a9e0e :: blocked before merge. :: none
  • reviewed 2026-09-04T13:59:53.626Z sha 9b25c8589f13dd716cbcedf2bab87fcab81a9e0e :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T14:44:26.811Z sha 9b25c8589f13dd716cbcedf2bab87fcab81a9e0e :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T19:04:10.597Z sha 9b25c8589f13dd716cbcedf2bab87fcab81a9e0e :: blocked before merge. :: none
  • reviewed 2026-09-04T22:58:21.290Z sha 1c2867d9d00e4563d085c651ed4282c000c9a194 :: blocked before merge. :: none
  • reviewed 2026-09-04T23:14:38.421Z sha 1c2867d9d00e4563d085c651ed4282c000c9a194 :: blocked before merge. :: [P2] Cancel generic watchdogs when managed handoff takes over
  • reviewed 2026-09-04T23:52:23.596Z sha 5817467 :: blocked before merge. :: none
  • reviewed 2026-09-05T00:07:46.229Z sha 5817467 :: blocked before merge. :: none

@PollyBot13
PollyBot13 force-pushed the fix/launchd-tailscale-owner-lifecycle branch from 2776d1f to cbc85f2 Compare August 20, 2026 01:02
@PollyBot13

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 20, 2026
@PollyBot13

Copy link
Copy Markdown
Contributor Author

Current-main conflict resolved on 0ef4fa97bd2 with a normal merge commit (no force-push).

The two conflict sites combined both lifecycle invariants:

  • the detached worker/claimant process groups, IPC-disconnect fallback, and descendant cleanup from this PR;
  • current main's SIGINT/SIGTERM/SIGHUP cleanup and interactive-interrupt regression.

Post-merge verification:

  • src/infra/tailscale-route-owner.worker.test.ts: 6/6 passed;
  • the remaining focused supervisor, daemon lifecycle, Gateway run-loop, launchd plist, and Tailscale suites: 195/195 passed;
  • git diff --check upstream/main...HEAD passed.

The PR body now distinguishes the current merged-head test evidence from the earlier exact patch-head macOS process-boundary proof.

@clawsweeper clawsweeper Bot added clawsweeper-recovery-stuck rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. clawsweeper-recovery-stuck status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 25, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 3, 2026
@PollyBot13
PollyBot13 force-pushed the fix/launchd-tailscale-owner-lifecycle branch from c8c3906 to 26e68a3 Compare September 3, 2026 22:10
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 3, 2026
@PollyBot13
PollyBot13 force-pushed the fix/launchd-tailscale-owner-lifecycle branch from 26e68a3 to a3c475a Compare September 3, 2026 23:02
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 3, 2026
@PollyBot13

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

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: serve ... off only clears background handlers, so foreground-only conflicts need guidance to stop their confirmed owning CLI. Leaving #126445 and this PR open pending that decision.

@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

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.

@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

The recovery follow-up is now on main in #139283, merged as 837e0b2. #139261 remains the canonical orphan-prevention repair.

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 main.

Thanks again @PollyBot13; contributor credit is preserved. FYI @Patrick-Erichsen — this completes the named follow-up, and the existing assignment is unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributor-review Clawtributor pull request awaiting prioritized maintainer review cli CLI command changes merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: launchd restart can orphan the Tailscale claimant and crash-loop on port 443

5 participants