Recovery moved the database aside but left every `.segments/*.json` routing
record in place. Each record names a Session whose row lived in the moved
database, so `list()` found a record without a row and refused with
`SESSION_STORAGE_MISSING` on every later call, permanently: not even a Session
created after the recovery could be listed, and `listStoredHeaders()` failed
with it.
`setAside()` now moves each routing record to `<hash>.json.unreadable-<stamp>`
with the bytes it names, so every record stays readable and none of them counts
as lost state. `list()` reads the directory again after the scan, because the
scan is what triggers recovery; without that the first call would still fail.
The extraction report for a missing database now says the records are kept, so a
restored database reads through them, which is what the code does.
`test: moves the routing records with a damaged database, so listing Sessions
works after recovery` writes a Session, damages the database, and asserts that
`list()` resolves and no `.json` record remains. It fails with
`SESSION_STORAGE_MISSING` when the two source files are reverted.
Also from the same review:
- `standIn`'s comment states that `time` resets per Segment, so a damaged first
frame reports the epoch.
- README documents `codec` 255 rows and the `session_segments` internal view.
- An unused `plan` helper is gone from the schema fixture.
A large `data` value ends mid-page, leaving the rest of its last page unused.
At 4 KiB that slack is 12.8% of a 370 MB corpus store; a 16 KiB page cuts it to
12.2% and the file to 362 MB from 366 MB, without changing any row, index, or
query. Tail reads and the flagship analytical query measure the same or slightly
faster. The pragma precedes WAL, which fixes the page size at the first write.
Small stores pay a little: the same 2,000-event session is 576 KB rather than
536 KB, because each page holds more slack. That is 40 KB against 4 MB saved on
the corpus.
README records the measured size trade and why per-event compression, not the
row layout, makes the store larger than frames: recompressing the same events in
groups of 64 reaches 183.8 MB against the frame layout's 186.7 MB, but a point
read would then decode its whole group, 19x slower for the reads a live Session
makes.
A lock is a live writer, not damage. SQLite holds its locks as operating-system
locks that the kernel releases when a process exits, so a lock that outlives the
busy timeout belongs to a process that is still inside it. Replacing its file
does not stop that writer: it keeps appending to the moved bytes while the new
database starts empty, splitting one history across two files.
Windows made the inconsistency visible: it refuses to move a file another handle
holds open, so the replacement could never work there, and the tests had to
assert different outcomes per platform. The rule is now uniform and simpler.
- `recovery: replace` keeps its meaning for damage only: a database this build
cannot read moves to `<name>.unreadable-<timestamp>` and an empty one takes
its place, so every byte survives and Sessions stay available.
- A lock always fails with `SESSION_STORAGE_LOCKED` after the busy timeout, on
every platform, and the database is left where it is.
- A damaged file whose move fails is never replaced either: returning false
reports the storage fault instead of discarding the only copy of the bytes.
- `ReplaceReason` and the `locked` tag are gone; only damage reaches the tag.
This matches SQLite's own SQLITE_BUSY contract, LevelDB's LOCK behaviour, and
Chrome's singleton lock handling, which reports an owner it cannot prove dead
rather than breaking a live one. README, upgrade guide, and the decision record
state the rule in both languages.
When the move aside fails, the recovery rethrew the internal replacement tag
instead of the error the caller understands. A Windows open whose file a live
writer holds open therefore surfaced `ReplaceDatabase` rather than
`SESSION_STORAGE_LOCKED`.
The tag is unwrapped before it leaves the store, and the guarded path is marked
platform-conditional: POSIX moves a locked file, so a refused move happens only
on Windows under a live writer.
The Windows lock test expected the database to be moved aside, which Windows
refuses while a live writer holds the file. The open correctly reports the lock
and leaves the file in place, so the test now asserts that: no moved file, no
replacement report, and a `SESSION_STORAGE_LOCKED` failure. POSIX keeps the
move-and-replace assertion.
The move-failure handler is marked as platform-conditional: an absent journal
moves without error, and POSIX renames a file another handle holds open, so only
Windows under a live writer reaches it.
A live writer on Windows holds the database file open, so the rename that
moves a locked database aside fails. The failure escaped the recovery instead
of reporting the lock, which failed the Windows coverage job.
A failed move now reports the same lock outcome the caller already handles, so
the database stays in place rather than disappearing behind an unhandled error.
The Windows lock test asserts the platform's real behaviour: no moved file, and
a reported lock instead of a replacement.
Test-only assertions for the derived-object recovery could not run on Windows
for the same reason and are unchanged.
Close the six review findings against the event-row store, add provisioned
recovery, and make the derived tables' indexes actually reachable.
Data carried over from the frame layout:
- Carry over the readable prefix of a frame recorded longer than its lines.
The frame layout served whatever prefix a read asked for, so only a sequence
with no readable line gets a row no reader decodes.
- Drop lines past a frame's recorded range: the frame layout never read them,
so reporting them as damage would fail a read that used to succeed.
- Repeat the nearest readable event's `time` in the stand-in row instead of 0,
so `session_summary.last_event_time` stays a real instant.
- Tolerate an absent version 1 trigger or index. A build that narrowed the
frame layout dropped some, and losing a trigger costs no stored event.
- Refuse a child Segment that does not start where its parent ends instead of
giving it a history the frame layout rejected.
- Set aside a frame whose Segment row is absent, which the version 1 foreign
key never checked.
Derived tables:
- Compare every declared object (table, session view, indexes, further views)
so a dropped view or index is rebuilt rather than silently missing forever.
- Analyze once when no statistics exist and `PRAGMA optimize` on close. Without
statistics SQLite scanned every result in the Segment per tool call:
`session_tools` took 2.3 s on 84,000 tool calls against 22 ms analyzed.
Recovery, new `recovery` setting defaulting to `replace`:
- An absent database becomes a new empty one.
- A lock waits the busy timeout, then the file moves to
`<name>.locked-<timestamp>` and a new empty database takes its place.
- An unreadable file moves to `<name>.unreadable-<timestamp>` the same way.
- `report` keeps the previous refusal for a storage root another process
may write. A newer schema version is never replaced under either mode.
Documentation records the recovery setting, the raw-state damage behavior, the
compression limit on JSON queries, and the statistics step. 488 tests with full
coverage on the package sources.
The schema and every static statement of the SQLite Session store were
string literals in TypeScript, and the upgrade step from the frame layout
executed whatever the current schema constant held. They now live under
resources/sql: schema/vN.sql is the whole schema of one version and is
not edited once released, upgrade/A-to-B holds the statements of one
upgrade step, and store/ and derived/ hold the statements of the store
and of the derived-table runtime. src/sql.ts is their only reader.
Two internal views, segment_extents and session_heads, replace the SQL
fragments the store shared by string interpolation. Transaction control,
connection pragmas and the DDL generated from a derivation stay inline.
The upgrade from the frame layout replaced a whole frame when one of its
lines was unreadable, so a read that stopped before the damaged event
failed after the upgrade although it succeeded before. A frame that
splits into its recorded lines is now carried over event by event, and
only an unreadable event gets a stand-in row.
Drop the two indexes on sessions that no statement or documented query
uses, and state the cross-build limitation of derived tables exactly.
The opt-in SQLite Session store kept each durable write as one compressed
frame, so SQL could not see an event's sequence, type or time. It now
stores one row per event: the envelope members are columns and data is
JSON text, or one Zstandard frame when it is large. Segments use integer
ids and a segment_paths table that lists each Segment's history, so the
session_* views return a Session's events in one join, forks included.
Derived tables for model calls, tool calls, tool results and compactions
are written in the events' transaction and rebuilt from events when a
table is missing, its version changes, or its derivation was absent.
Opening a database runs ordered upgrade steps under src/migrations. The
first rewrites the frame layout (schema version 1) in place; a frame it
cannot read is set aside without blocking the other Sessions.
BREAKING CHANGE: the frameEvents setting is removed, and a database
upgraded to schema version 2 cannot be opened by earlier releases.
/side forks now record origin: 'side' in the child Session header. The
left Sidebar hides side-origin Sessions as it hides subagent children.
The V4 codec admits the side origin without changing the frozen V2
header codec; the persistence acknowledgement records the same-version
decision.
Co-authored-by: Dudu-0223 <290591114+Dudu-0223@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): merge short SQLite frames inside the append transaction
Live writes store one to three events per frame, so compression barely
works. When the newest short frames of a Segment reach frameEvents events,
the append transaction re-encodes them as full frames. The frames_no_delete
trigger is dropped from the unreleased schema and from existing databases.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): read SQLite frame payloads only for a merge
Scan only frame ranges to decide whether the trailing short frames merge,
then read their payloads. Append decoded lines one by one so a large
frame size cannot exceed the argument limit.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): cap SQLite frame merges by decoded bytes
A merge skips a run of short frames whose stored or decoded text exceeds
4 MiB, bounding how long it holds the event loop and the write lock. Tests
cover merged compression, the live event path, a failure after the merge's
delete, and large events; a seeded synthetic diagnostic measures size and
append cost. Documentation drops the one-frame-per-write wording and lists
the write stop after short-frame corruption.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): store short SQLite frames uncompressed until merged
A short frame below min(64 KiB, 2 MiB / frameEvents) of JSON text is stored
as text; the merge compresses it together with its neighbours. This skips a
compression on every live append that the merge would redo, and keeps any run
of such frames within the 4 MiB merge limit.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): seal short SQLite frames when a writer closes
* test(session): assert the reported seal failure without an untyped matcher
---------
Co-authored-by: Turtle <turtle1999@deepseek.com>
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
Co-authored-by: Magolor <magolor@qq.com>
Each appended batch queues for the next group commit; the yield before a
group lets batches other writers append in the same turn share one
transaction, so a checkpoint costs one commit and one fsync per group
instead of per writer, and the synchronous transaction is bounded by an
event cap. A batch failing on its own terms rolls back to its savepoint
and rejects alone; an error that ends the transaction rejects the group.
A writer that checkpoints step after step runs its whole append path on
settled promises and a synchronous transaction, so the process never
returns to the I/O phase: timers, other writers waiting on a lease, and
the UI starve until the writer stops. Yielding once per commit bounds
that stall to one commit.
The SQLite plugin validates its own Config: the JSONL fields plus
frameEvents, the maximum events per new frame, defaulting to 64. Imported
histories reach the cap; larger frames compress a few percent better and cost
proportionally more to decode for a tail read.
The plugin's compression setting now also selects the physical encoding of
new frames: zstd compresses a frame when that shrinks it, none stores the
text. Stored frames decode by their own codec. A read decodes eight frames
at a time on the thread pool and yields between groups.
Each durable write stores one frame of JSON lines, Zstandard-compressed when
that is smaller than the UTF-8 text, in a rowid table keyed by Segment and
start sequence; the Segment event count is the last frame's end. Reads select
the frames overlapping the requested range and decode their slices, yielding
between frames. The schema version advances to 2; a version 1 database is
refused as before.
* test(session): cover SQLite persistence and document the provider
* test(session): align coverage with the latest SQLite implementation
* test(session): adapt storage coverage to the current SQLite backend
* feat(session)!: pass fork source through agent creation
* refactor: prepare forks privately and append child segment events
* refactor: choose fork sharing in SQLite creation transaction
* fix(session): preserve caller-prepared fork seeds
* feat(session): flush fixed fork prefix before child creation
* fix(session): persist fork sources and await parent drain
* chore: remove test and documentation changes from fork PR
* refactor(agent-loop): reuse agent fork source type
* fix(session): retain SQLite handle and JSONL errors after rebase
* perf(session): create forks from the caller's history without reloading the parent
The fork source carries the complete child history from seq 0. A live
parent's log supplies the shared prefix; a cold parent's prefix is used as
persistence returned it to the caller. The factory no longer reopens the
parent, and the JSONL backend copies the supplied history instead of
decoding the parent log again. The SQLite backend drains a live parent
writer before sharing its persisted prefix, so the factory no longer flushes
the parent or tracks owner disposal during that wait; its fork creation
serializes child events without the read-side validation and reports
publication failures through the shared wrapper.
* refactor(session-query): report the persisted prefix length on live observations
A live observation reports its event count as the persisted prefix, so the
fork command's boundary fallback only covers observations from other
producers.
* test(session): exclude the SQLite POSIX lease from Windows coverage
The SQLite copy of the session write lease executes its POSIX face only off
Windows, matching the JSONL exclusion.
* test(session): report legacy opener failures on stderr
The two-process suite asserts only the error name; the message and cause now
reach the inherited stderr so a CI failure identifies the SQLite error.
* refactor(agent): keep seed as the constructor input and narrow the fork source
CreateAgentOptions.seed stays the only constructor history; source names the
parent and cut a seeded fork shares. The factory stores the constructed log
with that source at creation, so no fork-only seed selection remains in the
loop.
* test(session): complete fork regressions and documentation
* test(session): propagate current SQLite fixtures through fork regressions
* test(session): describe fork creation from the caller's history
The fork source now carries the complete child history and the factory no
longer reopens or flushes the parent, so the fake factories, source
expectations, and cancellation cases follow that flow: a sharing backend
drains the parent writer itself, JSONL copies the supplied history, and
observations always report the persisted prefix. Documentation, the upgrade
guide, and the generated catalogs describe the same behavior.
* test(session): cover fork creation without a factory flush
The in-process fork provider's cases no longer wait for a parent flush: the
live log supplies the completed prefix and cancellation is exercised while
child storage is pending. The Remote fork command's boundary fallback is
covered by an observation that omits its persisted count.
* test(session): drop redundant observation assertions in the fork fallback case
* test(session): describe fork creation with seed beside a parent source
The agent factory keeps seed as the constructor history and source names
only the parent and cut, so the fakes, source expectations, and documentation
follow that split; the case where a live parent replaced the supplied prefix
no longer applies.
* refactor(session): name the fork parent option parentSource
`CreateAgentOptions.source` and `SessionPersistenceCreateOptions.source`
become `parentSource`: the field names the parent Session a seeded fork
shares its prefix with, and the shorter name read as a generic origin.
* refactor(session-query): report persistedEventCount on cold observations only
A live observation holds the Session's own events, none of them read-time
repairs, so its stored prefix is its whole log and the field said nothing;
only a cold read appends interrupted-turn closers in memory and needs to
tell the fork cut where the stored prefix ends.
One ENOENT helper, one routing-database check owned by the store, one
routing-record reader that validates identity, and one publication failure
wrapper replace the copies spread across the store and the service.
Fork creation lands with its own creation flow; the pending-create fork
record, handle cut offsets, and seed marker checks that flow would replace
are removed. The Segment schema stays, and cut() locates a fork attachment
through the segment_ancestors index instead of walking the parent chain.
The new schema starts at version 1, and the busy timeout and live batching
limits are named constants.
Write paths serialize already-typed in-process events without re-running the
read-side envelope validation. Listing checks routing records by their hashed
file names instead of reading each one and scans SQLite concurrently with the
JSONL listing. Reads decode long histories in yielding chunks. Create checks
only the retained JSONL identity before SQLite's own existence check, and a
queued legacy open no longer repeats the routing check its caller just made.
- document the exported SqliteStore prefix/suffix loaders (verify-export-jsdoc)
- share createStoredEventRead from session-persistence so the standalone
SQLite store stops duplicating the service helper (duplication gate)
- route replaceStored header upserts through writeRow (duplication gate)
- move replacement/conflict test SQL into closed test resources so the
SQLite SQL resource boundary test passes