Skip to content

fix(tailscale): release managed routes after Gateway crashes - #139261

Merged
steipete merged 1 commit into
mainfrom
fix/tailscale-owner-parent-loss
Sep 5, 2026
Merged

steipete merged 1 commit into
mainfrom
fix/tailscale-owner-parent-loss

Conversation

@steipete

@steipete steipete commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where a macOS Gateway killed during restart could leave its foreground Tailscale claimant alive. That stale claimant kept HTTPS port 443 occupied, so replacement Gateways failed to start and entered a restart loop.

Closes #126445. Supersedes #126457 with a focused repair to process ownership, preserving @PollyBot13's report and contribution.

Why This Change Was Made

The cleanup worker now has its own POSIX process group, allowing it to observe Gateway IPC loss and terminate the foreground claimant even when the Gateway's entire process group is killed. It also handles IPC loss before its listeners are installed. Normal cleanup still waits for the claimant to exit; redundant startup Promise-settlement bookkeeping is removed.

This repairs the existing documented promise that losing the Gateway releases its managed route. It does not change launchd shutdown budgets or introduce the original PR's unreadable-timeout immediate-exit policy. It prevents new orphans; foreground claims left by pre-fix Gateways still require the operator to stop their confirmed owning process, because unrelated foreground routes cannot safely be identified from a port or process name alone.

User Impact

A replacement Gateway can reclaim its Tailscale route after the previous Gateway is killed. Windows retains its current process behavior. No configuration, database, protocol, or dependency changes.

Evidence

Exact head: d42ae5d4803578c714e3c96ef4b01d605672a867; tree 04fe99ddc4971fd5d178d8d02bc77a603bcb0950. Both remote source checkouts had no tracked diff after their builds.

  • Fresh independent Codex review: scoped-clean at P0–P2, no actionable findings. Diff-scoped deslop found no further behavior-neutral cleanup needed.
  • Exact-head CI 33983015562: success; 130 passing checks, 51 intentional skips, zero pending/failing checks.
  • Fresh Crabbox proof used provider blacksmith-testbox, lease tbx_01m1sbvw4vd9z61aznp28td9wn, backing lease workflow. Node 24.19.0, pnpm 12.3.4, Linux 6.6.141 x86_64. The leased command passed; lease cleanup can mark its backing workflow cancelled.
  • Both revisions installed with pnpm install --offline --frozen-lockfile and built with node --import ./scripts/tsx.mjs scripts/build-all.mts qaRuntime.
  • 55/55 focused Linux tests across four files passed: node scripts/run-vitest.mjs src/infra/tailscale-parent-loss.process.test.ts src/infra/tailscale-route-owner.worker.test.ts src/infra/tailscale.test.ts src/gateway/server-tailscale.test.ts. Prior macOS owner/process proof passed 7 tests; the pre-fix group-kill regression failed because the claimant survived.
  • Production +6/-7 (net -1); tests/support +114/-7 (net +107).

Real Gateway before/after

The probe ran the built openclaw.mjs gateway run CLI with isolated state/config and a synthetic PATH tailscale executable owning a real loopback TCP proxy. It exercised the production claim owner without VITEST or test-only runtime overrides. This is real Gateway/process/socket proof, not authenticated Tailscale or HTTPS proof; neither Tailscale binary was installed on the runner. It directly tests the changed POSIX ownership boundary. Local macOS process tests and the documented launchd job-group cleanup contract cover the platform-specific premise; a full native launchd Gateway run was not performed in this lane.

Before: e09a265b11112623addd4de2167ee6b34cd82719.
After: d42ae5d4803578c714e3c96ef4b01d605672a867.

The Gateway commands, from their respective checkout roots, were:

node openclaw.mjs gateway run --allow-unconfigured --port 41373 --bind loopback --tailscale serve
node openclaw.mjs gateway run --allow-unconfigured --port 36053 --bind loopback --tailscale serve

Each scenario killed the original Gateway's process group with SIGKILL, then launched a replacement with the same Gateway and route ports for that scenario.

Observation Before After
Initial Gateway and proxied route health HTTP 200, ok:true HTTP 200, ok:true
Original Gateway / cleanup worker group Both PGID 9204 Gateway PGID 12012; worker PGID 12068
After group SIGKILL Worker exited; claimant PID 9267 still alive under PPID 1 after 5,042 ms Gateway, worker, and claimant all absent after 31 ms
Replacement Exited 78 after EADDRINUSE; old claimant remained Same route port 45363 reclaimed; Gateway and route healthy after 1,976 ms
Cleanup All owned processes gone; neither listener remained All owned processes gone; neither listener remained

The temporary remote checkouts, state, configs, listeners and proof processes were removed. The command and wrapper returned success; the lease was stopped and its completed state verified. Evidence report SHA-256: b037576f3ffeb99b24c42dcb2d8d7f6ba0ee73454b714be8b098c32f6b82a1c5.

Review follow-through and upgrade scope

The latest ClawSweeper review identified no code findings. Its requested real-Gateway before/after evidence and rank-up move are satisfied above. Its serialized-state flag is a false positive: the existing { argv } IPC payload is unchanged; this diff changes a spawn option, removes a redundant local boolean, and handles already-closed IPC. No stored representation, schema, migration, or config changes exist. Stable v2026.9.1 contains the same process-group mismatch; newly started upgraded Gateways use the repaired owner. The maintainer explicitly selected prevention with operator-assisted recovery for historical ambiguous claims.

Follow-up identified during review: foreground-conflict diagnostics currently suggest a background route removal command; they should distinguish foreground ownership and direct operators to stop the confirmed owning CLI. Automatic termination of ambiguous historical claims remains out of scope.

Keep the IPC cleanup worker alive when the Gateway process group is killed,
so its detached foreground claimant exits and a replacement can bind the
same port. Handle IPC loss during worker startup and rely on native Promise
settlement instead of duplicate startup state.

Related: #126445, #126457. Preserve this prevention repair pending the
ownership decision for foreground orphans left by pre-fix Gateways; no
automatic reclamation of ambiguous existing foreground routes is added.

Co-authored-by: PollyBot13 <[email protected]>
@clawsweeper

clawsweeper Bot commented Sep 5, 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 size: S maintainer Maintainer-authored PR labels Sep 5, 2026
@steipete
steipete marked this pull request as ready for review September 5, 2026 18:06
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 5, 2026, 2:13 PM ET / 18:13 UTC.

ClawSweeper review

What this changes

Keeps the Tailscale cleanup worker alive after a Gateway process-group crash so it can release the managed route, with regression coverage for cleanup and port reacquisition.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: current main still has the process-group lifecycle defect, and this focused repair has no blocking correctness findings.

Priority: P1
Reviewed head: d42ae5d4803578c714e3c96ef4b01d605672a867

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused lifecycle repair with meaningful regression coverage and no blocking code findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate. Its captured body reports seven macOS process-fixture tests through the production claim owner, while real-Gateway crash/reclaim proof remains pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate. Its captured body reports seven macOS process-fixture tests through the production claim owner, while real-Gateway crash/reclaim proof remains pending.
Evidence reviewed 11 items Pinned patch and merge result: The original head records parent e09a265. The inspected test merge records f8d63c5 followed by the exact PR head; its production delta contains the same worker detachment, disconnected-startup cleanup, and settlement simplification.
Current-main defect remains: Current main forks the cleanup worker without detachment, while the worker launches its claimant detached. Killing the Gateway process group therefore also kills its cleanup worker while leaving the claimant outside that group. Both production files are unchanged between the pinned merge base and fetched main.
Lifecycle owner and termination boundary: The complete worker retains idempotent stop, claimant-group SIGTERM, two-second SIGKILL escalation, and waiting for child close. The added connected-state check covers IPC loss before listener installation. Termination delegates through the local process helper to packages/agent-core/src/harness/env/kill-tree.ts; this path has no Codex runtime dependency.
Findings None None.
Security None None.

How this fits together

Managed Tailscale Serve and Funnel expose the Gateway through a foreground CLI process. A cleanup worker owns that process and releases its route when Gateway communication closes.

flowchart TD
  A[Gateway starts managed exposure] --> B[Cleanup worker in separate process group]
  B --> C[Foreground Tailscale claimant]
  C --> D[Gateway HTTPS route]
  E[Gateway exits or crashes] --> F[IPC connection closes]
  F --> B
  B --> G[Stop claimant and release route]
Loading

Before merge

  • Resolve merge risk (P1) - The captured evidence does not yet demonstrate supervised real-Gateway crash recovery; the reported process-fixture run does not establish the complete launchd flow.
  • Complete next step (P2) - Publish the already-promised real-Gateway before/after proof, or document the concrete infeasibility required by repository validation policy.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source -1, Tests +107. Total +106 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 2 6 7 -1
Tests 4 114 7 +107
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 120 14 +106

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net -1; tests/support net +107 The repair simplifies the existing lifecycle owner while adding process-kill and port-reacquisition coverage.

Stored data model

Persistent data-model change detected: serialized state: src/infra/tailscale.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #126445
Summary: This PR is a candidate repair for the canonical orphaned-claimant report; the deadline-based alternative overlaps but covers a different prevention mechanism.

Members:

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

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep crash cleanup in the existing route owner, with automatic release of newly managed claims and explicit operator recovery for already-orphaned legacy claims.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep crash cleanup in the existing route owner, with automatic release of newly managed claims and explicit operator recovery for already-orphaned legacy claims.

Do we have a high-confidence way to reproduce the issue?

Yes, source-backed: kill the Gateway's POSIX process group while it holds a managed route; current main also loses the cleanup worker while its detached claimant survives. This read-only review did not execute that scenario.

Is this the best way to solve the issue?

Yes: repairing the existing process owner addresses hard crashes directly without changing launchd drain policy or terminating ambiguously owned historical processes.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against bd381bffb29d.

Labels

Label changes:

  • add P1: An orphaned managed Tailscale claimant can prevent replacement Gateways from starting and sustain a restart loop.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate. Its captured body reports seven macOS process-fixture tests through the production claim owner, while real-Gateway crash/reclaim proof remains pending.

Label justifications:

  • P1: An orphaned managed Tailscale claimant can prevent replacement Gateways from starting and sustain a restart loop.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate. Its captured body reports seven macOS process-fixture tests through the production claim owner, while real-Gateway crash/reclaim proof remains pending.

Evidence

What I checked:

  • Pinned patch and merge result: The original head records parent e09a265. The inspected test merge records f8d63c5 followed by the exact PR head; its production delta contains the same worker detachment, disconnected-startup cleanup, and settlement simplification. (src/infra/tailscale.ts:274, d42ae5d48035)
  • Current-main defect remains: Current main forks the cleanup worker without detachment, while the worker launches its claimant detached. Killing the Gateway process group therefore also kills its cleanup worker while leaving the claimant outside that group. Both production files are unchanged between the pinned merge base and fetched main. (src/infra/tailscale.ts:269, bd381bffb29d)
  • Lifecycle owner and termination boundary: The complete worker retains idempotent stop, claimant-group SIGTERM, two-second SIGKILL escalation, and waiting for child close. The added connected-state check covers IPC loss before listener installation. Termination delegates through the local process helper to packages/agent-core/src/harness/env/kill-tree.ts; this path has no Codex runtime dependency. (src/infra/tailscale-route-owner.worker.ts:151, d42ae5d48035)
  • Caller, sibling modes, and documented contract: Gateway startup registers the exposure cleanup through src/gateway/server-start.ts. Both Serve and Funnel call the same claim owner; existing tests cover cleanup, startup failure, privileged errors, and preservation of external routes. The documented contract explicitly promises route release when the Gateway is lost. Public docs: docs/gateway/tailscale.md. (docs/gateway/tailscale.md:124, d42ae5d48035)
  • Node process and IPC contract: The patch directly uses node:child_process.fork. Node documents that POSIX detachment creates a new process group and session. Its v24.15.0 IPC implementation disconnects on EOF, clears connected, and emits disconnect, supporting both the crash-cleanup path and startup-state check. Inspected Node documentation and IPC source. (lib/internal/child_process.js:622)
  • Foreground route dependency contract: OpenClaw explicitly executes Serve/Funnel with --bg=false and recognizes Tailscale's readiness output. Upstream runServeCombined associates foreground configuration with its watch session and prints readiness after SetServeConfig succeeds; WatchNotifications defers DeleteForegroundSession, which removes the session's routes. Inspected CLI source, watch cleanup, and route deletion. (cmd/tailscale/cli/serve_v2.go:464)

Likely related people:

  • Josh Avant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jacqueline Henriksen: 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.

  • Attach the promised real-Gateway before/after results showing claimant release and replacement recovery, with private details redacted.

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.

@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Land-ready review for d42ae5d: the PR body now contains the fresh Crabbox before/after trace, exact Gateway/build/test commands, source identities and proof limitations.

The real Linux Gateway comparison reproduced the pre-fix PPID-1 claimant and replacement exit 78. The fixed worker/claimant exited within 31 ms, and replacement Gateway plus same-port route health passed within 1.976 seconds. This uses a synthetic PATH Tailscale CLI with real IPC/process/socket behavior; it is not authenticated tailnet/TLS or native launchd Gateway proof. All 55 focused tests and both runtime builds passed. The Testbox lease was stopped and cleanup verified: https://github.com/openclaw/openclaw/actions/runs/33982892355.

Independent Codex autoreview is scoped-clean at P0–P2. Exact-head CI is successful with 130 passing checks, 51 intentional skips and no pending/failing checks: https://github.com/openclaw/openclaw/actions/runs/33983015562.

The latest ClawSweeper proof request and rank-up move are addressed in the body. The serialized-state flag is inapplicable: the { argv } IPC payload is unchanged, and there is no stored format, schema, config or migration change. Maintainer direction is the focused prevention repair with operator-assisted recovery for already-orphaned historical claims. Production net -1; tests/support net +107. Contributor credit is retained.

@steipete
steipete merged commit eb08c36 into main Sep 5, 2026
252 checks passed
@steipete
steipete deleted the fix/tailscale-owner-parent-loss branch September 5, 2026 18:28
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 5, 2026
* commit '911d7d5b0c107f7274f2415ca9655dcc6105f0e8': (867 commits)
  fix(skills): deliver pending Workshop approval controls (#139248)
  fix(gateway): deliver loopback ask_user prompts to the originating channel (#138831)
  docs: keep root agent instructions focused on repository policy (#139258)
  fix(matrix): exclude archived state roots from scans and selection (#112329)
  perf(agents): prepare exact tool names once per catalog batch (#139267)
  fix: preserve Swarm progress and simplify owner plumbing (#139269)
  fix(tailscale): release claims after gateway process-group exit (#139261)
  refactor(cli): simplify lazy command registration (#139108)
  test(ui): retain synthetic widget failure evidence (#139229)
  fix(buzz): keep implicit replies at thread root (#138879)
  test(diagnostics): await graceful Gateway shutdown before cleanup (#139247)
  fix(ci): unblock releases with different tooling package managers (#139259)
  feat(ui): add social preview links for private sessions (#139250)
  fix(codex): retain failed conversations for guarded continuation (#139246)
  chore(ui): refresh control ui locales (#139200)
  fix(ci): run browser checks for real-gateway inputs (#139256)
  fix(llama-cpp): reconcile managed router state before requests (#136363)
  chore(i18n): refresh native locales (#139237)
  refactor(worker): unify inference payload handling (#139245)
  refactor(terminal): replay wrapped prefixes in one pass (#139240)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 6, 2026
…claw#139261)

Keep the IPC cleanup worker alive when the Gateway process group is killed,
so its detached foreground claimant exits and a replacement can bind the
same port. Handle IPC loss during worker startup and rely on native Promise
settlement instead of duplicate startup state.

Related: openclaw#126445, openclaw#126457. Preserve this prevention repair pending the
ownership decision for foreground orphans left by pre-fix Gateways; no
automatic reclamation of ambiguous existing foreground routes is added.

Co-authored-by: PollyBot13 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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

1 participant