Skip to content

improve: count marker-heavy transcripts without display metadata - #146382

Merged
steipete merged 1 commit into
mainfrom
codex/sqlite-history-count
Sep 15, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/sqlite-history-count

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #146371

What Problem This Solves

Counting a transcript with many visible markers builds display metadata that the caller discards.

User Impact

Visible-history counts become cheaper for marker-heavy sessions, including the Gateway sequence fallback when transcript updates lack a supplied sequence. Counts, errors and cold restoration remain unchanged. No migration or operator action is required. Synthetic measurements show gains of 19–31% for the 1,000-marker cases and a 9.8% regression in the unanalyzed 100-marker case; this is not a uniform or whole-Gateway speedup claim.

Why This Change Was Made

The count reader aggregates the existing marker selection and adds the existing reset-aware message total inside the same projection snapshot. It avoids marker metadata, the following-row join, ordering and next-message lookups. Full history and counting share the selection, including reset, inactive-branch and JSON guards.

Evidence

Baseline main: ad2e57b87c7624b7b292e63d0ba8f6649c9811db, which already amortizes marker-gap lookups. Actual public readSessionMessageCountAsync calls on synthetic canonical transcripts, Windows Node 26.8.2 / SQLite 3.53.4; complete captured owners with only import locations rewritten, shared dependencies and seven alternating blocks per cell:

Fixture Before ANALYZE, main → candidate After ANALYZE, main → candidate
message-only 2.609 → 2.348 ms 2.471 → 2.122 ms
one-marker 4.955 → 4.481 ms 3.751 → 3.609 ms
100-markers-interleaved 5.522 → 6.065 ms 4.882 → 4.538 ms
1000-markers-interleaved 10.474 → 7.189 ms 10.486 → 7.373 ms
1000-markers-trailing 14.677 → 11.733 ms 12.304 → 8.964 ms
1000-markers-consecutive 12.735 → 10.343 ms 12.378 → 9.461 ms
reset-kept-prefix 9.163 → 8.418 ms 9.075 → 8.139 ms

All 14 timed cells preserve exact counts, schema/typed-row and main/WAL/journal fingerprints, and integrity. Fourteen additional malformed/deep/inactive/pre-reset/compaction cells preserve exact values or errors. Two real cold archive/restore flows preserve the direct cold error and restore identical canonical events through the public async reader, returning count 4. Restoration intentionally writes through its existing owner.

A separate branch fixture stores 10,000 inactive markers with 22 active events. Both versions return 22; both use active-row driving after ANALYZE and identity driving before ANALYZE. The candidate uses a covering active index in the analyzed branch. These are plan and correctness checks, not branch latency or scanned-row measurements.

For 1,000 markers, the count query delivers one aggregate row to JavaScript instead of 1,000 metadata rows. It still evaluates the shared visibility predicate; returned rows are not SQLite rows scanned.

The paired run completed all timings, then stopped on an incorrect supplemental harness expectation that the unchanged baseline would drive from active rows before ANALYZE. Original failed artifacts and all timings are preserved. A separate supplemental-only run corrected that expectation to the existing analyzed-plan contract and passed every branch/error/cold check, without rerunning timed fixtures.

Validation: 69 existing tests passed across seven files covering the Gateway facade, history/reset/query-plan/marker-gap behavior, cold-read races and watermark isolation. Fresh independent P0–P2 review completed scoped-clean for this exact candidate; formatting and whitespace checks passed. The changed-check plan was inspected. Local lint was interrupted for shared-host capacity after identifying its type-aware default; local lint/type/schema passes are not claimed. Required exact-head hosted CI owns those integration checks and the native landing gates.

Limits: warm synthetic Windows reader measurements with uncontrolled host-wide load and OS caches; no cold-latency, p95, whole-Gateway throughput or concurrent-writer race claim. Final integrated-main remeasurement follows landing.

@clawsweeper

clawsweeper Bot commented Sep 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 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 12, 2026 19:49
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 12, 2026
@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 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 15, 2026, 1:59 AM ET / 05:59 UTC (Revision 3).

ClawSweeper review

What this changes

Counts visible transcript messages and markers with a scalar query while sharing the history reader’s existing visibility rules.

Merge readiness

✅ Ready for maintainer review

The refreshed PR resolves the prior integration blocker and measurement follow-up. No actionable correctness defect was found, and current main still performs the unnecessary metadata work.

Priority: P2
Reviewed head: ff8ea31822571e13d32bdf7a49a8d38376ff0dad

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with substantial, candidly bounded runtime evidence and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured PR evidence exercises the public count reader and production SQLite owners on Windows, showing preserved counts, errors and cold restoration alongside improved marker-heavy timings. It satisfies the prior measurement follow-up; the synthetic warm-reader results do not establish whole-Gateway performance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured PR evidence exercises the public count reader and production SQLite owners on Windows, showing preserved counts, errors and cold restoration alongside improved marker-heavy timings. It satisfies the prior measurement follow-up; the synthetic warm-reader results do not establish whole-Gateway performance.
Evidence reviewed 9 items Current main still needs the optimization: Current main’s count reader still calls resolveVisibleHistoryProjection and discards everything except total. The two affected files are unchanged between the refreshed benchmark baseline and fetched main.
One shared visibility owner: The scalar count and full projection use the same extracted marker query, including session scope, active membership, reset boundaries, index selection and guarded JSON predicates. The count adds the existing reset-aware message total; full history retains its ordering and metadata construction.
Snapshot and recovery contracts remain intact: The count still runs through withCurrentProjectionSnapshot, which validates projection freshness and cold-storage state inside the existing read transaction. The public asynchronous reader retains cold restoration and projection-reconciliation retry handling.
Findings None None.
Security None None.

How this fits together

OpenClaw’s SQLite transcript reader turns stored session events into visible history and counts. The Gateway also uses these counts when a transcript update needs a sequence fallback.

flowchart TD
  A[Stored transcript events] --> B[Validated session snapshot]
  B --> C[Reset-aware message total]
  B --> D[Shared visible marker selection]
  D --> E[Scalar marker count]
  C --> F[Visible history count]
  E --> F
  F --> G[Gateway sequence fallback]
  D --> H[Full history metadata]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +18. Total +18 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 2 59 41 +18
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 59 41 +18

Review metrics

Metric Value Why it matters
Marker rows returned to JavaScript 1,000 metadata rows → 1 aggregate row The count avoids per-marker materialization; this does not imply SQLite scans only one row.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #146371
Summary: This PR directly implements the linked count-materialization issue; the earlier history-loading optimization addresses adjacent work.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep scalar counting within the existing projection owner, sharing visibility selection with full history and preserving snapshot, reset and recovery semantics.

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

Yes: current-main source shows the public count path constructing marker metadata before returning only its total, and the supplied paired SQLite measurements exercise that path. This read-only review did not run the benchmark.

Is this the best way to solve the issue?

Yes: extracting the existing selection and aggregating it avoids competing visibility logic while retaining the current snapshot and recovery owners.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded transcript-reader performance improvement with measured gains for marker-heavy sessions.
  • 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): The captured PR evidence exercises the public count reader and production SQLite owners on Windows, showing preserved counts, errors and cold restoration alongside improved marker-heavy timings. It satisfies the prior measurement follow-up; the synthetic warm-reader results do not establish whole-Gateway performance.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured PR evidence exercises the public count reader and production SQLite owners on Windows, showing preserved counts, errors and cold restoration alongside improved marker-heavy timings. It satisfies the prior measurement follow-up; the synthetic warm-reader results do not establish whole-Gateway performance.

Evidence

What I checked:

  • Current main still needs the optimization: Current main’s count reader still calls resolveVisibleHistoryProjection and discards everything except total. The two affected files are unchanged between the refreshed benchmark baseline and fetched main. (src/config/sessions/session-accessor.sqlite-history-events.ts:508, b757ce0d5fd1)
  • One shared visibility owner: The scalar count and full projection use the same extracted marker query, including session scope, active membership, reset boundaries, index selection and guarded JSON predicates. The count adds the existing reset-aware message total; full history retains its ordering and metadata construction. (src/config/sessions/session-accessor.sqlite-history-projection.ts:100, ff8ea3182257)
  • Snapshot and recovery contracts remain intact: The count still runs through withCurrentProjectionSnapshot, which validates projection freshness and cold-storage state inside the existing read transaction. The public asynchronous reader retains cold restoration and projection-reconciliation retry handling. (src/config/sessions/session-accessor.sqlite-active-projection.ts:175, ff8ea3182257)
  • Refreshed runtime evidence and accepted tradeoff: The supplied body snapshot, sourceRevision cd896d6d226feb2f56803f31034cf387b13e22676d031eafbc304c7003e41436, reports public readSessionMessageCountAsync measurements using captured production owners and real SQLite on Windows, Node 26.8.2 / SQLite 3.53.4. All 14 timed cells preserve counts and storage fingerprints; additional error, branch and cold-restore checks preserve behavior. The maintainer explicitly accepts the 9.8% unanalyzed 100-marker slowdown in improve: count marker-heavy transcripts without display metadata #146382 (comment). The evidence discloses the corrected supplemental harness expectation and does not claim whole-Gateway gains. (ff8ea3182257)
  • Existing coverage protects visibility and error parity: Existing tests compare count and history behavior for inactive markers and malformed or deeply nested JSON, both before and after ANALYZE. Public reader fixtures also cover displayed versus hidden custom messages, retained reset prefixes, compactions and repeated resets. These tests were inspected; this review did not execute them. (src/config/sessions/session-accessor.sqlite-history-events.test.ts:473, ff8ea3182257)
  • Previous integration blocker resolved: Raw test-merge parent records match pinned base c657a10 followed by exact head ff8ea31. Comparing the merge result with that base shows only the intended two files. The refreshed body supplies the previously requested count and timing comparisons. (7dfa736e4ff9)

Likely related people:

  • steipete: 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 (2 earlier review cycles)
  • reviewed 2026-09-12T19:58:51.508Z sha cef1ceb :: blocked before merge. :: none
  • reviewed 2026-09-15T05:40:55.678Z sha cef1ceb :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/sqlite-history-count branch from cef1ceb to ff8ea31 Compare September 15, 2026 05:54
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The candidate and PR evidence have been refreshed against main ad2e57b87c7624b7b292e63d0ba8f6649c9811db, which already amortizes marker-gap lookups. This change keeps the current query selection and adds a scalar count in its existing projection owner; the prior candidate's larger gains are not used to justify this version.

Maintainer assessment: the disclosed 9.8% regression in the unanalyzed 100-marker case is acceptable for this bounded optimization. All six 1,000-marker cells improve by 18.8–31.4%, reset-kept cases improve by 8.1–10.3%, and the count operation avoids display metadata materialization without changing storage or visibility. These synthetic reader measurements do not establish uniform or whole-Gateway gains.

Fresh validation includes 69 existing tests, all 14 paired count/storage cells, 14 exact error/value cells, two cold restores and two short-active-branch plan checks. The initial supplemental harness mistake and its separate corrected proof are disclosed; no timed result was replaced. Required exact-head CI and independent review still apply.

@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@steipete
steipete merged commit 5b49bdf into main Sep 15, 2026
195 checks passed
@steipete
steipete deleted the codex/sqlite-history-count branch September 15, 2026 06:22
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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: 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.

Transcript counts materialize unused marker positions and metadata

1 participant