Skip to content

perf: avoid unused session lifecycle read snapshots - #169748

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

steipete merged 2 commits into
mainfrom
dbasync/readsnap

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway metadata and native model ownership reads request lifecycle timestamps that their consumers never use. That request forces a deferred read transaction even when the existing entry-facts query already returns an atomic result.

User Impact

Internal SQL reduction with unchanged session data, membership authorization, reset behavior, and user-facing contracts. No schema migration, update step, or configuration change.

Why This Change Was Made

Make lifecycle timestamps opt-in for qualified Gateway reads, remove unused lifecycle requests from native model preparation, and explicitly retain them for restart-safe chat admission. This reuses the existing single-query/retained-facts path; it adds no transaction helper, cache, SQL, or engine branch. PostgreSQL single-statement reads therefore remain plain queries.

Removed work and accepted edge case: metadata/observer/model ownership consumers no longer obtain unused lifecycle timestamps. A concurrent lifecycle-only change cannot affect their result because these consumers do not use those timestamps. Reset/admission consumers still request a coherent entry/header snapshot. Membership and live source-authority checks remain intact.

Evidence

One live baseline/candidate pair uses the shared SQL workload with transaction attribution, synthetic provider and isolated state. The task copy only restores census instrumentation, moves scratch to external storage, and disables evidence archives; workload and assertions are unchanged.

Measured base 9c54108f9f20a39211a5aba3a2bd2d6f8393d1a5 against patch head bbbe89debcbda75097ca3e55efd041717cd1612b, before integrating main's static fixes. Values below are aggregate counts divided by 10 warmed turns (one pair, not repeated-sample medians).

Warmed metric (per turn) Base Candidate Delta
All-thread SQL statements 311.2 363.4 +52.2
Worker requests 85.1 105.6 +20.5
MAIN statements 0 0.4 +0.4
All deferred BEGIN / matching COMMIT 18.6 / 18.6 18.7 / 18.7 +0.1 / +0.1
Exact-entry SQL statements 15.2 13.0 −2.2
Exact-entry requests 7.2 7.0 −0.2
Exact-entry BEGIN / matching COMMIT 3.0 / 3.0 2.0 / 2.0 −1.0 / −1.0

The deterministic saving is one redundant read envelope per warmed turn: 2 SQL statements removed, with no added request. The complete exact-entry family saves 22 statements and 2 requests across the sample; across the entire workload it changes from 277 statements / 124 requests to 245 / 122.

Raw totals rose because the candidate workload took 532.6 seconds on a heavily contended host versus 103.5 seconds for the baseline, allowing additional periodic work. For example, warmed database.domain.publish changes from 389 statements / 92 requests to 674 / 175, and transcript exports from 20 / 4 to 85 / 17. Additional cleanup/health/maintenance families also enter the warmed phase. All four candidate MAIN statements are existing periodic GitHub OAuth record reads from github-oauth-lifecycle.ts:reconcileRecords; the changed entry-read owner adds none. Whole-workload totals are 9,337 → 10,072 statements and 1,687 → 1,963 requests. This is owner-attributed SQL proof, not a latency improvement claim.

Gateway-main-thread T1 call sites in the changed area: 0 → 0. Final integrated-head CI's repository-wide worker ratchet is 544 → 544, and its dialect ratchet passes. No database call or synchronous fallback was added.

All 13 chat turns, child execution, cron, compaction, and clean shutdown succeeded. The final driver assertion reported one separate control-plane failure: mentions.dismiss returned UNAVAILABLE after the unchanged mention Inbox refresh owner logged failures. This is a recorded validation gap; the warmed-turn measurements are complete. An earlier attempt failed during the connection handshake before any turn and is excluded. No SQL execution errors or transaction pairing anomalies were observed.

The storage regression reads qualified entry/membership facts, commits changed values, verifies the next read sees both, and verifies explicit lifecycle reads recover the legacy transcript-header timestamp. Existing ordered-read and lifecycle tests remain applicable. Local oxfmt, focused type-aware oxlint, and diff checks pass; focused owner tests and broad static checks run in PR CI under the requested relaxed testing workflow. Codex autoreview: scoped clean, one round, no actionable findings. No SDK surface or update/Doctor/schema/plugin-loading/service lifecycle change, so no SDK diff or published-driver update cell is needed.

Complete warmed deferred-read census

Counts are per warmed turn (10-turn sample). Each transaction has one deferred BEGIN and one matching COMMIT.

Request / owning file:function Base tx/turn Candidate tx/turn Statements inside / reason to retain
session-row-facts — session-entry-read.worker.ts:readSessionRowDatabaseFacts 5.2 4.4 3: entry, participants, summary watermark must agree.
session-row-backfill — session-accessor.sqlite-active-events.ts:readSessionTranscriptBoundedMessageTailPage 2.0 2.0 3: projection, bounded metadata, payload must describe one tail.
session-exact-entries — session-entry-read.worker.ts:readExactSessionEntriesWithLifecycle 3.0 2.0 2 transactions contain one exact-facts SELECT; 1 contains 3 related reply-init reads. This PR removes unused lifecycle requests from eligible callers, retaining the actual reset consumer.
session.entry.read — session-entry-cohort.worker.ts:readSessionEntryCohort 3.0 3.0 2–4: entry, participants, runtime target, and cold metadata must agree.
session-pending-input-history — session-pending-input-history.kernel.ts:readPendingInputHistoryInDatabase 1.0 1.0 Empty sample has only count; nonempty history needs consistent count, page, and payload. Retained to avoid adding another count/probe or split snapshot.
session-activity-summary-source — session-transcript.worker.ts:readRequest 1.0 1.0 4: projection, ancestry, bounded metadata, payload.
transcript-anchors — session-transcript-anchor-read.kernel.ts:readSessionTranscriptAnchorFactsInDatabase 1.0 1.0 9: watermark, entry/participants, projection, anchors, tail and messages.
session-entry export — session-accessor.sqlite-read.ts:readTranscriptExportSnapshotReadOnlySync 0.4 1.7 3: hot guard, events, and statistics for one export.
transcript-hydration — session-accessor.sqlite-active-context.ts:readSessionTranscriptBoundedActiveContextCore 2.0 2.0 10: projection/bounds, metadata/payload, parents and anchors.
Additional periodic list/deletion/placement recovery snapshots 0 0.6 Candidate-only background work: session-entry-list, agentDatabaseDeletion.snapshot, and workers.placementRecoveryCandidates, each 0.2.
Total 18.6 18.7 No observed unmatched/overlapping transactions.

The retained envelopes protect related rows within the owning process. No retained envelope relies on an unsupported external writer. Size-limiting SQL JSON projections are unchanged.

LOC: production +9/−5, test +70/−0, docs +7/−0. No changelog edit: release-note context is retained here.

An earlier CI run hit an inherited type-suppression inventory expectation and the built-CLI lifecycle failure also recorded in main run 38220958692. The inventory fix was integrated, and both jobs pass on the final head.

Integrated main through fdbe95f5d1d68c160d8d281560b7ea43894bf00d without conflicts to include the inventory fix (64f11ced232c7) and existing Knip export cleanup (f0a14bf986e60). The measured owner implementation is unchanged by integration. Final integrated-head CI has green production types, all test-type stripes, core/extension lint, source contracts/export checks, Madge architecture, guards, and T1/dialect ratchets. The changed freshness test file passes all 8 cases (11.56s Vitest / 12.97s wrapper; new case 1.701s) in job 114736157967. Local test suites were waived by the requested CI-first workflow. The final CI aggregate is red only for the inherited corruption-fixture expectation detailed below; no PR-caused static or test failure remains. Full-tree and script Knip export scans pass. The production scan has only the precisely attributed inherited export finding below. All static requirements are passed or independently attributed to main.

The integrated-head production Knip scan reports only the pre-existing src/gateway/control-ui-public-session-card-render.ts: renderPublicSessionCardSvg export. The identical rule and file fail in main job 114717131950; main already fixes it in 802f3415be1f. The PR neither changes that module nor its consumers. The initial 600-second scan timed out under local contention; the same scan was retried serially with a 30-minute wall-clock allowance and no rule changes.

Final CI inherited-failure disposition: job 114736158090 fails only sessions-resolve-projection.test.ts / preserves warm and cold storage-reader outcomes for mismatched-window rows (expected target-id, received undefined). Its checkout log explicitly identifies merge b5f152ec824d3c2d55f5d70f0f1151f0016cc14e, combining this head with main 2c7cc827b309c6a2da1cd6c2aa5cb930eb326030. That main commit adds current_session_id to loadSessionEntrySnapshot's SELECT; the existing parseSqliteSessionEntryRecord rejects a row whose current session ID differs from its JSON session ID. The test deliberately creates that mismatch but retains its old expectation. This is the synchronous list-reader path, not either changed lifecycle-read path. The failing test and parser are unchanged by this PR. Focused local comparisons were attempted, then stopped during slow fixture startup once the actual CI checkout and source change established attribution; they are not claimed as passing proof. Landing uses the authorized inherited-failure exception.

@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 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: S labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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 makes lifecycle timestamp reads opt-in while preserving coherent snapshots for restart-safe chat admission.

Example: Read metadata for agent:main:qualified-lifecycle.

  • Before: The qualified reader prepares unused lifecycle timestamps inside a deferred transaction.
  • After: Metadata uses atomic entry facts; restart-safe admission explicitly requests lifecycle timestamps.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-consistent; reported measurements are appropriately limited, while independently inspectable runtime evidence remains limited.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body reports successful isolated Gateway chat turns and reduced exact-entry transaction work, but underlying runtime traces are not linked for independent inspection.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Session preparation performs avoidable transaction work for lifecycle timestamps that metadata and native ownership consumers discard.
Reason: Maintainer-directed scope removes unnecessary work while preserving session data, authorization, and restart-safe admission.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it provides a focused, maintainer-directed optimization absent from current main, with no introduced correctness or security defect found.

Priority: P2
Reviewed head: d02c28c7d1a116618442659d389670e602528110

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported Gateway SQL census has no linked underlying trace, and the new storage regression has no supplied base-fail/head-pass result.
Agent review details

How this fits together

Gateway session readers and native model preparation request worker-owned entry and membership facts; restart-safe chat admission additionally consumes lifecycle timestamps for reset freshness.

flowchart TD
 A[Metadata and observer readers] --> B[Qualified session reader]
 C[Chat admission] --> B
 B --> D[Worker entry facts]
 D --> E[Atomic entry and membership query]
 B --> F[Requested lifecycle snapshot]
 F --> G[Entry and transcript header]
 H[Native model preparation] --> D
Loading

Technical review

Best possible solution:

Retain the caller-level optimization and the existing coherent lifecycle snapshot wherever reset freshness requires it.

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

Current-main source shows unused lifecycle requests selecting the deferred snapshot path; the reported workload attributes a matching transaction reduction to the candidate.

Is this the best way to solve the issue?

The patch reuses the existing atomic query and worker owner, preserves the actual lifecycle consumer, and introduces no competing cache or public setting.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Qualified Gateway lifecycle preparation changes intended behavior with a stated reason (00daeeb: Move chat lookup to workers while preserving selected physical storage and current caller authority.)
  • Retained sharing and reply readers keeps the original intent (4590844: Carry selected execution through turn phases and avoid repeated discovery with bounded related facts.)
  • Native runtime ownership reads changes intended behavior with a stated reason (26b3127: Prepare conversation ownership through workers while retaining final authority guards.)
  • Runner ownership bookkeeping keeps the original intent (5d6cf74: Simplify overlapping bookkeeping while retaining checks that protect real effects.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduction: The introduced hunks remove unused lifecycle requests, propagate an internal opt-in, and explicitly enable it for chat retry admission. (src/gateway/session-utils-store.ts:259, d02c28c7d1a1)
  • Atomic facts boundary: Entry, participant, and membership facts come from one SQL statement; the existing worker adds a snapshot when lifecycleSessionKey requests the separate header fallback. (src/config/sessions/session-accessor.sqlite-entry-facts.worker.ts:95, d02c28c7d1a1)
  • Reset consumer preserved: withCurrentChatSendRetry explicitly requests lifecycle facts before restart-safe admission consumes them; membership, physical-source, caller, and configuration checks remain. (src/gateway/server-methods/chat-send-work-admission.ts:113, d02c28c7d1a1)
  • Current main still needs the optimization: Fetched main retains the unconditional lifecycleSessionKey in the qualified reader. (src/gateway/session-utils-store-retained.ts:159, 23a6da89a61a)
  • Reported performance result and accepted tradeoff: The complete PR body reports an isolated Gateway baseline/candidate workload with exact-entry deferred transactions reduced from 3.0 to 2.0 per warmed turn. It explicitly accepts omitting timestamps these consumers discard, discloses higher aggregate background work and a separate mentions.dismiss failure, and makes no latency improvement claim. (bbbe89debcbd)
  • Inherited CI attribution: The failing check annotation reports the catalog fixture expecting target-id but receiving undefined. Main commit 2c7cc82 adds current_session_id to its snapshot query, activating the existing parser rejection for the fixture's deliberately mismatched row. This PR changes neither the fixture, parser, nor catalog query. The other failure is the aggregate gate; raw job logs were blocked by the artifact host allowlist, so attribution uses annotations and source. (src/gateway/sessions-resolve-projection.test.ts:457, d02c28c7d1a1)

Likely related people:

  • Peter Steinberger: Raw commit 00daeeb adds src/gateway/session-utils-store-retained.ts:36 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 00daeebaf390; files: src/gateway/session-utils-store-retained.ts)

PR surface

Source +4, Tests +70, Docs +7. Total +81 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 9 5 +4
Tests 1 70 0 +70
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 86 5 +81

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +9/−5; tests +70/−0 Small production growth carries the lifecycle opt-in; the storage regression checks committed metadata, membership freshness, and legacy header fallback.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A bounded session-read performance improvement with no demonstrated urgent user-facing failure.
  • 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-12T08:18:02.459Z sha bbbe89d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T09:02:45.700Z sha d02c28c :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 5:33 AM ET / 09:33 UTC (Revision 3).

@steipete steipete added the ci:no-fail-fast Keep all selected CI matrix jobs running after failures on the next PR run. label Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Oct 12, 2026
@steipete
steipete merged commit d25e4d3 into main Oct 12, 2026
130 of 133 checks passed
@steipete
steipete deleted the dbasync/readsnap branch October 12, 2026 09:35
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
Make qualified Gateway lifecycle timestamps opt-in and remove unused native model lifecycle reads. Preserve the coherent entry/header snapshot for restart-safe chat admission and all membership/source-authority checks.

Reuses the existing atomic entry-facts read, removing one BEGIN/COMMIT pair per warmed turn. No schema, permissions, or update behavior changes.

Regression covers current entry and membership facts after in-process writes and explicit legacy lifecycle timestamp recovery.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling ci:no-fail-fast Keep all selected CI matrix jobs running after failures on the next PR run. 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: 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