Skip to content

improve(sessions): avoid redundant shared history copies - #154552

Merged
steipete merged 1 commit into
mainfrom
codex/history-last-reader-handoff
Sep 21, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/history-last-reader-handoff

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Equivalent queued history reads share one worker result but then deep-clone that entire result for every waiting caller, including the final caller who could own the original.

User Impact

Concurrent readers of the same history page allocate and copy less data while retaining separate mutable results. Single-reader behavior, cancellation, capacity limits, and read authority remain unchanged. No configuration, protocol, storage, or migration changes.

Why This Change Was Made

Count registered receivers and hand the original to the final receiver after earlier receivers have finished cloning. Dispatch already removes the group from the queue before the snapshot begins, preventing late joins. Decrement before cancellation; a canceled final receiver discards the original and simply forfeits this saving.

This complements #149219's lazy history-query preparation and the separately owned hydration/storage work. It does not change worker concurrency or bypass snapshot boundaries.

Evidence

  • Two readers of a synthetic 1 MiB page: median 1.435 → 1.053 ms/group (27% lower); process CPU median 1.603 → 1.127 ms/group. Seven samples of 20 groups through the actual read/coalescing owner with a deferred worker fixture. Isolated handoff evidence, not end-to-end RPC latency.
  • Regression failed before the change because 127 successful receivers made 127 clones instead of 126. First- and last-receiver cancellation both pass; canceled-final groups retain their existing clone count.
  • 22 focused cases plus 22 real worker integration/lifecycle cases passed, including nested result isolation, rejection/recovery, successor reads, admission revocation, and database replacement.
  • pnpm test src/gateway/session-history-worker-runtime.test.ts --maxWorkers=1: 28.83 s wrapper wall time including compilation/import; opt-in benchmark remains disabled in normal CI. The benchmark-enabled run passed all 23 cases.
  • Independent P0–P2 review: clean.
  • The two capacity/cancellation cases took 120 ms and 106 ms in the ordinary run; neither starts a worker or uses real-time waits.
  • node scripts/check-changed.mjs: passed, including core/test typechecks, lint, dead-export scans, and applicable repository guards.

@clawsweeper

clawsweeper Bot commented Sep 21, 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.

@steipete
steipete marked this pull request as ready for review September 21, 2026 07:17
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S maintainer Maintainer-authored PR labels Sep 21, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 21, 2026
@clawsweeper

clawsweeper Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 21, 2026, 3:23 AM ET / 07:23 UTC.

ClawSweeper review

What this changes

The PR avoids one deep copy per shared session-history read by giving the final receiver the original result, with cancellation coverage and an opt-in benchmark.

Merge readiness

✅ Ready for maintainer review

Keep open: this is a useful, bounded optimization that current main does not implement. No actionable correctness or security findings were identified.

Priority: P2
Reviewed head: 25dd33b7f05c286b8cbd4122c4cdd0ccd68997ab

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with sound handoff ordering, useful regression coverage, and appropriately bounded performance claims.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied repository state identifies maintainer-authored work, so the external-contributor proof gate does not apply. The deferred-worker benchmark exercises the changed handoff owner, while reported real-worker tests supplement it; neither is claimed as live RPC latency proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies maintainer-authored work, so the external-contributor proof gate does not apply. The deferred-worker benchmark exercises the changed handoff owner, while reported real-worker tests supplement it; neither is claimed as live RPC latency proof.
Evidence reviewed 7 items Introduced change and handoff invariant: The pinned introduced patch changes only receiver accounting and its tests. Each receiver decrements before cancellation; synchronous cloning completes before the final receiver receives the original. Dispatch removes the group before the snapshot starts, preventing late joins.
Still useful on current main: Fetched main retains the shared boolean and clones the result for every successful shared receiver. Its affected files match the pinned merge-base versions. No implemented-on-main or shipped-fix conclusion is supported; the supplied release commit was unavailable locally.
Verified merge result: The test merge's raw parents are the pinned base followed by the exact PR head. Comparing against that base preserves the same focused production change; unrelated base-branch work is not attributed to this PR.
Findings None None.
Security None None.

How this fits together

Gateway history requests share equivalent queued SQLite reads through the session-history worker owner. The owner returns independently mutable results for callers to present to clients.

flowchart TD
  A[Gateway history requests] --> B[Admission and capacity checks]
  B --> C[Group equivalent queued reads]
  C --> D[Worker reads history snapshot]
  D --> E{Receiver canceled?}
  E -->|Yes| F[Reject caller]
  E -->|No| G[Clone for earlier receivers]
  G --> H[Final receiver takes original]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +2, Tests +43. Total +45 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 6 4 +2
Tests 1 85 42 +43
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 91 46 +45

Review metrics

Metric Value Why it matters
Shared-result copies N → N−1 copies when the final receiver succeeds The optimization saves one full result copy without sharing mutable objects between successful callers.

Technical review

Best possible solution:

Retain the existing history-read owner and snapshot boundaries while eliminating the final receiver's unnecessary copy.

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

Yes, from source: equivalent reads queued before dispatch cause current main to clone once per successful receiver. The focused regression exercises that path, but no runtime reproduction was executed in this read-only review.

Is this the best way to solve the issue?

Yes. Receiver counting removes the redundant copy within the existing owner while preserving mutable isolation, cancellation, and snapshot freshness.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 057492fa6da7.

Labels

Label changes:

  • add P2: This is a bounded performance improvement for concurrent session-history reads, with no demonstrated urgent user-facing regression.
  • 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 supplied repository state identifies maintainer-authored work, so the external-contributor proof gate does not apply. The deferred-worker benchmark exercises the changed handoff owner, while reported real-worker tests supplement it; neither is claimed as live RPC latency proof.

Label justifications:

  • P2: This is a bounded performance improvement for concurrent session-history reads, with no demonstrated urgent user-facing regression.
  • 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 supplied repository state identifies maintainer-authored work, so the external-contributor proof gate does not apply. The deferred-worker benchmark exercises the changed handoff owner, while reported real-worker tests supplement it; neither is claimed as live RPC latency proof.

Evidence

What I checked:

  • Introduced change and handoff invariant: The pinned introduced patch changes only receiver accounting and its tests. Each receiver decrements before cancellation; synchronous cloning completes before the final receiver receives the original. Dispatch removes the group before the snapshot starts, preventing late joins. (src/config/sessions/session-history-worker-runtime.ts:49, 25dd33b7f05c)
  • Still useful on current main: Fetched main retains the shared boolean and clones the result for every successful shared receiver. Its affected files match the pinned merge-base versions. No implemented-on-main or shipped-fix conclusion is supported; the supplied release commit was unavailable locally. (src/config/sessions/session-history-worker-runtime.ts:51, 057492fa6da7)
  • Verified merge result: The test merge's raw parents are the pinned base followed by the exact PR head. Comparing against that base preserves the same focused production change; unrelated base-branch work is not attributed to this PR. (src/config/sessions/session-history-worker-runtime.ts:49, 30f860e4c1e4)
  • Isolation, cancellation, and validation: The complete focused test file covers nested mutation isolation, successor reads, rejected-read recovery, capacity release, and first/final receiver cancellation. The captured PR body reports 22 focused and 22 real-worker integration/lifecycle cases passing, with 28.83 seconds wrapper wall time. Its deferred-worker benchmark reports 27% lower handoff time, explicitly excluding end-to-end RPC claims. Tests were inspected, not executed during this read-only review; diff whitespace checks passed. (src/gateway/session-history-worker-runtime.test.ts:141, 25dd33b7f05c)
  • Authority and storage boundaries preserved: Worker dispatch, database-generation checks, post-await admission checks, capacity accounting, and cold restoration remain unchanged. This patch transfers an ordinary result object, not authorization; it introduces no persisted format, plugin API, dependency, or Codex contract change. (src/config/sessions/session-transcript-worker-runtime.ts:412, 25dd33b7f05c)
  • Distinct related optimization: improve(sessions): reduce allocation during history reads #149219 remains open and reduces SQLite query preparation within a history projection. Its supplied body establishes a different optimization from this PR's result handoff, so it does not supersede this work. (f170ca58a3f7)

Likely related people:

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

@steipete
steipete merged commit cf7b73c into main Sep 21, 2026
275 of 276 checks passed
@steipete
steipete deleted the codex/history-last-reader-handoff branch September 21, 2026 08:01
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to vyctorbrzezowski/openclaw that referenced this pull request Sep 21, 2026
…question-layout-restart-recovery-20260921

* 'main' of https://github.com/openclaw/openclaw: (110 commits)
  perf(infra): collect and retire idle worker heaps (openclaw#154408)
  perf(sessions): hand shared history to the final reader (openclaw#154552)
  fix: clarify Codex onboarding migration scope (openclaw#151383)
  fix: recover conflicted PRs after accepted auto-merge
  perf(update): defer Gateway maintenance during candidate validation (openclaw#154548)
  perf(test): advance llama.cpp reload deadlines virtually (openclaw#154536)
  refactor(skills): prepare pinned library resources off-thread (openclaw#148560)
  fix(tooling): preserve Node compiler policy in script subprocesses (openclaw#154509)
  ci: select supported Node and cover packaged Node 26 (openclaw#154298)
  fix(release): preserve Telegram rerun evidence (openclaw#154561)
  docs: follow pending PR merges through completion
  fix(gateway): avoid stuck shutdowns after lifecycle errors (openclaw#145241)
  fix(ui): let focused dashboard widgets fill the task area (openclaw#154440)
  feat(release): add non-Latest extended-stable releases (openclaw#154515)
  fix(release): project 7.35 package Telegram config (openclaw#154546)
  refactor(config): derive host contracts from schemas (openclaw#153936)
  fix(ui): remove finished subagents from inline activity (openclaw#154469)
  refactor(config): derive core channel contracts from schemas (openclaw#153935)
  refactor(config): derive boundary contracts from schemas (openclaw#153937)
  fix(ui): keep thread activity current across cached updates (openclaw#154540)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. 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.

1 participant