Repository navigation
improve(gateway): reduce session metadata read costs - #136391
Conversation
Unify exact, child and list metadata projections at the read boundary. Preserve full session payloads and write CAS bytes, and reuse the canonical accessor types instead of duplicating their contracts.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed September 2, 2026, 12:28 PM ET / 16:28 UTC. ClawSweeper reviewWhat this changesThe PR moves session metadata projection into shared SQLite reads so Gateway metadata and history paths avoid decoding unused saved-prompt fields while full reads retain them. Merge readinessKeep this maintainer-authored PR open. The shared projection change is source-consistent across exact, child, metadata, history, and cache reads; no introduced correctness or security defect was found, but exact-head CI is still queued and maintainer approval is required. Priority: P2 Review scores
Verification
How this fits togetherGateway metadata and history endpoints read agent session records from SQLite before returning client-facing session information. The new metadata-only mode removes saved prompt snapshots before decoding and flows through exact and child session lookups. flowchart LR
A[Gateway metadata request] --> C[Session-store lookup]
B[Gateway history request] --> C
C --> D[SQLite session rows]
D --> E{Read projection}
E -->|Metadata| F[Omit saved prompt fields]
E -->|Full| G[Decode full session entry]
F --> H[Gateway response]
G --> H
Decision needed
Why: The author association and protected maintainer label require explicit human judgment even though static review found no defect. Before merge
Agent review detailsSecurityNone. PR surfaceSource -118, Tests +37. Total -81 across 18 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain the single shared SQLite projection/decoder boundary, preserve full reads for prompt-owning callers, and merge only after exact-head CI succeeds and a maintainer approves the performance refactor. Do we have a high-confidence way to reproduce the issue? Not applicable: this PR is an internal performance and projection-consistency refactor, not a separate current-main bug report. Is this the best way to solve the issue? Yes. Centralizing metadata projection at the SQLite read/parse boundary removes consumer-side mutation while preserving full reads and existing validation semantics. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 1623683f478b. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
|
Merged via squash.
|
* perf(sessions): project metadata before decoding saved prompts Unify exact, child and list metadata projections at the read boundary. Preserve full session payloads and write CAS bytes, and reuse the canonical accessor types instead of duplicating their contracts. * test(gateway): assert metadata projection for history aliases * test(gateway): scope built CLI artifact inspection
What Problem This Solves
Gateway session metadata reads decode saved skills and system-prompt snapshots that the UI never consumes. Exact metadata lookups discard those fields only after parsing, and a borrowed metadata view's
getignores the projection that itsentriesmethod honors. History/startup reads also hydrate the full parent and direct-child entries.Why This Change Was Made
Move metadata projection into the shared SQLite query/parser boundary and carry it through exact, child, history, startup, and chat-metadata reads. Reuse the existing listing projection instead of maintaining consumer-side stripping. Consolidate 19 duplicated accessor type definitions into their canonical definitions, retaining SQLite-specific contracts separately.
Full reads and raw JSON comparison bytes remain intact. Canonical-key checks, owner/participant projections, read-only missing-store behavior, cache freshness, and corrupt/retained-row handling are preserved. The SQL projection retains corrupt prompt-only objects rather than converting them into the retained-window
{}sentinel; overdepth JSON still reaches the original parser. No schema, index, transaction, concurrency policy, configuration, dependency, or protocol change.Production LOC: +134 / -252, net -118. Tests and test support: +63 / -26, net +37.
User Impact
Less work and allocation when session metadata contains large saved prompts. This fixes inconsistent metadata projection and reduces duplication; it does not claim to eliminate Gateway saturation.
Evidence
The original 148 focused cases passed. New assertions failed on the parent for both writable/borrowed Gateway prompt decoding and exact borrowed-view projection. The final owner and sibling proof totals 637 passing cases across nine files, plus the built-CLI lifecycle proof, including history/startup, ownership/participants, canonical routing, corruption, retained windows, same-timestamp updates, and rollback. One cache-test observer needed to forward the new parser argument and exclude exact CAS reads now sharing the decoder; its count/byte budgets remain, and rollback now exercises the actual list cache. Independent Codex review is scoped-clean through P2 for the production refactor and both CI fixture corrections.
Controlled Blacksmith Testbox run: command exit 0; worker stopped after artifact verification. Baseline
e9f322ff2326abcf4cea736786827e1b737c4774; final production afterimages exactly match the measured candidate. Each revision installed and builtsourcePerformanceseparately, with all 36,679 source entries and 8,783 build entries verified unchanged. Node 24, four-CPU affinity, fresh HOME/state and loopback ports. Synthetic streaming provider; real Gateway HTTP/RPC. No operator or production Gateway was used.All 10 load runs passed the unchanged 2000ms control/handshake budgets with zero operation failures and zero plugin metadata rescans. Workload: 32/64 turns, 48 seed sessions, 128 updates/4 clients, 3 history clients × 5 burst, 6 visible subscribers, 100ms cadence, 1000ms stream delay. Before/after/after/before at each concurrency, plus separate 64-turn CPU profiles.
At 64 turns, candidate history p99 was 624.6 / 626.6ms, versus 993.5 / 627.0ms before. Candidate
sessions.listmaxima were 599.9 / 606.9ms, versus 985.0 / 608.6ms before. Typical tails are similar; the slower first baseline repetition is not attributed wholly to this patch.Component medians over 12 rounds of 100 reads, same worker, 48 rows:
The fixture uses one long prompt string, not every real prompt shape. Small-row metadata overhead increased by roughly 9µs; full-read timings were close. No universal speedup or memory-leak claim is made.
Residual saturation remains: candidate readiness degraded in 283/283 samples and median event-loop utilization stayed 1. Profiled transaction stacks occupied 17.57% before / 16.27% after, history handlers 11.95% / 11.43%; inclusive costs overlap and are not additive. RSS varied across repetitions.
Artifact bundle SHA-256:
80d62b3f1c3f12cd9a73e258edee2403319caf9355427aa4a4b8a7d18b46ca5e. The full changed-code gate and final local cache-fixture gate both exited 0. The one-shot worker stopped. Final exact-head CI passed on4f421e2036e7721330cc37461f1654a08622ee78, including the aggregate gate, both Windows jobs, and the built-artifact lifecycle proof.On initial head
d70dd0e, CI run33649514321attempt 1 lost its self-hosted runners before any test step; one unchanged-head retry used the workflow’s existing hosted fallback. Attempt 2 passed 227 checks and exposed two failures (plus the aggregate gate). The exact history-alias expectation now includes the metadata projection, preserving all other arguments; its complete 213-case file passed in original order. The built-CLI lifecycle proof requested a 293,362-byte all-plugin inventory through a 256 KiB log-tail helper. It now inspects only its explicit OpenAI provider artifact (4,097 bytes), retaining the bundled identity and built-path assertion without changing any limit. The complete real Gateway/mock-provider lifecycle proof passed in 147 seconds. No failed assertion, test, buffer bound, or latency budget was removed or relaxed.Maintainer Disposition
Accepted for landing as the requested internal session-read refactor. The latest completed ClawSweeper review covers this exact head and found no code or security defect; its outstanding CI condition is now satisfied. The read-only projection preserves existing storage semantics, and the residual saturation and measurement limitations above remain explicit. No required check or review rule is bypassed.