Commit Graph
32 Commits
Author SHA1 Message Date
Magolor 9d2a72ff0f feat(session): archive idle SQLite Sessions and add on-demand store compaction (#9362)
* feat(session): archive idle SQLite Sessions and add on-demand store compaction

* fix(session): preserve derived views on v2-to-v3 upgrade and harden cold restore races

* feat(session): default coldAfterDays to 30 and skip set-aside unreadable segments

* fix(session): clear cancelled warm entries and recheck cold state under write lease

* refactor(session): keep compactStorage internal to dsh-session-persistence-sqlite
2026-11-27 10:43:52 +00:00
Magolor 870c1d5c7e fix(session): list Sessions again after a damaged database is recovered
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.
2026-11-26 14:44:53 +08:00
Magolor 295666619f perf(session): use 16 KiB pages to reduce the padding around large values
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.
2026-11-26 14:22:03 +08:00
Magolor febabea5cf refactor(session)!: report a locked database on every platform instead of replacing it
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.
2026-11-26 13:35:24 +08:00
Magolor f2ab8c2f7b fix(session): report why a database could not be moved aside, never the internal tag
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.
2026-11-26 13:01:58 +08:00
Magolor 555d242441 fix(session): assert each platform's real behaviour when a locked database cannot move
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.
2026-11-26 12:42:30 +08:00
Magolor 354e9ae8f5 fix(session): keep a locked database in place when Windows refuses to move 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.
2026-11-26 12:19:30 +08:00
Magolor 0e56ff698b fix(session): recover an unusable database, keep planner statistics, and carry over damaged frames
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.
2026-11-26 11:52:53 +08:00
Magolor 6da7ed3f6e refactor(session): keep the SQLite store's SQL in versioned .sql resources
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.
2026-11-25 18:47:26 +08:00
Magolor cbc6457226 feat(session)!: store SQLite events as rows with derived tables
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.
2026-11-25 17:23:45 +08:00
6fd18391a2 revert: merge short SQLite frames inside the append transaction (#8674)
This reverts merge commit 0a25695c87697f04af906a01e4c259048937d421.

Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
2026-11-25 12:58:09 +08:00
07ad3a4dc5 perf(session): merge short SQLite frames inside the append transaction (#8674)
* 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>
2026-11-23 18:09:42 +08:00
liukx0205 9340e56c4a perf(session): commit concurrent SQLite batches as one group
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.
2026-11-18 15:20:49 +08:00
liukx0205 55e96102ec fix(session): yield the event loop after each SQLite commit
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.
2026-11-18 03:43:28 +08:00
liukx0205 64c574c0e2 feat(session): make the SQLite frame size a plugin setting
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.
2026-11-17 18:00:51 +08:00
liukx0205 cc93a902a0 perf(session): select SQLite frame compression by config and decode frames concurrently
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.
2026-11-17 18:00:51 +08:00
liukx0205 ac2e505c35 chore(session): keep the SQLite schema version at 1 for the unreleased store 2026-11-17 18:00:51 +08:00
liukx0205 ddd1850920 perf(session): store SQLite events as compressed frames
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.
2026-11-17 18:00:51 +08:00
Kexin Liu e50e24de40 feat(session): 等父前缀持久化后创建共享 fork (#8392)
* 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.
2026-11-17 17:28:59 +08:00
Dudu-0223 7b1553c31f fix(session): retry contended SQLite WAL initialization 2026-11-17 16:13:30 +08:00
liukx0205 2839c3532c refactor(session): name SQLite persistence classes after their roles
SqliteSessionPersistence, SqliteStore, and SqliteSessionHandle mirror the
JSONL backend's class names; Trace and Segment stay storage-internal terms.
2026-11-15 01:42:35 +08:00
liukx0205 ed2b030a84 refactor(session): share SQLite routing checks and record validation
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.
2026-11-15 01:42:35 +08:00
liukx0205 92d1100c24 refactor(session): keep SQLite Segment storage without pending-fork wiring
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.
2026-11-15 01:42:35 +08:00
liukx0205 16180383ca perf(session): trim SQLite write validation, listing reads, and open prechecks
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.
2026-11-15 01:42:34 +08:00
liukx0205 0d13ccf03b perf(session): reduce SQLite persistence overhead 2026-11-15 01:42:34 +08:00
liukx0205 4bd6b6882e refactor(session): trim persistence internals 2026-11-15 01:42:34 +08:00
liukx0205 86ecc66742 fix(session): enable WAL before publishing SQLite schema 2026-11-15 01:42:16 +08:00
liukx0205 7ecfef7473 fix(session): repair SQLite CI fixtures and failure coverage 2026-11-15 01:41:28 +08:00
liukx0205 f798414231 fix(session): coordinate legacy reads and retain closing live events 2026-11-15 01:38:51 +08:00
liukx0205 75b3dbc9d8 fix(session): retain JSONL internals and remove SQLite plugin settings 2026-11-15 01:38:51 +08:00
liukx0205 d67adbfac7 refactor(session): keep SQLite private and simplify initialization 2026-11-15 01:38:51 +08:00
liukx0205 a3c870e3e4 feat(session)!: use SQLite and import legacy JSONL on open 2026-11-15 01:38:51 +08:00