Skip to content

perf(sessions): avoid duplicate reads during compaction - #169931

Merged
steipete merged 2 commits into
mainfrom
dbasync/compactpath
Oct 12, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/compactpath

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Manual transcript compaction hydrates the transcript more than once. Its ordered cursor previously read event sequence numbers, then issued a separate query for the first 64 KiB of every event. Return that first bounded slice from the cursor and retain follow-up reads only for larger events. This preserves the SQLite snapshot, event order, database encoding, transport backpressure and bounded memory. Large payloads stay sliced in SQL.

Read compaction's entry and transcript statistics once after the previous writer settles, then reuse those facts while the lifecycle owner excludes competing session work. Keep the final persistence guard and live requester/operator authority checks. The regression starts with an empty transcript, commits the previous writer's final message and entry update during settlement, and verifies compaction sees both.

Measurement

One alternating baseline/candidate pair of the shared live SQL workload, with the workload unchanged and request attribution added in a private harness copy. Baseline 0cea8cd24977; candidate c62673a2ffb6. All workload assertions passed on both. Counts include all threads; warmed statistics cover ten turns per run.

Metric Baseline Candidate
Compaction statements 205 142 (−30.7%)
Compaction requests 37 43
Compaction MAIN statements 0 0
Warmed statements median [min–max] 439 [393–506] 398 [388–451]
Warmed requests median [min–max] 107.5 [90–124] 93.5 [89–106]
Warmed MAIN median [min–max] 0 [0–1] 0 [0–0]
First-turn statements / requests 950 / 203 758 / 158
Whole-workload statements / requests 11,451 / 2,062 10,705 / 1,841

The baseline already has zero compaction MAIN SQL: the older census's two reads are absent. Changed owners have no Gateway-main-thread SQL calls: T1 0 → 0. CI's worker/T1 and dialect ratchets pass.

Operation attribution

Compaction operation Statements baseline → candidate Requests baseline → candidate
streamSessionTranscriptHydration cursor / slices / transaction envelope 78 → 6 2 → 2
Transcript statistics owner 5 → 4 2 → 1
Exact-entry facts 2 → 7 3 → 8
Secret expiry / GitHub connection maintenance, including transaction envelopes 0 → 5 0 → 2

The changed operations remove 73 statements and one request: 72 per-event first-slice SELECTs and one duplicate statistics read. The entry reread removal is not assigned an additional measured saving because retained facts already elide it in this workload. Five additional exact-entry requests dispatch from WorkerTaskPoolCore.finish, and two unchanged maintenance requests (purgeExpiredSecretStoreEntries, runMaintenance) fall inside the candidate's compaction window. These add ten statements and seven requests, explaining the observed −63 statements / +6 requests exactly. Whole-workload exact-entry requests fall from 101 to 91; no new request class or dispatch was added by this PR.

The host load changed substantially between runs: complete workloads took 339.6s and 85.1s; compaction windows took 1.919s and 3.122s. Do not interpret these as latency benchmarks or credit the raw warmed-turn decrease to this PR. The modified full-hydration worker runs only during compaction in this workload; warmed turns use the separate bounded-hydration path. Background scheduling explains changes outside the touched operation. Exact operation savings above are directly counted, independent of elapsed time.

Shared-family statements per warmed turn:

Family Baseline Candidate
Exact-entry facts 9.1 8.1
Actor hydration 6.6 6.4
Entry-cache snapshots 1.8 0.8
Row facts 14.4 13.5
Watermarks 5.8 5.5

No shared warmed family rises. This PR adds no cache, invalidation policy, schema, worker routing, or compatibility path.

Removed checks and accepted edges

  • Per-event first-slice reread: the ordered cursor already supplies those bytes from the same snapshot; no new consistency tradeoff.
  • Preparation-to-execution entry reread: the lifecycle owner covers both phases. An out-of-contract raw mutation may leave prepared descriptive facts old until the retained final mutation guard rejects it.
  • Duplicate transcript-statistics reads: read once after prior writer settlement under the same lifecycle owner; no separate timing probe.

No schema, update, migration, plugin-loading, service-lifecycle or public SDK change. No change to compaction checkpoints or transcript durability. No update cell or SDK API diff applies.

Evidence

  • Changed-file oxfmt, type-aware oxlint and git diff --check pass.
  • Added byte-boundary hydration coverage (65,535 / 65,536 / 65,537 / 131,072 bytes); existing concurrent-replacement coverage checks snapshot consistency and subsequent fresh reads.
  • Added post-settlement entry/transcript regression; retained empty-transcript behavior for native and legacy harnesses.
  • Codex autoreview: scoped-clean, no actionable findings. Two invocations total, including one interrupted before inference.
  • Final-head CI is green: changed tests, production/test types, lint, source/export contracts, Madge and database ratchets. Changed-test shards took 77–365s including setup. First-head CI exposed an unpinned test runtime; the fixture now explicitly pins its intended native runtime.
  • Knip script export scan passed. Production and isolated full-tree scans report only the untouched DurableDirectoryReceipt re-export. The same rule/symbol fails in scheduled main CI; newer main already removes it in 9514dbad63f, and this PR does not reintroduce it. The initial concurrent full-tree scan timed out at 600s; the isolated rerun completed within the unchanged limit.
  • Local diagnostic pnpm test src/gateway/server.sessions.compaction.test.ts --maxWorkers=1: 20 passed, 1 timeout in the existing reset-waits-for-terminal-compaction test; 701.35s total under heavy load. The new regression passed. The timeout remains an unresolved local observation; passing current-head CI does not prove it fixed.

LOC: production −2 (33 added / 35 removed); tests +63 (109 added / 46 removed); docs +5.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

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 labels Oct 12, 2026
@clawsweeper clawsweeper Bot added 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. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR combines transcript cursor and first-slice reads and reuses compaction facts collected after prior writers settle.

Example: Session sess-compact-settled initially has no transcript; its previous writer commits a final message during settlement.

  • Before: Compaction returns “no transcript” before waiting for the writer.
  • After: Compaction waits, reads the committed message and updated entry, and proceeds.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch appears correct and has meaningful boundary coverage; runtime performance evidence remains limited.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; boundary-test source and CI support the changed owners, while the comparable after-fix live compaction measurement remains explicitly pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Manual compaction performs unnecessary database work and can miss a final transcript write when the session initially appears empty.
Reason: The maintainer-authored direction improves existing behavior with a smaller production implementation and no new option or public contract.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it contributes useful compaction improvements absent from current main, and review found no introduced correctness or security defect.

Priority: P2
Reviewed head: c62673a2ffb672f181028adfb76d59b3ce335f5f

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The planned candidate workload results and a recorded base-fail/head-pass settlement regression are not supplied.
Agent review details

How this fits together

The Gateway compaction RPC coordinates session lifecycle ownership and invokes the compaction runner; the history worker reads canonical SQLite events and returns bounded transcript frames.

flowchart TD
  A[Compaction request] --> B[Prior writer settlement]
  B --> C[Session lifecycle owner]
  C --> D[Prepared compaction facts]
  D --> E[Compaction runner]
  E --> F[History worker snapshot]
  F --> G[Bounded transcript frames]
  E --> H[Guarded persistence]
Loading

Technical review

Best possible solution:

Keep the existing worker and lifecycle owners while removing their redundant reads.

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

Current-main source shows per-event first-slice queries and an empty-transcript return before writer settlement; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch removes duplicate work at the existing owners while preserving snapshot transfer, storage-error propagation, lifecycle exclusion and final persistence checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 63bd1e92db98.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit dbd3bf7 adds src/config/sessions/session-transcript-hydration.worker.ts:31 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dbd3bf7da26b; files: src/config/sessions/session-transcript-hydration.worker.ts)

PR surface

Source -2, Tests +63, Docs +5. Total +66 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 33 35 -2
Tests 3 109 46 +63
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 147 81 +66

Review metrics

Metric Value Why it matters
Production versus test LOC Production −2; tests +63 Production removes duplicate work; test growth covers byte boundaries, settlement ordering and empty-transcript behavior.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Focused compaction performance and settlement-ordering improvements have limited blast radius.
  • 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.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Publish the planned comparable baseline/candidate compaction workload results, including SQL counts and successful compaction outcomes.

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-10-12T13:53:30.329Z sha f9481cf :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T14:07:02.727Z sha c62673a :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 10:45 AM ET / 14:45 UTC (Revision 3).

@steipete
steipete merged commit f0818ac into main Oct 12, 2026
145 checks passed
@steipete
steipete deleted the dbasync/compactpath branch October 12, 2026 15:16
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
)

Return the first bounded transcript byte slice from the ordered hydration cursor and reuse entry/statistics facts after writer settlement. Preserve snapshot consistency, backpressure, exact bytes, lifecycle ownership, and final mutation authority.

Live paired proof: compaction statements 205 -> 142 (30.7% fewer), MAIN 0 -> 0. The changed operations remove 73 statements and one request; the raw phase includes seven additional queued/maintenance requests. Current-head CI and Codex review completed. The only Knip finding is the pre-existing durable receipt re-export already removed on main.
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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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