Repository navigation
Description
Problem
Some Storage and Runtime Host operations process substantially more data than the requested result or the new change requires. Repeated page serialization, full-record output updates, full-store metadata reads, and historical Usage materialization can spend CPU, memory, and I/O on unchanged or unrelated data.
This tracker owns the remaining delivery and measurement work identified by Discussion #4876. It is scoped to read/write amplification in Storage and the Host protocol, rather than every performance issue in Maka.
Scope and relationship to existing work
- This tracker: rows scanned/materialized/decoded, bytes encoded and written, and how those costs scale with the requested page, changed data, and stored history.
- tracking(perf): bound Desktop and Runtime Host work as history grows #4677: user-visible Desktop and Host outcomes such as startup, Session opening, scrolling, and reading-position preservation. A storage improvement does not by itself satisfy those latency and interaction budgets.
- perf(desktop): make session data flow incremental and bounded #2913: incremental Session data flow. Reuse its existing work where the same path is involved.
- Discussion [DISCUSS] Storage and protocol: four published rules, each enforced in exactly one path #4876: the underlying rules, accepted exceptions, and unresolved policy questions. This issue does not turn every proposal in that discussion into an approved implementation requirement.
Use existing issues and PRs for their concrete work. Links here record dependencies and acceptance; they do not create a second implementation or a second owner.
Current evidence
Source inspection baseline: 87797378c. The observations below are code-path evidence, not new production latency measurements.
Repeated encoding and page assembly
Several page builders append one item, serialize the entire candidate page, and discard that encoding after checking its byte length. Examples:
For similarly sized items, cumulative serialization work grows quadratically with the number of items admitted to a page. Existing count/byte caps limit several of these paths; this is not a claim of unbounded whole-history work or a measured user-visible regression in every page builder.
Byte-limit helpers also retain private copies alongside protocol/codec.ts. Consolidation alone is not performance acceptance: measure actual repeated serialization along producer/consumer paths. The transport already accepts EncodedProtocolMessage; extend that seam where applicable rather than adding a parallel encoding path. Raw frame bytes, normalized values, and nested-object budgets are distinct and must not be substituted for one another.
Shell output persistence
ShellRunManager.queuePersist compares the output snapshot with the current record and calls updateShellRun. Storage reads the stored record and serializes the complete next record into record_json.
The full-record operation is confirmed. Its practical amplification remains to be measured against retained-output bounds, flush frequency, and SQLite write/WAL bytes before selecting a representation change.
Existing delivery paths
| Work | Existing issue / PR | Remaining acceptance |
|---|---|---|
| Artifact point reads and revisions | #4037 / #4874 | Verify bounded materialization when unrelated Sessions grow and when the target Session grows; preserve revision consistency and cross-process visibility. |
| Batch artifact cleanup during Session retirement | #4038 / #4984 | Verify batch work avoids repeated whole-store guard scans while preserving physical deletion safeguards and retryability. |
| Revision-consistent bounded Usage reads | #4058, #5019 / #5023; related UI work #4531 / #4539 | #5023 is currently a design-only draft. Resolve its Storage/query boundaries, then measure SQL scan/sort work as well as application decoding and transfer. UI pagination alone is insufficient. |
Delivery checklist
- Deliver the first encoding/page-assembly change through existing protocol seams. Record the concrete covered paths, remove replaced implementations in the same change, and attach same-load before/after evidence. Keep this as one PR unless an actual dependency blocks part of the work.
- Measure Shell output persistence at representative retained-output sizes and flush rates. Record either a justified follow-up with its recovery contract or an explicit decision that the bounded cost is acceptable.
- Accept Artifact point-read growth behavior through perf(storage): artifact metadata rewrites the full record table on every mutation (O(M×N) during startup) #4037 / perf(storage): bound artifact point reads and revisions #4874.
- Accept batch retirement behavior through perf(storage): batch multi-Session artifact purge during session retirement (O(M×N) guard scans) #4038 / fix(storage): batch retired Session artifact cleanup #4984.
- Accept the Storage/protocol portion of Usage bounded reads through fix(runtime-host): serve one revision-consistent Usage snapshot #4058 / docs(usage): design revision-consistent screen reads #5023, including the All-range scenario in bug(desktop): Settings Usage can hang after selecting the All range #5019. Keep the unresolved design decisions in that work rather than preselecting them here.
Already changed; do not reopen from the old inventory
- Scheduled-task point operations no longer rewrite the full catalog: perf(storage): scheduled-task point operations rewrite the full catalog #4954 / perf(storage): avoid scheduled-task catalog rewrites #4955.
- Host Ready is followed by bounded background context-offload GC and maintenance: fix(runtime-host): defer bounded storage maintenance until ready #4963. The old statement that GC is reached only through retirement/copy disposal is no longer current.
- Transcript query and navigation changes landed through refactor(runtime): derive Session transcripts from RuntimeEvents #4879 and subsequent fixes. Old findings and counts in [DISCUSS] Storage and protocol: four published rules, each enforced in exactly one path #4876 require current-source verification before becoming new work.
Deferred questions
- Owner-lock/control-directory cleanup requires proof that removal preserves mutual exclusion; coordinate with fix(runtime-host): reap stale Runtime Host control directories #4712. Do not treat unlinking lock files as an ordinary cleanup optimization.
- Usage retention after Session deletion is a product-policy decision, not permission to delete historical records as part of a performance fix.
- Other tables without retirement paths are not automatically implementation tasks. Add work only when growth or an operational obligation is established.
- A repository-wide CI ratchet or mandatory exception ledger is not a prerequisite for the first fix and is not approved by this tracker.
Acceptance
For each delivered path:
- Name the real producer, authority, and downstream consumer. Measure through that path rather than only benchmarking a helper.
- Compare the same workload on explicit before/after commits. Vary the relevant dimension: page size, target history, unrelated records, retained output, or retired Session count. Include a cold/warm distinction where relevant.
- Report applicable rows scanned/decoded, serialization work, retained memory, write/WAL bytes, and elapsed time. For timing comparisons, use repeated runs and report median/p95; distinguish synthetic measurements from production observations.
- Preserve UTF-8 byte budgets, completeness/cursor semantics, revision consistency, atomic durable facts, and retry/restart behavior relevant to the changed path. Retain focused behavioral tests that fail on the replaced behavior.
- Do not accept moving a full scan from reads to every write, materializing everything behind a paginated API, or adding a second durable authority as a reduction in amplification.
Completion means each delivery item has a verified result or a documented, evidence-backed scope decision. It does not mean every read is constant-time, every historical row is deleted, or the separate user-experience budgets in #4677 have been met.
AI assistance: Codex helped inspect current source and draft this tracker under maintainer direction.
Activity
chinawch007 commentedon Sep 8, 2026
I’d like to take on the first delivery checklist item: encoding and page-assembly optimization.
My initial scope is the five page-building paths identified here: Memory entries, Artifact pages, Plan pages, Session catalog pages, and Runtime resource pages. I’ll verify these against current
mainand check for overlapping work before making changes.My proposed approach is:
Trace the existing paths and establish a baseline.
Follow page construction through protocol validation, outbound encoding, transport, and the downstream consumer. Identify repeated serialization and array copying, and measure the work performed by the actual request paths rather than only benchmarking a helper.
Replace repeated candidate-page serialization with incremental byte accounting.
Evaluate a shared implementation that measures normalized items once and accounts for the page envelope, separators, and changing cursor fields. Reuse encoding results or byte measurements where they describe the same representation, through the existing protocol interfaces and
EncodedProtocolMessageseam.Apply the change consistently and remove superseded implementations.
Cover the identified page builders in one PR unless a concrete dependency blocks part of the work. The PR will explicitly document the paths covered and remove the implementations it replaces.
Verify behavior and attach reproducible performance evidence.
Add focused tests for UTF-8 and JSON escaping, exact byte boundaries, oversized items, empty/final pages, and cursor transitions. Check pagination completeness and revision consistency. Compare explicit before/after commits under the same workloads, varying page size and item size, and report serialization work, memory, and repeated-run median/p95 timings, with cold/warm distinctions where relevant.
The key constraints I’ll preserve are the existing count/byte limits and validation behavior. Raw frame bytes, normalized result values, and nested-object budgets will remain distinct; reusing an encoding measurement must not bypass a different validation boundary. Performance claims will be limited to the measured paths.
liuxiaocs7 commentedon Sep 8, 2026
Thanks @Astro-Han for pulling these performance points together into a well-scoped tracker — the clear boundaries around scope, the acceptance criteria, and the "already changed; do not reopen" section make this a genuinely useful read.
I'd like to pick up the second checklist item: Shell output persistence measurement. I'll confirm the paths against current
mainfirst.As the tracker frames it, this is a measure-first task, not a predetermined representation change. My plan follows the Acceptance criteria:
1. Path (producer → authority → consumer).
ShellRunManager.queuePersist— takes a full output snapshot, deep-compares the candidate record, and on any diff callsupdateShellRunwith the completeoutput.SqliteShellRunStore.updateShellRun— reads the current record, merges, andJSON.stringifys the wholenextrecord into therecord_jsoncolumn (one atomicUPDATE).readShellRun/listSessionShellRunson restart, plus the live shell-run views. Recovery reconstructs the retained tail and truncation flags from that single blob.2. What I expect to find, and want to quantify. The retained output is already bounded (
BASH_MAX_RETAINED_CHARS, ~1MB/stream), so per-flush cost is bounded. The amplification is in the flush count: with a ~1s / 64KB flush cadence, a long-running command that produces far more than the retained cap rewrites the full (capped) record on every flush. So cumulative write/WAL work scales roughly as(total_produced_output / flush_bytes) × retained_record_size, even though only a tail is ever kept. I want to measure whether that is material at representative sizes rather than assume it.3. Measurement. Same-workload before/after on explicit commits, varying:
Reporting per-flush
JSON.stringifybytes,isDeepStrictEqualcost, SQLite/WAL bytes written, retained memory, and repeated-run median/p95 elapsed, with a cold/warm distinction.4. Deliverable. Per the checklist, one of: (a) a justified follow-up with an explicit recovery contract — preserving the atomic durable fact, exact reconstruction of the retained tail and truncation flags, and retry/restart behavior — or (b) an explicit, evidence-backed decision that the bounded cost is acceptable. I will not move a full scan onto every write, add a second durable authority, or weaken atomicity/recovery as a "reduction."
I'll keep performance claims limited to the measured paths. Happy to align if a maintainer prefers I fold this into existing shell-run work instead.
liuxiaocs7 commentedon Sep 8, 2026
Shell output persistence baseline
I measured the current Shell persistence path before selecting a representation change.
Scope and environment
9cb5cc93c03f8d07550e739164d5e33168892563v24.14.0SqliteShellRunStore.updateShellRun()path with the operationalruntime.sqliteschema, WAL mode, andsynchronous=FULL.ShellRunProcessManager -> ShellRunStore -> SQLitepath with real child processes and the default 1-second / 64-KiB flush policy.Isolated Store results
The amplification ratios compare the sum of complete encoded
ShellRunRecordsizes, or WAL growth, with the amount of newly changed output.Metadata-only updates still process the complete output-bearing record:
End-to-end Runtime path
For the saturated-tail workload, the Store update p50 was 4.38 ms and p95 was 6.90 ms. Approximately 16 KiB of output arrived after saturation, while the persistence path processed about 6 MiB of complete records and produced about 6 MiB of WAL traffic.
Interpretation
The amplification is real but bounded by the existing retained-output limits and flush coalescing:
observedAtalso retain the full JSON processing cost because output and lifecycle metadata share onerecord_json.This is a local synthetic Storage/Runtime measurement, not a production latency claim. Disabling auto-checkpointing makes cumulative WAL writes visible; the numbers should not be interpreted as steady-state WAL file size.
The results justify a follow-up, particularly around separating small lifecycle metadata updates from the large output payload and reducing saturated-tail rewrites. They do not yet demonstrate that a more complex append-log or checkpoint-plus-delta representation is necessary.
liuxiaocs7 commentedon Sep 9, 2026
Proposed Shell output persistence plan
The measurements support treating two costs separately:
The first problem can be addressed without changing flush behavior or recovery semantics. Neither a two-column nor a two-table split eliminates the main saturated-tail checkpoint cost when output actually changes. Changing automatic flush behavior requires an explicit recovery-contract decision.
Invariants
ShellRunStoreremains the sole ShellRun state-machine authority;nextShellRunRecord()retains the transition, revision, no-op, and terminal-outcome rules.observedAtremains terminal-only and first-write-only.New evidence: column isolation is not page isolation
A scoped diagnostic used Node v24.14.0 / SQLite 3.51.2, 4 KiB pages, WAL, and
synchronous=FULL. Each case used a fresh database with the composite ShellRun primary key and Session ordering index, retained 1 MiB of stdout, and kept output unchanged. Setup WAL was checkpointed/truncated before one metadata-only transaction. Automatic checkpointing was disabled only to make WAL-frame accounting visible.The comparison covered combined
record_json, same-row split columns in both orders, and separate metadata/output tables. It used both repeated-character and deterministic varied ASCII output. All 32 combinations were repeated in a fresh process/directory with matching reported results.observedAton a completed run (+27 bytes)Both output patterns and both split-column orders produced the same WAL totals. The large cases had 260 WAL frames, including 257 overflow-page frames with changed page images. Separate-table metadata updates touched no pages belonging to the output table. Output equality and
PRAGMA integrity_checkpassed in every case.These updates assigned
started_atas well as the changed JSON column, matching the current Store's SQL; the small total includes an additional ordering-index frame. WAL bytes are not total filesystem/device write amplification.The counterexample is the important result: a metadata-length change can rebuild the large SQLite record and rewrite its overflow chain even without assigning
output_json. This is a physical-layout diagnostic, not an end-to-end CPU/latency benchmark, a production speedup claim, or sufficient evidence to select a production schema.Phase 1: isolate metadata/output work, then choose the physical layout
This phase addresses metadata/output coupling only. Select the layout before committing to a schema migration.
Layout alternatives
metadata_jsoncontains ShellRun identity, command, lifecycle state, timestamps, revision, and sandbox fields.output_jsoncontains onlyPipeShellOutputorPtyShellOutput.started_atremains the scalar projection for Session ordering.metadata_json+output_jsonI retract the earlier statement that a second table provides no relevant benefit. Two tables do not weaken SQLite transaction atomicity; they add invariants the adapter must enforce.
If the scoped objective is reduced JavaScript encoding work, same-row columns remain a candidate. If it includes preventing metadata-only mutations from rewriting the large output record, separate tables should be evaluated directly. Do not choose solely from the micro-diagnostic: compare both through the real Store/Manager paths with representative workloads.
Interface and ownership
Keep the existing complete-record
ShellRunStoreinterface:The SQLite adapter owns the physical split, reconstruction, transactions, and migration. Runtime should not learn about the layout or duplicate the state machine. An internal Storage codec should be shared by migration and normal reads/writes.
Within the existing write transaction:
nextShellRunRecord(current, patch).For two tables, complete-record reads must use one joined statement or an explicit read transaction so they cannot mix metadata from one commit with output from another. Missing/inconsistent rows must be rejected rather than silently reconstructed.
Keeping the complete-record return type means metadata-only updates still read/parse output in this design. Splitting the schema also does not automatically remove the existing equality checks; unchanged strings have fast paths, so a full MiB scan on every metadata mutation should not be assumed. Measure the remaining work rather than claiming output CPU cost is eliminated. Removing the remaining parse is a separate interface/ownership decision.
Migration
Only after selecting and validating the layout:
SQLITE_CORE_EXECUTION_SCHEMA_VERSIONto the next version; current inspected schema is v9, so v9 → v10 if no intervening migration lands.record_json, then encode both parts using the production codec.core_shell_runs_session_order, update the operational schema registry, and requireassertCurrentOperationalTargetSchema()to accept the exact final shape.Report representative existing-row count, migration elapsed time, peak temporary disk use, and DB/WAL growth.
Phase 1 acceptance and measurements
Behavioral coverage should include:
observedAt.Performance comparisons must identify before/after commits and include 1 MiB and 2 MiB output with:
Measure JavaScript encoding/decoding work separately from SQL assignments and physical WAL/page writes; report transaction median/p95, CPU, and applicable allocation/memory metrics. Use the default checkpoint configuration for representative runs; disabled-checkpoint runs are a separate accounting diagnostic. Include realistic table sizes and mutation mixes, not only repeated equal-length timestamps.
A test showing that
UPDATEomitsoutput_jsonis not evidence that output pages were not written.Decision gate: specify recovery requirements before changing flush behavior
Maintainer question:
Until answered, preserve the existing automatic flush behavior and defaults:
Two implementation details matter:
data.lengthinpendingFlushChars(JavaScript string code units), not UTF-8 bytes.scheduleAutomaticFlush()also returns early when a timer or automatic flush is already pending. It is therefore not an unconditional “persist immediately at 64 KiB” contract.Do not silently change those semantics inside the storage-layout PR.
Live Read/inspect already goes through
persistObservation(live): it cancels a pending timer and persists a current snapshot cut. Preserve and strengthen tests for this path, along with stop, finalization, foreground return, normal shutdown, and PTY operations requiring a durable cut.If a looser checkpoint/recovery target is explicitly accepted
Evaluate adaptive full-checkpoint coalescing before introducing a new log format:
A timer schedules work; it does not guarantee that a commit completes within that age under overload or I/O failure. A strict time/byte loss bound would need explicit enforcement and failure/backpressure behavior, not just a larger timer.
Recovery must remain “the last committed checkpoint after abrupt Host loss.” For normal paths, specify the admitted-output snapshot cut that must be committed before successful return.
Tests should cover threshold crossing while a timer exists, Unicode/unit semantics, oldest-pending age, delayed/in-flight writes, output arriving during persistence, Read replacing a timer, final atomic settlement, persistence failure, and restart from the last committed checkpoint.
If existing cadence must be retained, or a strict loss bound is required
Do not infer a strict one-second guarantee from the current implementation, and do not weaken the agreed contract just by increasing a timer.
Extend real-path measurements before deciding whether complete checkpoints are acceptable or need a different representation:
runtime.sqlite.The earlier short baseline does not establish acceptable cost for long-running or concurrent ShellRuns. Its approximately 6 MiB manager trace included the initial fill checkpoint and final observation; it should not all be attributed to the subsequent small increments. The bounded tail limits snapshot size, not cumulative writes over the run's lifetime.
If measured interference is acceptable, an evidence-backed scope decision remains a valid deliverable. If it is unacceptable and permitted coalescing is insufficient, consider pipes-only checkpoint plus bounded deltas. That design needs explicit recovery/compaction rules for stdout/stderr ordering, retained-tail prefix removal, redaction across chunks, oversized-line safety, atomic revision publication, and interrupted compaction. PTY should remain on full screen checkpoints.
Revised delivery sequence
The guiding rule remains: remove avoidable metadata/output coupling, then let measured interference and the recovery contract determine the next step. SQL column separation must not be presented as guaranteed page isolation, and timer settings must not be presented as hard durability bounds.
perf(runtime-host): budget paginated JSON incrementally
ci(windows): update Skill catalog test count
test(ci): align Skill catalog gate assertions
perf(storage): reuse Usage range statistics across filter changes (#5517
perf(storage): bound Usage page queries and avoid redundant counts
perf(storage): bound Usage page queries and avoid redundant counts (#…
ggbdpq commentedon Sep 28, 2026
Status of delivery checklist item 5 - "Accept the Storage/protocol portion of Usage bounded reads through #4058 / #5023, including the All-range scenario in #5019": every anchor is closed, only the checkbox is waiting.
Anchor chain, all verified closed:
c980b93a3): single read transaction + revision fence + keyset cursor; the wire contract from the closed #5023 design (screen_response_too_largesection/entry/message caps) landed there too, with coverage inusage-screen.test.tsAgainst this tracker's acceptance wording for the item ("measure SQL scan/sort work as well as application decoding and transfer"):
readUsageScreenfacade including row decode) - 50k-record paging median 53.5ms -> 0.8ms, independent of history depth.screen_response_too_largerejection path are tested, so transfer cannot grow unboundedly with history; raw wire bytes were however never recorded as a number (perf(storage): bound Usage page queries and avoid redundant counts #5514 explicitly excluded wire serialization). If the literal number is wanted, extendingscripts/perf/usage-pages.mjsto serializereadUsageScreenresults throughprotocol/codec.tsand report bytes per page/screen is a small addition - happy to do it.Unless the maintainers want that last number, this item looks ready to tick. Source inspection on current main confirms the shape: per-source
ORDER BY ts DESC ... LIMIT 51subqueries merged globally, statistics reuse, cursor trimmed for two-column index seeks; the remaining range-level scans (full statistics, exact filtered counts, sparse substring search) are the explicitly exempted ones.chore(runtime-host): declare the byte-limit consolidation as a protoc…
refactor(runtime-host): consolidate the private byte-limit helpers in…
Astro-Han commentedon Nov 5, 2026
Closing: this targets the TypeScript implementation on
main, which is superseded byrust-preview(#6366). If it still applies torust-preview, please open a new issue against it.