Skip to content

fix(sessions): reduce history stalls during cron cleanup - #155998

Merged
steipete merged 1 commit into
mainfrom
codex/team-r3-reader-20260922
Sep 23, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/team-r3-reader-20260922

Conversation

@steipete

@steipete steipete commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Related: #155414

What Problem This Solves

Fixes history and exact-entry reads waiting behind full-store validation during cron session retention.

User Impact

Foreground reads can complete while cron discovery validates a large session store. One additional reader worker is created on demand. In the synthetic Linux replay below, observed warm RSS increased by 19–159 MiB, and the cold 64 MiB shared-store foreground p95 increased from 425 to 655 ms. Workers retain the existing 30-minute idle retirement and critical-memory cleanup behavior.

Why This Change Was Made

Cron target discovery, validation, and reader cleanup use one bounded maintenance lane within the existing session database lifecycle owner. Foreground history and entry reads keep their queue. Both lanes preserve admission, per-lane cleanup sequence receipts, alias custody, revocation, failed-close retention, and the Bun retirement path. Whole-store corruption and participant checks, logical-agent throttling, exact deletion guards, schemas, retention, and update behavior remain unchanged.

The raw pool exports are private; internal callers and tests use the production lane interface.

Evidence

Frozen ABBA comparison against 9c87f193a96f759e5d08e1a2a314c9e4d4911104, using built workers on one Blacksmith Testbox: Node 24.19.0, Linux, 4 visible CPUs, 16 GB RAM. Each variant has two process replicates, six warm passes per process, two logical agents, and three foreground reads per agent. The table reports medians of each process's p95, with whole-pass CPU/wall differences and process-wide RSS observations.

Fixture Warm foreground p95 Reader queue p95 Process CPU Main-thread CPU Pass wall time Observed RSS increase
Shared 64 MiB 125.14 → 8.37 ms 105.91 → 3.63 ms −5.7% −3.1% +1.2% 59 MiB
Shared 640 MiB 1464.81 → 8.75 ms 1313.22 → 4.42 ms −6.5% +7.5% +1.6% 159 MiB
Canonical 64 MiB per agent 133.64 → 15.43 ms 130.75 → 7.95 ms −5.9% −0.3% −3.0% 39 MiB
Shared 64 MiB, entry + history page* 206.78 → 121.73 ms 159.26 → 84.77 ms −5.7% −9.8% −7.5% 19 MiB

Every qualified cell has matching foreground output and final-store hashes, identical asserted runtime/resource identity, and observed foreground arrival while discovery is pending. Cold process CPU increased 10–16% in the shared-store cases. Other maintenance work remains visible: the 640 MiB pass still reached 394 ms maximum event-loop delay. These measurements describe the synthetic workload; they do not establish aggregate Gateway CPU savings.

*The same-store entry + history-page cell is a separate matched ABBA comparison on a fresh lease with the same visible Node/CPU/RAM profile; its clocks and resource identity are qualified independently. Its queue column includes all attributed reader requests. Cold page p95 increased from 509 to 716 ms. All four raw page captures independently match the source namespace derived from the owner-declared database path, logical agent, session, and stored transcript generation. Replacing only that verified fixture-specific token yields identical messages and pagination across all runs. The initial unnormalized page comparison is excluded; the original lease expired before correction, so no successful retry or same-host continuity is claimed for it.

Actual active-close proof joined both busy reader lanes, rejected the revoked foreground result, pruned no rows, preserved all 1,026 stored rows and their digest, and allowed a fresh-generation read. Critical-memory reclamation left both reader pools at zero workers. This proves closure through the physical database path; the rejected lexical-alias probe is excluded.

Focused owner, entry-reader, and cron coverage passed 81 unique cases across runs. The new two-case lifecycle suite and the existing concurrent-cleanup case preserve the native cleanup boundary. Required changed checks passed, including core and all 25 test typecheck shards, formatting, lint, import cycles, storage guards, and all three dead-export scans. Independent P0–P2 review is clean. pnpm test src/config/sessions/session-transcript-worker-lanes.test.ts --maxWorkers=1 passed: 12 ms test time, 65.73 s cold wrapper wall (91% of Vitest duration was transformation). The existing concurrent reaper-cleanup case passed in 12.94 s test time / 125.17 s cold wrapper wall; these costs include the real reader/writer lifetime boundary. The exact-head CI run 35799286375 passed after incorporating the canonical main fixture fixes 8ce411c1aedf and 46dfea6a4201. The original failing run remains attributable to those independently reproduced main defects; it was not blindly rerun. The refresh preserved the stable patch ID and all touched production/test bytes.

Only the two raw pool export modifiers changed after the frozen measurement. Source reconstruction and normalized test-call binding checks verified unchanged pool construction, execution, and lifecycle behavior.

CI-reported case time by changed test file follows. These sums exclude shared collection, transformation, setup, and teardown wall costs; they are not incremental CI job wall time.

Changed test file Passing cases Reported case time
src/agents/cli-runner/session-history.async.test.ts 14 8.412 s
src/agents/sessions/session-manager-hydration-stream.test.ts 7 3.861 s
src/agents/sessions/session-manager-hydration.test.ts 39 8.082 s
src/config/sessions/session-transcript-worker-lanes.test.ts 2 0.002 s
src/cron/session-reaper.test.ts 35 12.072 s
src/gateway/server-methods/question.own-run.test.ts 18 11.736 s
src/gateway/server-methods/question.session-access.test.ts 47 26.153 s

@clawsweeper

clawsweeper Bot commented Sep 22, 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 docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Sep 22, 2026
@steipete
steipete marked this pull request as ready for review September 22, 2026 22:59
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 22, 2026, 7:57 PM ET / 23:57 UTC (Revision 2).

ClawSweeper review

What this changes

Separates cron session-retention reads from foreground history reads while keeping both worker queues under the existing database cleanup owner.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still shares the reader queue, and this PR addresses the remaining contention with convincing scoped performance evidence. No blocking correctness finding was identified.

Priority: P2
Reviewed head: 38543f678b5a09504e585a5c09b1a5ea91d4ff29

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with strong scoped performance and lifecycle evidence and no identified blocking defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded Linux built-worker comparisons exercise foreground entry/history reads during real cron discovery, with matching outputs and store hashes; active-close and memory-reclamation observations cover the shared lifecycle owner. The evidence is scoped to synthetic workloads, and no stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded Linux built-worker comparisons exercise foreground entry/history reads during real cron discovery, with matching outputs and store hashes; active-close and memory-reclamation observations cover the shared lifecycle owner. The evidence is scoped to synthetic workloads, and no stored-data contract changes require migration proof.
Evidence reviewed 8 items Introduced change and lifecycle ownership: The pinned merge-base-to-head diff adds a single-worker maintenance lane and passes it through cron discovery and retained database reads. Cleanup sequences remain keyed by lane, and database closure joins every lane recorded in nativeSequences.
Current-main necessity: Fetched main routes expired-cron reads through the default history worker without a maintenance-lane argument. Its reader pool has maxWorkers: 1, so full-store validation and foreground reads still contend for the same queue.
Recorded production-path performance proof: The complete supplied PR body records built-worker ABBA comparisons on Linux Node 24.19.0 with two logical agents and foreground arrivals during discovery. Warm foreground p95 falls from 125.14 to 8.37 ms for the shared 64 MiB fixture and from 1464.81 to 8.75 ms for 640 MiB; foreground outputs and final-store hashes match. The body explicitly bounds these claims to synthetic workloads and reports 19–159 MiB additional RSS and worse cold latency. Evidence is retained from supplied sourceRevision b3a5e176c8eae5b911ebb227d95b13874c768422c7fba8c0d43353f625ce8a7b, rather than substituted with a later body.
Findings None None.
Security None None.

How this fits together

Session readers serve conversation history and supply expired-session candidates to cron cleanup. Their lifecycle owner retains database access, rejects revoked results, and drains workers before a database closes.

flowchart TD
  A[History and exact-entry requests] --> B[Foreground reader queue]
  C[Cron retention sweep] --> D[Maintenance reader queue]
  B --> E[Shared database lifecycle owner]
  D --> E
  E --> F[SQLite session store]
  B --> G[History results]
  D --> H[Validated cleanup candidates]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +40, Tests +154, Docs +5. Total +199 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 3 135 95 +40
Tests 7 194 40 +154
Docs 1 6 1 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 335 136 +199

Review metrics

Metric Value Why it matters
Reader capacity 1 additional on-demand worker; 512 MiB old-generation limit Queue isolation has an explicit memory cost while retaining idle and critical-memory retirement.
Production versus test growth Production net +40 lines; tests net +154 lines Production growth threads lane selection through the existing owner, with focused coverage for cross-lane cleanup.

Technical review

Best possible solution:

Keep foreground and maintenance reads independently scheduled under one database lifecycle owner, preserving existing admission, cleanup, and storage contracts.

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

Yes, from source: current main queues foreground reads behind full-store cron validation in a single-worker pool, consistent with the recorded contention measurements. This review did not execute a runtime reproduction.

Is this the best way to solve the issue?

Yes: a bounded second queue reuses the existing reader and lifecycle contracts without duplicating storage policy or changing persisted state.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7a66ecd22a43.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded latency improvement for foreground session reads during cron retention.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded Linux built-worker comparisons exercise foreground entry/history reads during real cron discovery, with matching outputs and store hashes; active-close and memory-reclamation observations cover the shared lifecycle owner. The evidence is scoped to synthetic workloads, and no stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded Linux built-worker comparisons exercise foreground entry/history reads during real cron discovery, with matching outputs and store hashes; active-close and memory-reclamation observations cover the shared lifecycle owner. The evidence is scoped to synthetic workloads, and no stored-data contract changes require migration proof.

Evidence

What I checked:

  • Introduced change and lifecycle ownership: The pinned merge-base-to-head diff adds a single-worker maintenance lane and passes it through cron discovery and retained database reads. Cleanup sequences remain keyed by lane, and database closure joins every lane recorded in nativeSequences. (src/config/sessions/session-transcript-worker-resources.ts:130, 38543f678b5a)
  • Current-main necessity: Fetched main routes expired-cron reads through the default history worker without a maintenance-lane argument. Its reader pool has maxWorkers: 1, so full-store validation and foreground reads still contend for the same queue. (src/config/sessions/session-entry-read-runtime.ts:121, 7a66ecd22a43)
  • Recorded production-path performance proof: The complete supplied PR body records built-worker ABBA comparisons on Linux Node 24.19.0 with two logical agents and foreground arrivals during discovery. Warm foreground p95 falls from 125.14 to 8.37 ms for the shared 64 MiB fixture and from 1464.81 to 8.75 ms for 640 MiB; foreground outputs and final-store hashes match. The body explicitly bounds these claims to synthetic workloads and reports 19–159 MiB additional RSS and worse cold latency. Evidence is retained from supplied sourceRevision b3a5e176c8eae5b911ebb227d95b13874c768422c7fba8c0d43353f625ce8a7b, rather than substituted with a later body.
  • Revocation and reclamation proof: The supplied body records physical-path active closure joining both busy lanes, rejecting a revoked foreground result, preserving all 1,026 rows and their digest, and allowing a fresh-generation read. Critical-memory reclamation leaves both reader pools empty. Source preserves pre-dispatch and post-await revocation checks; no schema, stored representation, retention rule, or permission change is introduced. (src/config/sessions/session-transcript-worker-runtime.ts:102, 38543f678b5a)
  • Focused regression coverage: Two new lifecycle cases protect cross-lane custody and joined retirement. The existing real reaper case starts a foreground read during maintenance cleanup and verifies its full prompt survives while the expired sibling is removed. Other test changes migrate spies to the lane interface. Reported validation includes 81 unique cases; tests were not executed during this read-only review. (src/config/sessions/session-transcript-worker-lanes.test.ts:74, 38543f678b5a)
  • Merged related work and routing history: Provided GitHub metadata verifies fix(cron): avoid blocking Gateway during retention discovery #155414 merged as 8e18591. It moved cron discovery off the Gateway thread but documented remaining reader-queue contention. Current-main history also identifies Peter Steinberger's worker lifecycle and transcript refactors and Vincent Koc's adjacent retained-request-authority work; these are routing signals, not causal attribution. (src/config/sessions/session-transcript-worker-resources.ts, 8e185919954f)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (1 earlier review cycle)
  • reviewed 2026-09-22T23:10:48.823Z sha 51f46b448eb45bbb26e934d55ad949e4d641d3f9 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/team-r3-reader-20260922 branch from 51f46b4 to 38543f6 Compare September 22, 2026 23:50
@steipete
steipete enabled auto-merge (squash) September 23, 2026 00:05
@steipete
steipete merged commit 586f129 into main Sep 23, 2026
177 checks passed
@steipete
steipete deleted the codex/team-r3-reader-20260922 branch September 23, 2026 00:06
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

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 maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant