Skip to content

fix: wait for final chat writes during restart handoff - #196493

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-handoff-refusal-names-holder-20260919
Nov 10, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-handoff-refusal-names-holder-20260919

Conversation

@steipete

@steipete steipete commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A restart handoff could refuse a final chat write that appeared after READY, even with most of the drain budget remaining. The refusal named no holder, and the deployment controller discarded the structured RPC failure.

User Impact

Finishing chat writes can settle before handoff without requiring a deferred deployment retry. A leaked holder still refuses handoff, now with its count, oldest observed terminal-event age, and bounded redacted run IDs in both journals and RPC error details. No configuration or migration is required.

Why This Change Was Made

The Gateway owns the wait, bounded by the original 30-second drain budget; the existing 15-second cleanup grace is untouched. It first attempts the synchronous handoff, so the idle path does no extra registry scan. Only a terminal-persistence refusal waits, then requester authority and final write custody are checked again. Freeze handoffs remain immediate. The controller change only preserves recognized diagnostic fields from failed JSON RPC output.

No new config, environment variables, state, caches, or schema. Production delta +100 lines supplies the bounded wait and diagnostics at their owners and the controller egress; tests +171 lines (matching allocation), standalone benchmark 150 lines, docs +8 lines. The eight-ID/256-character cap omits session keys; unknown ages are null. The controller's final status check may still defer before handoff if it observes custody there; this fixes the later handoff refusal.

Evidence

  • New RPC regression fails on parent a65cb61a7d14c7dbee97f92d442f9a378c88a688: pending writes return immediate, unattributed UNAVAILABLE. Final 77 focused Gateway/coordinator/activity tests pass (55.65 s wrapper wall time, mostly compilation). Coverage includes settlement after READY, refusal at the original deadline, resumed lease, oldest age, count/cap, control stripping, and redaction.
  • Hosted review identified the bundled updater's shorter handoff transport deadline. It now allows 30 seconds for handoff while other RPCs retain 10 seconds. The caller regression fails with a transport deadline before the fix and all 58 caller tests pass after it (41.55 s wrapper wall; mostly compilation), including a reply delayed 20 seconds. The follow-up also passed Codex autoreview P0–P2.
  • Controller regression fails on the parent because stderr is empty. 28 controller custody tests pass in Linux/Node 26 (6.114 s total; regression 0.413 s), plus shell syntax.
  • Core and all 27 core-test typecheck graphs, scripts types, final targeted lint/format, docs MDX and diff checks pass. The native Linux service-drain suite skips on macOS (15 cases); no live deployment was performed.
  • CI on the prior head found TS2769 in the new caller test: its RPC timeout is nullable. The fixture now normalizes null to undefined; the exact tsconfig.core.test.cli-update.json graph fails before and passes after. Targeted lint/format and Codex review pass. Production code is unchanged by this correction.
  • Authority-chain proof at final head: pnpm test src/gateway/server-methods.suspension-admission.test.ts passes 36/36 (44.33 s wrapper; compilation dominated). This harness calls the real core method registry, request dispatcher, captured operator guard, handoff handler/coordinator, host lifecycle and markGatewayRestartDraining; final assertions inspect the real restart-draining state. Allowed late settlement commits; read-only scope is FORBIDDEN; admin scope downgraded while waiting is FORBIDDEN with unchanged shutdown state. Mutation proof removing only the post-wait assertCurrent() makes the revoked case fail because shutdown actually commits (4 other cases pass); restoring it returns all 36 to green. The test does not launch a live Gateway or kill a process; it exercises the privileged commit boundary in-process with synthetic identities and fake time. Gateway-server test types, lint/format and independent Codex review pass.
  • pnpm check:changed completed. Its patch-local lint findings were fixed and rechecked. Its remaining dead-export failure reproduces exactly on the parent: 32 production + 10 full-tree findings, no additions/omissions; script scan passes. These are main regressions, not ignored failures. Attribution is below.
  • Final independent Codex autoreview, P0–P2: scoped-clean, no accepted/actionable findings, against the full local change from the parent above. Review includes the final fast-path simplification. Exact-head CI will provide broad proof.

Synthetic owner measurements

Command: node --import ./scripts/tsx.mjs scripts/perf/handoff-terminal-persistence-measure.ts --source-root <checkout> --mode <idle|refusal|settlement> --sessions 10800 --iterations 20. Five fresh-process A/A pairs and five interleaved A/B pairs per mode; warm measured operations exclude imports/setup. CPU is process CPU; allocations use HeapProfiler sampling including collected objects. Host load is recorded (comparison one-minute load roughly 13–24 on 32 CPUs).

Mode Baseline → candidate wall median / p95 (ms) CPU median (ms) Sampled allocation median (MiB) Outcome
Idle 14.10 / 14.86 → 14.21 / 15.51 14.20 → 14.48 10.41 → 10.98 100/100 accepted each
Direct pending-write refusal 12.08 / 14.39 → 11.76 / 15.55 12.35 → 11.81 12.87 → 13.88 100/100 refused each; candidate identifies holders
Writer settles after 100 ms 16.93 / 17.13 immediate refusal → 287.02 / 291.43 successful handoff 16.95 failed attempt → 40.74 successful attempt 13.56 failed attempt → 32.32 successful attempt 0/5 → 5/5 accepted

A/A wall median/p95: idle 10.90/13.41 vs 10.97/12.94 ms; refusal 12.22/14.22 vs 12.90/17.26 ms; settlement refusal 12.06/14.46 vs 12.22/13.98 ms. No microbenchmark speedup is claimed. Diagnostics add about 8% allocation to refusals. Waiting deliberately adds inventory work: the successful settlement attempt uses about 24 ms more CPU and 19 MiB more sampled allocation than one failed baseline attempt; this comparison excludes the baseline's later deployment retry. The requested behavioral gain is avoiding that deferral, while retaining write protection. An initial implementation added an idle scan and regressed CPU 25%; the final implementation deletes that scan (final idle CPU +2%).

This is an intentionally large in-memory registry fixture: 10,800 registered sources, ten pending terminal writes. No database/workspace I/O occurs at this boundary. It does not establish 35 GiB database, filesystem-scale, live model, or btrfs performance. CPU profiles confirm inventory traversal remains the dominant work.

Exact-parent local dead-export failures and source attribution

node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts reproduces byte-identical finding lists on a65cb61a7d14. No changed runtime module contributes a finding. Source/parent-relative attribution:

These remain main regressions for separate repair; no ignores, export removals, or unrelated fixes were added here.

The final CI main-parent test-line failure is reproduced and attributed: at 261b24e6bc8e3012687f5b27623b0e26f3defff6, the canonical checker reports 6,618,989 lines versus ceiling 6,618,696: 293 over. Initial parent a65cb61a7d14 is exactly at its ceiling. #194996 (e6afc3c54002b6c2aca7eefb2a12038482e93506) introduced 71 unallocated lines; #188748 (441b6139039d18701357e93665dcc59f787f439d) introduced 223; intervening #194429 removed 1. Canonical runs at both introducing commits reproduce the debt. Their affected files and the checker remain unchanged in the tested merge. This PR adds 171 lines with 171 allocation, leaving the same 293 debt. Final branch check against its original parent passes exactly at ceiling 6,618,478. These are main regressions for follow-up, not ignored noise.

ClawSweeper’s review on 88723a019477c0bd52af23a8b9431fa81917f11c cleared all three authority-proof items: no open checklist items, no findings, no security concern. OpenGrep, CodeQL Security High, and Critical Quality all passed on attempt 2 after confirmed GitHub SARIF-upload recovery. Main CI completed with all functional/type/lint/UI/PostgreSQL checks passing; only the reproduced inherited test-line ratchet and its aggregate gate remain red. The native pinned-head exception is limited to that attributed ratchet failure.

Keep late terminal persistence within the original drain budget and retain final custody checks. Report bounded redacted holder facts through Gateway RPC errors and both journals. Preserve the synchronous idle path and immediate freeze behavior.
@clawsweeper

clawsweeper Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes scripts Repository scripts size: M labels Nov 10, 2026
@steipete
steipete marked this pull request as ready for review November 10, 2026 07:00
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T07:28:04.990001Z 88723a0 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 038fb4289f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@steipete

Copy link
Copy Markdown
Contributor Author

Addressed review item 1 (bundled updater RPC deadline) in 20e342b41a442f53e2c8df97ac5363bcf3ed3f26:

  1. The updater now gives gateway.suspend.handoff a 30-second transport timeout; all other calls retain 10 seconds (caller). The regression drives the actual maintenance caller with a reply delayed 20 seconds and enforces the caller-selected transport deadline (test). It failed before the fix with transport deadline; all 58 caller tests now pass. The follow-up passed independent Codex review through P2.

The branch and PR evidence are current. The Gateway remains the sole settlement-wait owner. Final writes and live authority checks remain required.

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR waits for late final-chat writes within the existing drain budget and preserves bounded holder diagnostics through failed handoff responses.

Example: Handoff starts 6 seconds after preparation, with final-chat writes settling another second later.

  • Before: Handoff immediately returns UNAVAILABLE and the deployment must defer.
  • After: Handoff waits for settlement, rechecks requester authority and write custody, and commits shutdown within the original budget.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused implementation with sufficient authority-boundary proof; validation remains principally in-process and exact-head CI is not yet clear.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (terminal): For this maintainer-authored PR, the requested production-path authority harness is satisfied: the real dispatcher, operator guard, handler, coordinator, host lifecycle, and restart-draining owner exercise late settlement and reject read-only or mid-wait revoked callers before commitment. Public results report 36 passing cases and a mutation that fails when the post-wait guard is removed. This proves the privileged in-process commit boundary, without claiming live deployment or OS process-exit coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A restart controller can be forced to defer when a final chat write appears after readiness despite remaining drain time, and receives little useful holder information.
Reason: The maintainer-authored direction improves an existing administrative workflow while retaining write protection and the fixed suspension deadline.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a current handoff failure, resolves the previous authority-proof concern, and has no actionable introduced defect identified.

Priority: P2
Reviewed head: 88723a019477c0bd52af23a8b9431fa81917f11c

Before merge

None.

Findings

None.

Agent review details

How this fits together

Administrative suspension RPCs connect update controllers to the Gateway’s suspension coordinator, which checks active-work custody before transferring shutdown to the process-owning host.

flowchart LR
  A[Update controller] --> B[Gateway request dispatcher]
  B --> C[Suspension handler]
  C --> D[Suspension coordinator]
  D --> E[Final write inventory]
  D --> F[Host shutdown owner]
  C --> G[Bounded failure diagnostics]
Loading

Technical review

Best possible solution:

Keep settlement waiting in the existing suspension coordinator, preserving the original deadline, final custody checks, and live requester authority.

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

Pinned main immediately rejects a pending final write after readiness, and the submitted regression reports red-before/green-after evidence; this review verified the source path without executing it.

Is this the best way to solve the issue?

The change uses the existing coordinator and host owner, retains the synchronous idle path, and updates the affected caller timeout without adding competing state or shutdown policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 261b24e6bc8e.

Provenance checked

  • Final-write handoff refusal changes intended behavior with a stated reason (6a0423c: Protect final-chat persistence when arming and consuming an externally owned restart handoff.)
  • Drain deadline and cleanup reserve keeps the original intent (7042b9a: Prevent repeated controller operations from extending user-work suspension beyond the fixed drain and cleanup window.)
  • Controller failure-output privacy keeps the original intent (fa68922: Classify structured failures without forwarding arbitrary private subprocess output.)
  • Maintenance caller RPC timeout changes intended behavior with a stated reason (54abbae: Bound lifecycle RPC observation independently of the maintenance deferral deadline.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Dallin Romney: Raw commit 14886e4 adds src/cli/update-cli/update-command-service-drain.ts:181 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 14886e46e823; files: src/cli/update-cli/update-command-service-drain.ts)

PR surface

Source +78, Tests +171, Docs +8, Other +174. Total +431 across 15 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 96 18 +78
Tests 5 173 2 +171
Docs 1 11 3 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 4 177 3 +174
Total 15 457 26 +431

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +121/-21 lines; tests +173/-2 lines. Growth supplies the bounded wait, holder diagnostics, and distinct settlement, deadline, revocation, transport, and diagnostic-egress regressions; the standalone benchmark is excluded.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove merge-risk: 🚨 security-boundary: Current PR review selected no merge-risk labels.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Late final-chat writes can unnecessarily defer an administrative restart handoff, with existing write protection preventing unsafe interruption.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-10T07:15:58.114Z sha 20e342b :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-10T07:23:52.258Z sha 5ece842 :: needs real behavior proof before merge. :: none

Reviewed November 10, 2026, 2:33 AM ET / 07:33 UTC (Revision 3).

@steipete

Copy link
Copy Markdown
Contributor Author

Final head is 5ece84229a40ec9f51f04f203c4c5d32f0ca6e5a. Since the prior review request, CI caught TS2769 in the new test: request.timeoutMs can be null. The fixture now passes request.timeoutMs ?? undefined to the timer. The exact failing CLI-update type graph is red before and green after; lint, formatting, and independent Codex review pass. No production behavior changed. The updater transport finding remains addressed as detailed in the numbered response above.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressing every open item in ClawSweeper’s review at 20e342b41a44, now on 88723a019477c0bd52af23a8b9431fa81917f11c:

  1. Add real behavior proof: Expanded the existing production-path authority harness at test line180. It uses the real core registry and handleGatewayRequest dispatcher, captured operator guard, handoff handler/coordinator, and host lifecycle. The stop callback now directly runs the production markGatewayRestartDraining owner (line191); assertions inspect its real state, not a mock call count. Allowed settlement returns committed and changes that state; read-only scope receives FORBIDDEN without a stop (lines245 onward).

  2. Resolve security review attention item: The new revoked case starts with admin scope, confirms that handoff is waiting, then downgrades the same caller’s scopes before releasing terminal persistence (line230). The production captured operator guard rejects it with FORBIDDEN / Gateway requester authority changed, and the restart owner stays uncommitted (line252). No fake authority assertion or new production seam was added.

  3. Resolve merge risk: A local mutation run removed only the coordinator’s post-wait params.assertCurrent() at line388. The revoked case failed at the final-state assertion: expected no restart, received restart-draining=true; the other four settlement cases passed. Restoring the check gives 36/36 passing dispatcher tests. The exact gateway-server type graph, lint/format, and independent Codex review also pass. This establishes that the delayed revocation cannot reach the privileged commit effect with the final code.

Command: pnpm test src/gateway/server-methods.suspension-admission.test.ts. All identities and persistence sources are synthetic. This is the production-path authority harness requested in item1; it does not claim live WebSocket/model/deployment proof or an actual OS process exit. The PR body contains the results and limitations.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@steipete
steipete merged commit c96584a into main Nov 10, 2026
199 of 213 checks passed
@steipete
steipete deleted the steipete/perf-micro-handoff-refusal-names-holder-20260919 branch November 10, 2026 08:12
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 11, 2026
* fix: wait for late final writes during gateway handoff

Keep late terminal persistence within the original drain budget and retain final custody checks. Report bounded redacted holder facts through Gateway RPC errors and both journals. Preserve the synchronous idle path and immediate freeze behavior.

* fix: keep updater handoff transport open for terminal settlement

* test: normalize nullable handoff transport timeout

* test: prove handoff authority through terminal settlement
RomneyDa added a commit that referenced this pull request Nov 12, 2026
* fix: wait for late final writes during gateway handoff

Keep late terminal persistence within the original drain budget and retain final custody checks. Report bounded redacted holder facts through Gateway RPC errors and both journals. Preserve the synchronous idle path and immediate freeze behavior.

* fix: keep updater handoff transport open for terminal settlement

* test: normalize nullable handoff transport timeout

* test: prove handoff authority through terminal settlement

(cherry picked from commit c96584a)

Release adaptation: omit optional benchmark; preserve candidate owners.
Proof: RPC regression red, 197 tests across seven files green; targeted
types, lint, formatting, docs, syntax and allocation checks pass.
Independent local review omitted by explicit release-owner instruction.
Live deployment and stable upgrade remain qualification gaps.

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
(cherry picked from commit 36bb0cf580122d335c004ffd696cf62f3542cf6e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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.

1 participant