Skip to content

perf(sessions): keep context accounting bounded on large sessions - #174274

Merged
steipete merged 4 commits into
mainfrom
dbasync/bigturn-accounting
Oct 16, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/bigturn-accounting

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large sessions repeatedly scan retained events to compute context totals, and session actors hydrate every historical input-completion receipt. Both costs grow with retained history even when the next model prompt uses a bounded window.

User Impact

The session actor now retains exact event and byte totals independently of its bounded transcript window. Appends and metadata-only rewrites update those totals in the existing writer transaction and publish them with the receipt. Boundaries and uncovered historical rewrites use the canonical reader; rollback preserves the previous totals. Completion residency is limited to 512 records, with indexed durable lookup preserving older retry outcomes.

Input staging consumes prepared completion/transcript facts instead of reading them again. It retains the accepted input-ID comparison, session authority, and live input-owner check. Accepted edge: completion/transcript bookkeeping may advance after preparation; a still-authorized run consumes its prepared facts. In particular, a retry prepared before an input is staged can observe an absent row again after that input finishes; staging does not add a second completion-snapshot check for that theoretical interleaving. A different accepted input still refuses staging.

Prompt/context selection, stored transcript bytes, durability, schemas, and retention are unchanged. This is the accounting half of the two merged large-session changes.

Validation and scope

The corrected focused owner batch passed 57 tests across eight files, including accounting rollback/rewrites, completion eviction and old retries, pending-input custody, history readers, query plans before and after ANALYZE, and live session previews. Formatting, type-aware lint, source-contract/export checks, types, Madge, PostgreSQL conformance, selected changed tests, and T1/dialect ratchets passed on the final PR heads. Accounting CI: 38916493040; history CI: 38919216838. Both required CI gates passed; no CI/admin exception was used.

Knip's lane-caused obsolete export was removed. Two remaining unused exports, redactSensitiveText in packages/ai/src/transports/transport-utils.ts and I18nController in ui/src/i18n/lib/lit-controller.ts, reproduced under the same rules/files on main cf7522093c8832429689ac32d5e79d2eafdb3f3a and were routed for repair. Knip is not described as wholly green. Two Codex review rounds completed; the remaining P2 history-cache finding is recorded below.

T1 inventory: touched shared modules 28 → 28, broader session/history scope 164 → 164, global 222 → 222, global compatibility tier 12 → 12. Retained synchronous SDK/opaque-callback roots require a public-contract/owner cutover; not every shared primitive has independently proven SDK reachability. No worker-only relabel hides that debt. Dialect ratchet: mechanical 2 → 2, design 12 → 9, engine-maintenance 0 → 0. No public SDK surface, schema, update, Doctor, plugin-loading, or service-lifecycle change; the update cell is not applicable.

Combined measurement

These measurements cover both the accounting and history changes together. The 25 owned production files at the final history merge are byte-identical to measured candidate 027ba984fb63a06d323303ef5caa728406df7484; CI fixture/type-only integration fixes do not change that implementation. This does not establish session-size-independent end-to-end turns. withTranscriptContextSnapshot still reads the entire navigation projection before bounding context, and older model-size batches grow with history. Cold accounting, cache eviction, marker-dense TTL work, and the legacy unindexed-prefix join also remain.

Base 95a27d0779d1c8e0c44b35e6cab9d7662e3bb6e7; candidate 027ba984fb63a06d323303ef5caa728406df7484. Three alternating pairs. Counts are median [min–max]. Ordinary warm rows have n=9 per available side; supplemental profiles have n=1. No quiet-host latency claim. Sizes are initial synthetic transcript-event counts; ordinary turns append normally. Full active history is retained with the supported 20-message channel history limit, disabled transport and memory search, and synthetic completion rows.

Ordinary warm turns

Causal SQL / requests / MAIN follow turn ownership, including work outside the observed window.

Events Base causal SQL / requests / MAIN Candidate causal SQL / requests / MAIN
1,000 89 [89–90] / 23 [23–24] / 0 [0–0] 85 [85–86] / 23 [23–24] / 0 [0–0]
10,000 127 [127–140] / 25 [25–27] / 0 [0–0] 123 [123–137] / 25 [25–27] / 0 [0–0]
30,000 unavailable 172 [172–186] / 25 [25–27] / 0 [0–0]
60,000 unavailable 247 [247–251] / 25 [25–25] / 0 [0–0]

Raw SQL / requests / MAIN include all work observed in the named phase.

Events Base raw SQL / requests / MAIN Candidate raw SQL / requests / MAIN
1,000 89 [82–96] / 23 [23–25] / 0 [0–0] 86 [85–89] / 23 [23–25] / 0 [0–0]
10,000 127 [119–129] / 25 [25–26] / 0 [0–0] 123 [118–124] / 25 [25–27] / 0 [0–0]
30,000 unavailable 174 [172–193] / 25 [25–32] / 0 [0–0]
60,000 unavailable 248 [247–251] / 25 [25–25] / 0 [0–0]

Baseline 30k/60k paired warm samples are unavailable after product worker timeouts. An earlier excluded 30k diagnostic succeeded; the 30k failure is not universal. Later baseline arms were restricted to 1k/10k; no further large-session timeout probes were run.

Cost diagnostics

Logical returned MB follow causal turn ownership, including work outside the observed window; they are decoded values, not disk I/O. MAIN CPU is thread CPU measured within the tighter operation snapshots. These loaded-host instrumented CPU values do not support latency or speedup claims. Snapshot bytes, service and elapsed observations remain in the local measurement artifact. No quiet Testbox was immediately available; the queued lease was cancelled.

Events Base causal logical MB Candidate causal logical MB Base snapshot MAIN CPU ms Candidate snapshot MAIN CPU ms
1,000 0.356 [0.354–0.358] 0.325 [0.323–0.327] 343.6 [216.9–392.7] 295.0 [234.4–382.7]
10,000 4.521 [4.515–9.489] 4.490 [4.484–9.458] 389.6 [272.4–467.2] 315.4 [245.2–367.2]
30,000 unavailable 11.154 [11.148–16.178] unavailable 316.2 [216.9–587.7]
60,000 unavailable 21.443 [21.437–21.449] unavailable 292.1 [231.3–507.0]

Remaining model-context growth

SQL families use full observed phases; request families use causal ownership. Full-phase SQL-family bytes need not reconcile with the causal bytes above. The zero at 1k means this named model-context worker request was not used; it does not mean there was no context assembly.

Candidate events Named model-context worker SQL / requests Full navigation MB Model-size statements
1,000 0 [0–0] / 0 [0–0] 0.000 [0.000–0.000] 0 [0–0]
10,000 36 [36–36] / 1 [1–1] 3.235 [3.234–3.236] 26 [26–26]
30,000 85 [85–85] / 1 [1–1] 9.745 [9.744–9.746] 76 [76–76]
60,000 160 [160–160] / 1 [1–1] 19.510 [19.509–19.511] 151 [151–151]

At the matched 1k/10k sizes, median causal SQL falls by four and total causal request counts are unchanged. Four measured native read classes shrink: active COUNT/SUM, latest active boundary, exact-entry snapshots and participant projection. Individual turn deltas vary, and observed phases can straddle operation boundaries. Other shared entry/row/watermark reads remain. The generic accounting-associated request lacks a retained domain caller at 10k, so its request-level attribution is positional and is not included as a machine-classified family. Actor operations are mixed reads/writes, not an actor-rehydration-only total. Candidate 30k/60k first warm turns can still include a boundary lookup; no universal zero-boundary claim is made.

Shared native-read families (statements per warm phase, median [min–max]; n=9 per cell):

Family Base 1k Candidate 1k Base 10k Candidate 10k Candidate 60k
Active accounting COUNT/SUM 1 [0–2] 0 [0–0] 1 [1–1] 0 [0–0] 0 [0–0]
Latest active boundary 1 [0–2] 0 [0–0] 1 [0–1] 0 [0–0] 0 [0–1]
Exact entry with snapshot subqueries 3 [2–4] 2 [2–2] 3 [2–3] 2 [2–2] 2 [2–2]
Batched entries with snapshot subqueries 1 [1–1] 1 [1–1] 1 [1–1] 1 [1–1] 1 [1–1]
Participant projection 2 [1–2] 1 [1–1] 2 [1–2] 1 [1–1] 1 [1–1]
Row/transcript facts 1 [1–1] 1 [1–1] 2 [2–2] 2 [2–2] 2 [2–2]
Watermark/index facts 1 [0–2] 1 [1–2] 1 [0–1] 1 [0–1] 1 [1–1]

Actor hydration and entry-cache loads are not separately isolated in retained request origins. Snapshot-bearing SELECTs above are directly measurable native reads, not independent cache-load requests. Mixed actor command counts are retained separately in JSON and must not be relabeled as hydration. No zero-hydration or flat-rehydration claim is made.

History and session list

Ordinary chat.history first page, observed SQL / requests / MAIN and snapshot logical returned MB (n=3 per available side). UI bytes use the tighter operation snapshots, not the full observed phase:

Events Base SQL / requests / MAIN Base snapshot logical MB Candidate SQL / requests / MAIN Candidate snapshot logical MB
1,000 19 [17–19] / 2 [1–2] / 0 [0–0] 0.308 [0.308–0.339] 13 [12–16] / 2 [1–2] / 0 [0–0] 0.308 [0.308–0.308]
10,000 21 [21–21] / 2 [2–2] / 0 [0–0] 0.341 [0.341–0.341] 17 [16–18] / 2 [2–2] / 0 [0–0] 0.310 [0.310–0.310]
30,000 unavailable unavailable 17 [16–29] / 2 [2–4] / 0 [0–0] 0.312 [0.312–5.329]
60,000 unavailable unavailable 17 [17–17] / 2 [2–2] / 0 [0–0] 0.312 [0.312–0.312]

The marker/reply-heavy supplemental profile shows the following after-append refresh (n=1); raw counts use the full observed phase, while bytes use the operation snapshots:

Events Base raw SQL / requests / snapshot bytes Candidate raw SQL / requests / snapshot bytes Base direct-handler SQL / requests Candidate direct-handler SQL / requests
1,000 227 / 4 / 138,386 170 / 2 / 93,776 210 / 2 170 / 2
60,000 210 / 2 / 2,690,770 170 / 3 / 94,680 210 / 2 170 / 2

At 60k the metadata projection changes from 41 calls/2,596,325 logical bytes to 1 call/235 bytes. The extra candidate observed request is a nested readonly-worker request with no retained domain caller; do not label it confidently unrelated background. Its associated SQL finishes outside the named phase. sessions.list at 60k has 0 observed SQL/requests on both sides. Initial 1k UI observations include initialization/background work.

Unchanged shared harness

Scope Base SQL / requests / MAIN Candidate SQL / requests / MAIN
causalWarm 72 [72–78] / 23 [23–25] / 0 [0–0] 70 [70–76] / 23 [23–25] / 0 [0–0]
rawWarm 72 [72–111] / 23 [23–28] / 0 [0–13] 70 [70–97] / 23 [23–29] / 0 [0–9]
whole 4,149 [4,147–4,154] / 1,049 [1,045–1,049] / 185 [185–185] 4,112 [4,109–4,130] / 1,042 [1,041–1,051] / 185 [185–186]

Warm rows pool 30 turns per side; whole rows have 3 runs per side. Observed warm MAIN outliers are background lease-expiry reads (openclaw-state-lease-store.ts:131), not causal turn SQL.

Prompt and evidence limits

Across 26 matched prompts, all 63 differing fields are observed wall-clock prefixes after fixture-root normalization. Exact bytes differ; source comparison retains every difference. 30k/60k prompts are unpaired. Provider input items and bytes are retained in the measurement artifact; exact selected source-event counts are not fully retained.

The source inventory is distinct from measured MAIN statements: changed shared files retain 28 T1 sites; the measured ordinary scale path is 0 MAIN.

Remaining review follow-up

P2: the per-connection history cache key contains session ID, while display-source identity also includes logical agent. Two logical agents reading the same physical session may reuse the first agent's cursor source. No data-loss or disclosure effect was demonstrated. This cursor-consistency case is deferred under the requested two-round review cap; it is not claimed fixed.

Change size: 25 files, +442/−88 lines; production +257/−56, tests +173/−31, test support +4/−1, docs +8.

…ions

Keep exact context accounting in the session actor across ordinary appends and
metadata rewrites. Bound resident completion history and preserve durable retry
lookup. Remove duplicate completion and transcript reads during input staging.
@clawsweeper

clawsweeper Bot commented Oct 16, 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 Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T14:14:23.878727Z 87a3894 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 size: L labels Oct 16, 2026
Carry the complete actor projection into cold accounting without another snapshot read.
Correct the regression fixtures to exercise the existing worker message path.

@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: 880889261d

ℹ️ 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".

if (input.kind === "stage") {
const snapshot = readPendingInputStage(current, input, row);
if (!isDeepStrictEqual(snapshot, input.expected)) {
if (row?.input_id !== input.expected.existing?.input_id) {

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.

P1 Badge Recheck terminal completion before restaging

When a tracked retry reads its snapshot just before the original run records a terminal completion and removes the pending row, both row?.input_id and input.expected.existing?.input_id are undefined, so this check passes and the transaction inserts the pending input again without noticing the newly committed completion. The retry then receives custody and can execute the same user input twice; recheck the completion/committed-input state at the staging effect rather than comparing only the pending-row identity.

AGENTS.md reference: AGENTS.md:L71-L71

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 16, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Review disposition: the absent → staged → terminal → absent retry case is an accepted internal-bookkeeping interleaving under this change's design scope. Staging keeps the input-ID comparison, session authority, and live input-owner check; it does not recapture the full completion/transcript snapshot after preparation. The accepted edge is now explicit in the PR body. No reproduced data-loss, disclosure, or money-risk case was provided.

Supply the required validateTurn flag and retain the literal message event type.
Production behavior and regression assertions are unchanged.
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR maintains incremental context totals, bounds resident completion records, and removes duplicate bookkeeping reads during input staging.

Example: Append a message to a session containing 600 retained events.

  • Before: Accounting falls back to aggregating retained events because the actor's 512-row window is incomplete.
  • After: The actor increments exact event and byte totals and publishes them through its existing receipt.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, coherent implementation with focused owner coverage and no identified defect; measured runtime performance remains unestablished.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence covers production owners through focused tests, while the declared large-session baseline/candidate measurements remain pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large retained sessions repeatedly perform history-dependent accounting and hydrate historical completion records during otherwise bounded operations.
Reason: The maintainer-authored direction addresses concrete remaining work without new configuration, storage formats, or competing owners; separate history paging is explicitly outside scope.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses remaining history-dependent work on main, and source review found no actionable introduced defect.

Priority: P2
Reviewed head: 8ddeb4bf4272befccea5919b4805fbe58df2a89c

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not demonstrate shipped-entry-point scale measurements or a base-fails/head-passes regression run.
Agent review details

How this fits together

The session writer receives transcript and pending-input operations, commits SQLite changes, and publishes actor receipts that context-accounting readers consume.

flowchart TD
  A[Session operations] --> B[Session actor writer]
  B --> C[SQLite transcript and completions]
  B --> D[Committed actor receipt]
  D --> E[Context accounting reader]
  E --> F[Context size and event totals]
  C --> E
Loading

Technical review

Best possible solution:

Land the existing actor-owned accounting and bounded completion changes once the exact-head CI gate completes successfully.

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

Current-main source shows unbounded completion hydration and aggregate accounting outside complete actor windows; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change appropriately extends the existing actor and receipt owners, preserves canonical fallback readers, and makes the accepted staging-bookkeeping tradeoff explicit.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 33f497e178d7.

Provenance checked

  • Context metadata and accounting keeps the original intent (c9e7c71: Reuse actor-owned bounded metadata while retaining canonical readers for uncovered contexts.)
  • Bounded actor hydration keeps the original intent (dd9cdee: Keep navigation residency bounded and treat missing facts as unknown outside complete coverage.)
  • Pending-input staging snapshot comparison changes intended behavior with a stated reason (d6c1b1f: Move staging and settlement into workers while preserving authoritative session and live-custody checks.)
  • Projection receipt reuse keeps the original intent (e9df67c: Publish committed actor facts through existing scoped receipts while keeping payload reads with the history owner.)
  • Exact stored-byte accounting keeps the original intent (a15b5c7: Bound append residency while preserving exact persisted transcript bytes and accounting.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit c9e7c71 adds src/config/sessions/session-actor-context-metadata.ts:9 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c9e7c71c0859; files: src/config/sessions/session-actor-context-metadata.ts)

PR surface

Source +201, Tests +145, Docs +8. Total +354 across 25 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 18 257 56 +201
Tests 6 177 32 +145
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 25 442 88 +354

Review metrics

Metric Value Why it matters
Production versus test changes Production +257/-56; tests +173/-31; test support +4/-1. Growth implements independent scalar accounting and bounded completion coverage, with focused rollback and retry regressions.

Labels

Label changes:

  • add P2: This improves large-session accounting and writer residency without establishing an urgent current outage.
  • 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.

Label justifications:

  • P2: This improves large-session accounting and writer residency without establishing an urgent current outage.
  • 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.

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 October 16, 2026, 10:46 AM ET / 14:46 UTC.

@steipete
steipete merged commit 87ca2c8 into main Oct 16, 2026
145 of 146 checks passed
@steipete
steipete deleted the dbasync/bigturn-accounting branch October 16, 2026 14:50
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…enclaw#174274)

Keep exact context event/byte totals in the session actor across ordinary appends and metadata rewrites, with receipt publication and rollback. Bound resident completion history to 512 entries and retain indexed lookup for older retries. Remove duplicate staging snapshot reads while preserving input identity and live authority.

Focused owner tests, two Codex review rounds, and static proof cover the change. Full large-session measurements follow separately; no latency saving is claimed.

Release notes: large-session context accounting and completion hydration no longer reread all retained history during ordinary warmed operations.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 19, 2026
…turn (#1475 D1)

Carry openclaw#169843 (ca0a172, "fix: chat turns fail when
session receipts exceed transport limits") onto the composite's actor
shape, plus the transfer collector it depends on from
openclaw#169744 (31a4b92, sqlite-worker-transfer.ts only).

When the committed outcome serializes past SQLITE_WORKER_MAX_MESSAGE_BYTES,
the worker frames it through live transaction admissions and commits only
a small transfer witness. The host accepts the frames, and certifies the
outcome only when the witness names the completed transfer. The receipt cap
is unchanged.

Adaptation to 855242b: admissions carry the full projected hot snapshot
(this base has no projectSessionActorAuthority), and the commit admission
has no inner kernel publication, so authorities receive undefined there as
before. Accepted cost: on oversized sessions every frame repeats the hot
snapshot; upstream later bounded the hot state itself (openclaw#172702, openclaw#174274),
which stays a separate carry.

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 454e86e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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