Skip to content

fix: gateway stop/restart refuses a healthy gateway when the Windows process snapshot misses - #146387

Merged
steipete merged 2 commits into
openclaw:mainfrom
fszcd:fix-145984-windows-port-ownership
Sep 13, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
fszcd:fix-145984-windows-port-ownership

Conversation

@fszcd

@fszcd fszcd commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #145984

What Problem This Solves

Fixes an issue where users on Windows running openclaw gateway stop --force or gateway restart --force would be refused with gateway port 18789 is still busy ... remaining listener ownership could not be verified even though the gateway on the configured port is healthy, serving, and plainly killable (Stop-Process -Id <pid> -Force works from a non-elevated shell).

On Windows, ownership proof for the Scheduled Task gateway depended entirely on the full Win32_Process CIM snapshot (readWindowsProcessSnapshot). When that snapshot is unavailable (CIM timeout/failure — or, as demonstrated below, its JSON output exceeding Node's 1 MB spawnSync buffer on a busy machine), the CLI gave up on a gateway it should be able to identify as its own, and the error named no PID to act on.

Why This Change Was Made

Two narrow changes, keeping the existing conservative kill contract:

  1. When the full-process snapshot is unavailable, stop/restart now verifies the actual port listeners per PID (CIM CommandLine, WMIC fallback) with the exact same proof standard as before — persisted task argv plus --port match, with and without the supervisor flag. Same proof, more resilient retrieval.
  2. When ownership still cannot be verified, the thrown error now lists the remaining listener PIDs, whether each looks like an OpenClaw gateway, and the manual remediation (Stop-Process -Id <pid> -Force), per option (b) in the issue.

Non-goals: no loosening of ownership proof (unverified or foreign-checkout listeners are never killed), no behavior change when the CIM snapshot works, no changes off the Windows path besides the error text. The argv-mismatch trigger family (e.g. hand-edited launcher redirections) is intentionally left to #137374 and to the new actionable diagnostics here, rather than relaxing the exact-argv kill proof.

User Impact

  • Windows users hitting the false "port is still busy" refusal during transient CIM trouble now get a clean stop/restart instead of a dead end.
  • When the refusal is legitimate (e.g. a same-port gateway from another checkout or a drifted launcher), the error now names the exact listener PID(s) and how to resolve them, instead of requiring manual Get-NetTCPConnection hunting.

Evidence

Real Windows 11 runs — this branch built from source, packed via scripts/package-openclaw-for-docker.mjs, installed from the tarball, gateway installed as the real OpenClaw Gateway Scheduled Task (build stamp OpenClaw 2026.9.4 (6141a57)).

  1. Snapshot-unavailable fallback, before/after (the core change). Setup: gateway listener started outside the task instance with the exact persisted argv (supervisor + gateway child, mirroring a watchdog-restarted gateway that schtasks /End cannot kill); the full-process CIM snapshot forced to fail for real by flooding ~850 processes with long command lines, pushing the snapshot JSON past Node's 1 MB spawnSync maxBuffer (verified directly: spawnSync returns ENOBUFS; output was 1,140,175 bytes). This mirrors a genuinely busy developer machine.
    • Stock npm [email protected] (3a9d69d): gateway stop --force → Gateway stop failed: Error: gateway port 18789 is still busy after stop; remaining listener ownership could not be verified; listener still alive and serving afterwards — the exact reported failure.
    • This branch, identical setup: gateway stop --force → Stopped Scheduled Task: OpenClaw Gateway; port free, owned process gone (per-PID CIM verification → taskkill → port release confirmed).
    • This branch gateway restart --force in the same setup → Restarted Scheduled Task: OpenClaw Gateway; old listener terminated, new task-spawned gateway listening on 18789.
  2. Happy path unchanged. With a working snapshot, gateway restart --force and stop --force against the task-owned gateway both succeed.
  3. Actionable refusal when verification legitimately fails. Gateway started with a drifted argv (manual node dist\index.js gateway --port 18789):
    • Stock: ... remaining listener ownership could not be verified — dead end.
    • This branch: ... could not be verified. Remaining listener(s): pid 47792 (node.exe, openclaw gateway). If one of these is this gateway, stop it with "Stop-Process -Id <pid> -Force" and retry. Following the hint then lets stop --force succeed.
  4. Published updater on an existing installation. Ran the stock 2026.9.4 npm install (global prefix, real Scheduled Task gateway running) through the official openclaw update flow with the candidate served as [email protected] from a loopback registry (OPENCLAW_UPDATE_PACKAGE_SPEC=openclaw + NPM_CONFIG_REGISTRY=http://127.0.0.1, the repo's documented local integration seam). The updater resolved the target, staged and packed the candidate, ran candidate Doctor including a live inference probe (HTTP 200 from the configured provider) and migration rehearsal, and exercised the gateway service stop/start machinery this PR touches. The run then stopped at a deterministic Windows EBUSY on unlink openclaw-agent-exec-*\state\openclaw.sqlite inside the rehearsal's agent-exec cleanup — a pre-existing Windows temp-file race in the rehearsal harness (no processes hold the file afterwards; same failure with TEMP redirected to a different drive), in code this PR does not touch. After every failed attempt the installation rolled back cleanly: still 2026.9.4, gateway running and listening (pid unchanged). The update path was equally exercised with a same-version control target, which passed staging/install until the intentionally faked version check.

Tests — src/daemon/schtasks.stop.test.ts (Windows host): 194/196 pass across the stop/restart/install/startup-fallback files; the only 2 failures (accepts a localized /End failure when COM proves the task is disabled/ready) fail identically on unmodified main here (pre-existing Windows environment issue, unrelated). New/updated coverage:

  • refuses a same-port gateway from another checkout when the CIM snapshot is unavailable — the per-PID fallback still refuses a foreign gateway; the error names pid 6262 + openclaw gateway.
  • reports remaining listeners when the port stays busy before restart — restart error now includes the remaining listener PID.
  • Existing ownership tests now also assert the owned PID is actually terminated via taskkill on Windows, while does not kill an unrelated listener... asserts the unrelated PID is never touched.

Static checks — pnpm tsgo, pnpm tsgo:core:test, pnpm tsgo:test:root: clean. oxlint on the three touched files: clean. oxfmt --check: clean.

@clawsweeper

clawsweeper Bot commented Sep 12, 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 size: S labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 13, 2026, 3:00 AM ET / 07:00 UTC (Revision 4).

ClawSweeper review

What this changes

Adds per-process ownership verification when Windows cannot retrieve its full process snapshot, and includes listener identities and recovery instructions in Gateway stop/restart errors.

Merge readiness

⛔ Blocked before merge - 3 items remain

This remains a useful fix absent from current main. The updated Windows evidence addresses the earlier stop/restart reproduction gap, and no blocking code defect was found; the required published-updater compatibility evidence remains outstanding.

Priority: P2
Reviewed head: 9ad33b3d8fa1cd4c6054c68580e22faf6f6354ff

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and improved Windows evidence are useful, but the required upgrade compatibility proof is incomplete.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The updated Windows 11 observations sufficiently exercise snapshot failure through per-PID inspection, real termination, port release, restart, and diagnostic refusal. The remaining gap is the stronger AGENTS.md service-lifecycle requirement: a published updater operating on an existing installation with the candidate; direct tarball installation does not establish that path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The updated Windows 11 observations sufficiently exercise snapshot failure through per-PID inspection, real termination, port release, restart, and diagnostic refusal. The remaining gap is the stronger AGENTS.md service-lifecycle requirement: a published updater operating on an existing installation with the candidate; direct tarball installation does not establish that path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 7 items Current main still needs this fallback: At fetched main, resolveScheduledTaskOwnedGatewayPids returns an empty array on Windows when readWindowsProcessSnapshot fails. The supplied latest-release evidence also reports this failure on v2026.9.4; neither related item establishes a merged replacement.
Fallback preserves ownership predicates: The introduced fallback requires an actual listener, matching port, and the same normalized installed argv or supervisor argv. The existing termination owner still checks lifecycle authority before native termination. Port inspection obtains command lines through per-PID CIM/WMIC queries.
Updated real Windows evidence: The supplied PR body, captured under sourceRevision a65ceab89cde9739198f4912874729db0e63f97ab4f27df5bc8343d77584e5ab, reports Windows 11 runs with a real Scheduled Task and snapshot ENOBUFS at 1,140,175 bytes: stock stop fails, the candidate stops the owned process and frees the port, and candidate restart produces a new listener. It also reports working-snapshot success and refusal of drifted argv. These observations address the previous core-proof request; they are contributor-reported, not executions performed by this review.
Findings None None.
Security None None.

How this fits together

The Windows service controller translates Gateway lifecycle commands into Scheduled Task operations and process termination. It compares running processes with the installed launch command before stopping them, then verifies that the listening port is released.

flowchart TD
  A[Gateway stop or restart] --> B[Installed task command]
  B --> C[Read Windows process snapshot]
  C --> D[Verify command and port]
  C -->|Snapshot unavailable| E[Inspect individual port listeners]
  E --> D
  D -->|Owned| F[Terminate and verify port release]
  D -->|Unverified| G[Refuse and describe listeners]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The updated Windows 11 observations sufficiently exercise snapshot failure through per-PID inspection, real termination, port release, restart, and diagnostic refusal. The remaining gap is the stronger AGENTS.md service-lifecycle requirement: a published updater operating on an existing installation with the candidate; direct tarball installation does not establish that path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P2) - Direct candidate stop/restart runs do not establish how a published updater reaches this fallback while preserving an existing Windows service installation.
  • Complete next step (P2) - Add the previously requested published-updater × candidate Windows upgrade evidence to the PR body, preserving the existing stop/restart proof. Redacted terminal output or logs are sufficient; remove credentials, private endpoints, and other private details. Updating the body should trigger re-review; if it does not, ask a maintainer to comment @clawsweeper re-review.
Agent review details

Security

None.

PR surface

Source +66, Tests +80. Total +146 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 80 14 +66
Tests 1 86 6 +80
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 166 20 +146

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #145984
Summary: This PR supplies snapshot-failure recovery and requested diagnostics for the linked report; launcher-redirection normalization is adjacent work.

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 the existing ownership checks and resilient per-PID retrieval, with published-updater compatibility demonstrated for an existing Windows installation.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the existing ownership checks and resilient per-PID retrieval, with published-updater compatibility demonstrated for an existing Windows installation.

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

Yes: current main returns no owned process after snapshot failure, and the contributor reports a concrete Windows ENOBUFS reproduction against v2026.9.4. This read-only review did not execute a current-main reproduction.

Is this the best way to solve the issue?

Yes: reusing per-PID process inspection and the existing exact-argv ownership predicate is a focused repair; the separate launcher-redirection fix does not cover this failure.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1cc5eea5e2d6.

Labels

Label justifications:

  • P2: Repairs a bounded Windows service-control failure when full process inspection fails while the Gateway remains reachable.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The updated Windows 11 observations sufficiently exercise snapshot failure through per-PID inspection, real termination, port release, restart, and diagnostic refusal. The remaining gap is the stronger AGENTS.md service-lifecycle requirement: a published updater operating on an existing installation with the candidate; direct tarball installation does not establish that path. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current main still needs this fallback: At fetched main, resolveScheduledTaskOwnedGatewayPids returns an empty array on Windows when readWindowsProcessSnapshot fails. The supplied latest-release evidence also reports this failure on v2026.9.4; neither related item establishes a merged replacement. (src/daemon/schtasks-process.ts:175, 1cc5eea5e2d6)
  • Fallback preserves ownership predicates: The introduced fallback requires an actual listener, matching port, and the same normalized installed argv or supervisor argv. The existing termination owner still checks lifecycle authority before native termination. Port inspection obtains command lines through per-PID CIM/WMIC queries. (src/daemon/schtasks-process.ts:195, 9ad33b3d8fa1)
  • Updated real Windows evidence: The supplied PR body, captured under sourceRevision a65ceab89cde9739198f4912874729db0e63f97ab4f27df5bc8343d77584e5ab, reports Windows 11 runs with a real Scheduled Task and snapshot ENOBUFS at 1,140,175 bytes: stock stop fails, the candidate stops the owned process and frees the port, and candidate restart produces a new listener. It also reports working-snapshot success and refusal of drifted argv. These observations address the previous core-proof request; they are contributor-reported, not executions performed by this review.
  • Negative ownership coverage: The changed tests exercise stop/restart boundaries, assert Windows taskkill targets, and reject a foreign-checkout listener. Foreign-listener preservation remains test-backed; the reported live drifted-argv refusal provides additional negative-path evidence. No weakening of the ownership predicate was found. (src/daemon/schtasks.stop.test.ts:741, 9ad33b3d8fa1)
  • Remaining lifecycle proof requirement: Root policy requires a published-driver × candidate cell for service-lifecycle changes. The complete supplied body describes tarball installation and direct lifecycle commands, but no upgrade initiated by the published updater against an existing installation. This is also the concrete outstanding request in the previous completed review. (AGENTS.md:69, 9ad33b3d8fa1)
  • Related work has distinct scope: [Bug]: Windows - gateway restart/stop fails with "port is still busy; remaining listener ownership could not be verified" against a healthy gateway #145984 is the open report this PR proposes to resolve. fix(daemon): restart Windows gateways with redirected launcher output #137374 remains open and handles launcher redirection tokens causing argv mismatch, a different trigger that does not replace snapshot-failure recovery.

Likely related people:

  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: 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.

  • Add a redacted published-updater × candidate result using an existing Windows installation, showing service recovery and retained settings.

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 (3 earlier review cycles)
  • reviewed 2026-09-12T20:04:16.197Z sha 6141a579304c279025ed90b5ea0e33b13b80d38c :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-12T22:31:25.668Z sha 0636dc06a0813e01d6c72941f2769a2c6642cc7f :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-13T04:59:31.933Z sha 9ad33b3 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 12, 2026
…misses (openclaw#145984)

On Windows, stop/restart ownership proof for the Scheduled Task gateway
relied entirely on the full Win32_Process CIM snapshot. When that
snapshot is unavailable (CIM timeout/failure) the CLI refused to touch a
healthy gateway with "remaining listener ownership could not be
verified", forcing manual process hunting.

- Fall back to verifying the actual port listeners per PID (CIM
  CommandLine, WMIC fallback) with the same persisted-argv + port proof
  standard, so a healthy owned gateway is still stopped cleanly.
- When ownership still cannot be verified, include the remaining
  listener PIDs, whether each looks like an OpenClaw gateway, and the
  manual Stop-Process remediation in the thrown error.

Unverified or foreign-checkout listeners are still never killed.
@fszcd
fszcd force-pushed the fix-145984-windows-port-ownership branch from 0636dc0 to 9ad33b3 Compare September 13, 2026 04:50
@steipete
steipete merged commit 9c295a5 into openclaw:main Sep 13, 2026
224 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 13, 2026
* commit '2acbeee461474b6ba41f5186ae1a4e0e80f4087a': (117 commits)
  fix(ui): import the shared deferred helper in sidebar scope tests (#146862)
  fix(ui): copy chat content from its context menu (#146679)
  perf(memory): defer legacy sidecar writer imports (#146815)
  fix(e2e): accept expected Kitchen Sink worker rejection (#146681)
  fix(ui): distinguish absolute and relative file links (#146572)
  feat(ui): keep file previews in tabs and render HTML (#146672)
  refactor: reuse shared deferred promises in UI tests (#146670)
  fix: gateway stop/restart refuses a healthy gateway when the Windows process snapshot misses (#146387)
  improve(crabbox): keep healthy cloud desktops warm on resume (#146816)
  fix: report blocked SQLite WAL checkpoints in status and doctor (#146775)
  feat: share browser dashboards with agents (#146702)
  fix(doctor): continue repairs after legacy agent directory collisions (#146092)
  feat(agents): retry cyber-refused embedded turns on Daybreak (#145291)
  fix: restore media uploads through protected egress (#144902)
  refactor(qa): share capture filter rendering (#146696)
  fix(cli): keep running stream jobs visible as running (#146793)
  refactor(parallels): share gateway readiness loop (#146694)
  fix(sessions): avoid rewriting already-consumed input on release (#146795)
  fix: preserve scheduled conversation delivery after Doctor (#146794)
  perf(ui): avoid redundant session-row provenance work (#146797)
  ...
@fszcd
fszcd deleted the fix-145984-windows-port-ownership branch September 13, 2026 08:55
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…process snapshot misses (openclaw#146387)

Windows Scheduled Task Gateway stop/restart now verifies actual listening PIDs when the full Win32_Process snapshot is unavailable, including CIM failure or oversized snapshot output. The existing persisted argv, port, supervisor, and lifecycle-authority checks remain in place; foreign listeners are refused with their identities and recovery guidance.

Exact-head CI and focused ownership/diagnostic tests pass. The restart-listener diagnostic regression fails before the fix and passes after it. Contributor-reported Windows evidence is preserved in the PR; independent native Windows and published-updater compatibility runs remain documented proof gaps accepted for this landing.

Closes openclaw#145984

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

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Windows - gateway restart/stop fails with "port is still busy; remaining listener ownership could not be verified" against a healthy gateway

2 participants