Skip to content

fix(agents): preserve streamed replies across Gateway restarts - #195164

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-shutdown-admissions-9s-under-load-20260919
Nov 8, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-shutdown-admissions-9s-under-load-20260919

Conversation

@steipete

@steipete steipete commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Preserves the provider's terminal partial assistant reply during a graceful restart without leaving the newly introduced consumer and pre-writer waits unbounded. This corrects the cancellation-bound regression in the first revision of this PR.

Why This Change Was Made

The idle wrapper forwards restart cancellation immediately, then allows one non-renewing abort-settle grace (normally two seconds; 250 ms in fast tests) for the terminal reply. Chunks and heartbeats cannot extend it. Expiry rejects pending iterator reads with the original abort reason. A native producer that completes within the grace keeps its queued terminal readable even if the consumer is delayed.

Session cleanup uses the existing waitForEmbeddedAbortSettle owner before closing the transcript writer. It records timeout/failure through the existing cleanup step and consumes this budget once; resource disposal does not start another sequential abort-settle wait. Ordinary Stop and LLM idle policies retain their existing behavior.

Scope limit: this bounds logical cancellation, not arbitrary provider resource closure. The existing retained-work contract still joins raw provider next()/return() operations and accepted writes after reporting deadlines. A provider that ignores both cancellation and iterator cleanup can still retain Gateway shutdown. Dropping that custody would risk late writes and resource release races; this PR does not do so and does not claim a universal two-second Gateway shutdown. The originally reported nine-second admissions/received-work stall remains unreproduced.

Production delta against the pinned parent: +34 net lines across three owners. Growth supplies the finite terminal grace, timer cleanup, and the bounded pre-writer join; no new config, schema, cache, dependency, or public API. Tests add 157 net lines across the durable-persistence regression and distinct cancellation/cleanup cases; the existing test allocation is updated accordingly.

User Impact

On Gateway restart or deploy, a run's final streamed partial reply is no longer dropped before persistence, so transcripts keep their tail; shutdown waits stay bounded by the existing 2 s abort-settle budget (no SIGKILL risk from a provider ignoring cancellation).

Evidence

  • New regressions fail on the previously pushed head: the cleanup owner stays pending after its settle budget and both normal/local stream consumers fail to reject. The corrected implementation passes.
  • One and sixteen concurrent cleanup waits both finish at the same 250 ms test budget, with cleanup uncertainty recorded. Stream tests cover ignored abort, late chunks that must not renew the grace, and a timely terminal queued behind a delayed consumer. The queued-terminal case also failed the first bounded candidate before its producer-completion cleanup was corrected.
  • The real AgentSession/SQLite regression still preserves the terminal partial reply before writer closure. Existing retained-work tests remain green; the new stream test explicitly proves raw producer work stays retained until it really settles.
  • 130 focused tests passed across eight files (115 on the final timer implementation; 15 unchanged cleanup/yield cases reused from the same revision). Codex autoreview is scoped-clean through P2 on the complete staged candidate. New head: a320c5f9420a340a0e783c1e178f68cf0afd0b2f. Exact-head CI passed, including the CI gate, selected tests, lint and typechecks. The fresh loaded result is summarized below.

Fresh loaded measurement

Five interleaved pairs against the exact parent: median SIGTERM-to-exit 1.487 → 1.894 s (+27.4%), admissions 0.787 → 1.228 s, received work 0.563 → 0.632 s, main-thread CPU 579 → 693 ms (+19.7%). Fresh A/A wall spread is 87 ms; median paired increase 399 ms. Candidate wall range 1.364–2.004 s; the worst pair increases wall 41.1% and CPU 21.1%. These costs are explicit; no speedup is claimed.

Every bounded run preserves 16/16 partial replies before exit and after recovery, 18 exactly-once resumes/recovery inputs, two interrupted tool receipts and four cron receipts, with zero surviving children. All 18 stopped transcripts remain byte-identical prefixes after recovery. Every baseline still loses 16 partials, so this compares different correctness outcomes. The added work is concentrated at admission/transcript settlement. All three built production-source hashes match the pushed head; the fixture uses the normal two-second abort budget, verified from its runtime environment.

Separate sampled allocation A/A: 119,675,296 / 121,983,120 bytes (1.93% spread). Adjacent A/B: 121,983,120 → 135,585,240 bytes (+11.15%). In those sampled runs, main-thread CPU rises 674.924 → 858.439 ms (+27.19%) and wall time 1.459 → 2.168 s (+48.55%). Sampling durations are excluded from the normal timing median; CPU and allocation cover only the Gateway main thread/heap, not workers or tool children.

Historical baseline and known gate failures

The original five-pair loaded result was 1.388 s without partial persistence versus 1.742 s on the first PR revision. It is historical evidence, not a measurement of this bounded revision. The synthetic fixture uses 16 slow streams, two foreground tool children, four cron runs and four pending WebSocket RPCs, with concurrent fsync pressure; the allocated 35.1 GiB database is largely synthetic padding, not a production history distribution. All data is synthetic; no production access was used.

The previous local check:changed failures were reproduced on exact parent 3a25991e37c4bad581b34ebf19f0b9b3e036b5cf: changelog credits introduced by #194364 (266a7aa0fe69); unused script export introduced by #195099 (c9e6370bb191); path-containment exports introduced by #195061 (ce840d8a8290); retention helper exports introduced by #195064 (754b41c65df0). These are identified main regressions, not ignored noise. This revision reran the complete local gate: only those same two gate families failed; all typechecks, lint, format, import-cycle and other guards passed. The separate test-line ratchet passed with 31 lines slack.

Allow restart-aborted provider streams to deliver their terminal event, then join prompt settlement before retiring the transcript writer. Ordinary cancellation and idle watchdog policies stay unchanged. The loaded synthetic Gateway now preserves partial replies and restart receipts; this does not claim a shutdown latency reduction.
@clawsweeper

clawsweeper Bot commented Nov 8, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 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-08T10:48:29.400243Z a320c5f 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 8, 2026
@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 8, 2026
Reuse the existing abort-settle budget before writer cleanup without waiting twice. Bound restart iterator consumption with a nonrenewing grace while preserving timely native terminal replies and retained source custody.
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR preserves terminal partial replies during graceful Gateway restarts while bounding stream consumption and pre-writer settlement.

Example: The assistant streams “Already streamed answer” before a graceful Gateway restart.

  • Before: Cancellation can reject stream consumption and close the transcript writer before the provider's terminal partial reply persists.
  • After: The terminal reply can persist within the existing settlement budget, while an unresponsive producer cannot indefinitely block the stream consumer.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is focused and source-consistent, with meaningful regression coverage, but supplied real-behavior evidence does not exercise the final bounded revision.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
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 streamed assistant answer can disappear from durable conversation history when the Gateway restarts before its terminal reply is persisted.
Reason: Preserving already-streamed conversation content has clear value, and the maintainer-authored direction keeps the existing cleanup and persistence boundaries.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses a concrete transcript-loss path using the existing lifecycle owners, and source review found no actionable introduced defect.

Priority: P2
Reviewed head: a320c5f9420a340a0e783c1e178f68cf0afd0b2f

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not show the final head preserving a streamed partial reply through a real Gateway stop, restart, and history readback; the reported loaded run predates the bounded revision.
Agent review details

How this fits together

The embedded runner connects provider event streams to AgentSession and transcript persistence; restart cancellation passes through the stream watchdog and session cleanup before writers and runtime resources retire.

flowchart TD
  A[Gateway restart] --> B[Run cancellation]
  B --> C[Provider stream watchdog]
  C --> D[AgentSession settlement]
  D --> E[Transcript writer drain]
  E --> F[Resource disposal]
Loading

Technical review

Best possible solution:

Keep restart settlement bounded in the existing stream and cleanup owners, persist timely terminal replies before writer retirement, and retain unfinished provider work until it settles.

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

Current-main source exposes both premature iterator rejection and writer cleanup before prompt settlement; the committed regression composes the real AgentSession and SQLite owners, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch is a focused repair: it reuses the existing settlement budget and owners, preserves ordinary cancellation and retained-work custody, and adds no competing persistence or recovery path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8027d2dcc230.

Provenance checked

  • Stream cancellation changes intended behavior with a stated reason (5621081: The watchdog optimization replaced per-delta abort races with one subscription while preserving immediate cancellation and retained cleanup.)
  • Session cleanup ordering changes intended behavior with a stated reason (79eb5bd: The consolidation carried transcript cleanup before aborted-session settlement; later repairs retained cancellation-aware idle skipping and disposal after cleanup failure.)
  • Shutdown measurement keeps the original intent (e32051e: The existing measurement exercised loaded shutdown and delayed finalizer retirement; the extension adds transcript readback and realistic concurrent work without claiming a latency improvement.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +34, Tests +157, Docs +6, Other +234. Total +431 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 42 8 +34
Tests 3 169 12 +157
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 2 254 20 +234
Total 9 471 40 +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
Runtime versus regression growth Production +42/-8; tests +169/-12 The runtime growth supplies the finite grace and cleanup ordering; the regression growth covers persistence, cancellation deadlines, delayed consumption, and retained custody.
Measurement controls 5 new measurement-script flags; 0 new runtime settings The added controls select tools, clients, ignored SIGTERM, CPU profiling, and seeded history only in the shutdown measurement script.

Labels

Label changes:

  • add P2: This is a focused correctness repair for partial assistant replies lost during graceful restart, with limited scope and no demonstrated current process outage.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a focused correctness repair for partial assistant replies lost during graceful restart, with limited scope and no demonstrated current process outage.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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.

Reviewed November 8, 2026, 6:02 AM ET / 11:02 UTC.

@steipete
steipete merged commit 9fb5cdc into main Nov 8, 2026
153 of 159 checks passed
@steipete
steipete deleted the steipete/perf-micro-shutdown-admissions-9s-under-load-20260919 branch November 8, 2026 11:13
vincentkoc added a commit that referenced this pull request Nov 8, 2026
…tooling-lint-selection-20261108

* commit 'b0e90e6a4b359fff7756698067fdce4758b1907b': (38 commits)
  fix(android): Talk button demands a realtime provider on a native Talk setup (#191194)
  chore: trace first-run Gateway work and verify later replies (#195185)
  fix(knowledge): keep deleted messages out of reply previews (#195126)
  fix(agents): preserve streamed replies across Gateway restarts (#195164)
  perf(ci): reuse SDK transport path boundaries (#195180)
  fix(sandbox): avoid pauses for unchanged command checkpoints (#195120)
  fix(test): make retention checks portable across runtimes (#195091)
  fix(knowledge): clarify temporal kind filters (#194995)
  improve: reduce Gateway allocation while draining SQLite receipts (#195129)
  fix: reduce streaming CPU after reply and voice directives (#195145)
  fix: reduce Markdown reparsing during streamed tool-call checks (#195161)
  fix: restore the main dead-export gate (#195158)
  improve(ci): pack small UI selections into fewer jobs (#195107)
  fix(muse): quota and sign-in failures end with no reply (#195148)
  fix: allow first release push with shipped patch bytes (#195174)
  fix(ci): narrow single-config tooling selections (#195147)
  fix(packaging): reject incompatible prepublish plugin cohorts (#195152)
  fix(ci): prepare verified Bun before parity checks (#195155)
  fix: Incognito agent turns stall before execution (#195005)
  fix: credentialed search and speech providers work without picking a provider (#195169)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
…law#195164)

* fix(agents): preserve streamed replies across gateway restart

Allow restart-aborted provider streams to deliver their terminal event, then join prompt settlement before retiring the transcript writer. Ordinary cancellation and idle watchdog policies stay unchanged. The loaded synthetic Gateway now preserves partial replies and restart receipts; this does not claim a shutdown latency reduction.

* fix(agents): bound restart terminal settlement

Reuse the existing abort-settle budget before writer cleanup without waiting twice. Bound restart iterator consumption with a nonrenewing grace while preserving timely native terminal replies and retained source custody.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: L 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