DSH / Atlas
2026-11-25implementedarchitecture

SQLite event rows with derived tables

SQLite 事件行与派生表

The opt-in SQLite Session store kept each durable write as one frame: the batch's events as JSON lines, Zstandard-compressed, keyed by Segment and start sequence. A frame carries no per-event sequence, type, or time, so SQL cannot filter, count, or aggregate events; counting events by type means decoding every frame. Frames compress well only when they hold many events, and live writes carry a few, so matching JSONL'

English

Problem

The opt-in SQLite Session store kept each durable write as one frame: the batch's events as JSON lines, Zstandard-compressed, keyed by Segment and start sequence. A frame carries no per-event sequence, type, or time, so SQL cannot filter, count, or aggregate events; counting events by type means decoding every frame. Frames compress well only when they hold many events, and live writes carry a few, so matching JSONL's size needed a second step that merged short frames after the fact. That step rewrote stored rows, cost write latency, and was reverted.

Session listing, search, and statistics all read whole logs today. A store that already holds every event in a database should answer questions about events, token usage, tool calls, and compactions without a full read, and a forked Session's shared history must not make those answers wrong.

Decision

@deepseek-ai/dsh-session-persistence-sqlite stores one row per event. The envelope members are columns: seq, type, time, surface_op, source_seqs, ignorable. Inline data is JSON text, or one Zstandard frame when its text is at least 1,024 characters and compression shrinks it; codec names which. The event and its envelope are immutable; the cold tier can move its payload without changing the event row's identity.

seq is the Session sequence. A Segment's base_seq is its first sequence and therefore the cut in its parent. segment_paths holds, for each Segment, itself and every ancestor with the exclusive sequence up to which that member's events belong to its history. A trigger fills it when a Segment is inserted. The session_* views join Sessions to events through it, so SQL written against a Session never handles Segments.

Derived tables hold facts read out of events: llm_calls, tool_calls, tool_results, compactions. A Derivation declares one table, a version, the event types it reads, and a pure function from an event to a row. The store owns the key (segment_id, seq), the per-Session view, and rebuilding. Rows are written in the events' transaction. No counter is stored on a Session: totals are sums through the views, so a fork that shares a prefix needs no copy and no correction. A table whose version changes, or whose derivation was absent for a while, is refilled from events through a cursor in derivations. Events are the only authority.

Opening a database runs the ordered upgrade steps in src/migrations/, one per schema version, inside the transaction that opens it. The step from version 1 is the only code that reads the frame layout. It rewrites the same file: the database is one artifact for every Session, so it has no per-Session generation to keep beside a successor, and the transaction leaves either the old layout or the new one.

Measurements

Eighty real Sessions (84,456 events, 408.6 MB of event JSON) were replayed through the provider in batches of the size live writes had: one batch per 200 ms of event time, 12,692 commits. The machine was an Apple Silicon laptop running macOS and Node 24.21.0 with other work in progress; latencies are medians of five alternating runs, and sizes are of a checkpointed database.

StoreSize
Zstandard JSONL105.8 MB
Frames, at the 6.65 events per frame live writes produced109.7 MB
Event rows with derived tables157.6 MB
Event rows without compression442.4 MB
One uncompressed JSON text per event487.5 MB

The events table is 96.5% of the row store, its two indexes 2.4%, and everything derived 1.1%. A full read of the largest Session takes the same time as with frames; the last 50 events take 0.35 ms against 1.05 ms; counting events by type across the store takes 10 ms against 1,278 ms. Per-Session token totals, tool counts, and compaction totals each answer in about 1 ms or less.

With one writer, an append plus flush has a median of 0.190 ms without derived tables and 0.226 ms with them. Deriving costs 0.10 µs of CPU per event; the added time is write volume, because each derived table touched by a commit dirties one more 4 KB page.

Alternatives considered

  • Keep frames and merge short ones. Rejected. It recovers JSONL's size but keeps events opaque to SQL, rewrites stored rows, and the measured merge raised append latency.
  • Plain JSON rows without compression. Rejected. Every byte is readable by any SQLite client, at three times the size.
  • Compress every row, or use a trained dictionary. Rejected for now. A threshold of 256 characters saves 3% and hides another 28% of rows from SQL JSON operators. A dictionary saved about 9% in an estimate, and its bytes would become part of the format; the per-row codec leaves room to add one without rewriting rows.
  • Write derived rows after the commit. Built, measured, and removed. A second transaction per commit is a second synchronization, and the median append rose from 0.75 ms to 0.90 ms with four writers. Batching the deferral further saves little, because rebuilding from stored events costs 11 µs per event to read and decompress them again.
  • SQL triggers or generated columns for derived facts. Rejected. A trigger runs in the same transaction, so it saves nothing, and it cannot read compressed data.
  • One generic derived table. Rejected. It lowers pages written per commit from 14.3 to 12.1, and every query would filter on a kind column and read unnamed slots.
  • Counters on the Session row. Rejected. A fork would have to copy and then correct them, and they would be a second authority beside events.
  • Keep SQL as strings in TypeScript. Rejected. The schema could not be read or diffed per version, and an upgrade step silently followed the current schema constant.
  • Refuse databases of the frame layout. Rejected. Two alpha releases wrote that layout.
  • Write a successor database file instead of rewriting in place. Rejected. It doubles disk use during the upgrade and needs a publication step for the file swap and the routing records that name the database; one transaction gives the same all-or-nothing result, and the upgrade guide asks for a backup.
  • A separate read-model plugin with its own database, like the full-text query provider. Rejected for these facts. It re-reads and decompresses every event the store just wrote, trails the log, and needs its own change detection; rows written beside their events need none of that. Full-text search stays in that separate provider because its index is large and optional.
  • Session projections as the owner of these facts. Not replaced. Projections fold one Session's log in memory and remain the authority for what DSH displays, such as tokenUsage. They cannot answer across Sessions without opening each log, which is the question the tables serve.
  • A service through which other plugins register derivations. Deferred. No plugin needs one yet, and Derivation stays internal until one does.

Consequences

Events, token usage, tool calls, and compactions are queryable with ordinary SQL while DSH runs, per Session and across the store, and tail and point reads no longer decode a frame. The store is 44% larger than frames and 49% larger than JSONL on the measured corpus, and an append is about 0.04 ms slower at the median than without derived tables.

Another SQLite client cannot read data stored with codec 1 without a Zstandard function; every other column, the derived tables, and small events remain readable. Derived tables exist only under this provider, so a consumer that needs their facts under JSONL still folds the log.

The first open of a frame-layout database blocks the process while it rewrites every event, about four seconds per 100 MB, and earlier builds refuse the upgraded file. The file then holds both layouts until freed pages are reused. Damaged frames do not stop the upgrade: a frame's readable events are carried over, an undecodable row stands in for each sequence with no readable line, and the frame's bytes are kept in frames_set_aside, so a read fails afterwards exactly where it failed under frames. A version 1 child Segment that does not start where its parent ends stops the upgrade instead of receiving a history it never had, and a frame whose Segment row is absent is set aside like any other unreadable frame. Each schema version is a file, resources/sql/schema/vN.sql, that is not edited once a release has written it. An upgrade step names the file of the version it writes and keeps its statements under resources/sql/upgrade/A-to-B/, so adding version 3 adds a step module and files and edits none. A test checks that the first step reads only its own files and the version 2 schema, and that the database it leaves has the schema of a new one.

No service lets another plugin register a Derivation, and no setting turns the built-in tables off. Sessions still cannot be deleted, so shared history is never reclaimed.

An open that cannot use the database recovers rather than failing the whole Session service. An absent file becomes a new empty database, and a file this build cannot read is moved aside to <name>.unreadable-<timestamp>, where a new empty database takes its place: every stored byte survives and the Sessions stay available except for the ones the moved file holds. recovery: report keeps the earlier refusal for an operator who repairs storage by hand.

Only damage replaces a file. A lock that outlives the busy timeout is reported as SESSION_STORAGE_LOCKED on every platform, because SQLite holds its locks as operating-system locks that the kernel releases when a process exits: a surviving lock belongs to a live writer, and replacing its file would leave that writer appending to bytes no Session reads while the new database started empty. Windows cannot move a file another handle holds open at all, so a lock there could never be recovered that way; reporting it uniformly is the one rule that holds everywhere. A database whose schema is newer than this build is likewise never replaced, because its bytes are readable and only the release that wrote them can interpret them.

Related

  • JSONL-only first-party Session persistence records why the earlier SQLite provider was removed. This provider returned later as an opt-in package; that note's requirement of an owner, a deployment need, and a format-transition policy applies to it, and the ordered upgrade steps are that policy for the physical schema.
  • SQLite physical chunk-row compression is the removed provider's layout, which packed runs of streamed chunks into one row. Chunks are no longer separate events, so one row per event no longer multiplies rows the way it did then.
  • Handle-based session persistence defines the service this provider implements.

中文

问题

需手动启用的 SQLite Session 存储过去把每次持久写入存为一帧:该批事件以 JSON 行表示,经 Zstandard 压缩,以 Segment 和起始序号为键。帧不携带每个事件的序号、类型或时间,所以 SQL 无法对事件做过滤、计数或聚合;按类型统计事件数就得解码每一帧。帧只有在容纳很多事件时才压缩得好,而实时写入每次只有几个事件,因此要达到 JSONL 的体积,还需要事后合并短帧的第二步。这一步会改写已存的行,增加写入延迟,后来被回退。

如今会话列表、搜索和统计都要读取整份日志。一个已经把每个事件放进数据库的存储,应当不必整份读取就能回答有关事件、token 用量、工具调用和上下文压缩的问题,而且fork 出的 Session 的共享历史不能让这些答案出错。

决策

@deepseek-ai/dsh-session-persistence-sqlite 每个事件存一行。信封成员各占一列:seq、type、time、surface_op、source_seqs、ignorable。内联的 data 是 JSON 文本;当文本不少于 1,024 个字符且压缩后更小时,是单个 Zstandard 帧;codec 标明是哪一种。事件及其信封不可变;冷存储可以移动事件内容,不改变事件行的标识。

seq 是 Session 序号。Segment 的 base_seq 是其第一个序号,因而也是它在父 Segment 中的切点。segment_paths 为每个 Segment 保存它自身和每个祖先,以及一个不含端点的序号上界,该成员中序号小于它的事件属于此 Segment 的历史。插入 Segment 时由触发器填充。session_* 视图通过它把 Session 与事件连接起来,所以针对 Session 编写的 SQL 从不需要处理 Segment。

派生表保存从事件中读出的事实:llm_calls、tool_calls、tool_results、compactions。一个 Derivation 声明一张表、一个版本、它读取的事件类型,以及一个把事件映射为一行的纯函数。存储负责键 (segment_id, seq)、按 Session 的视图以及重建。派生行在事件所在的事务内写入。Session 上不保存计数器:总量是通过视图求和得到的,因此共享前缀的 fork 既不需要复制,也不需要修正。版本发生变化的表,或其 derivation 缺席过一段时间的表,会借助 derivations 中的游标从事件重新填充。事件是唯一的权威。

打开数据库时,会在打开它的事务内依次执行 src/migrations/ 中的升级步骤,每个 schema 版本一步。从版本 1 出发的那一步是唯一读取帧布局的代码。它改写的是同一个文件:数据库是所有 Session 共用的一个产物,没有可以与后继并存的按 Session 的代次,而事务保证留下的要么是旧布局,要么是新布局。

测量

用 80 个真实 Session(84,456 个事件,408.6 MB 事件 JSON)按实时写入时的批次大小经提供方重放:每 200 ms 事件时间一批,共 12,692 次提交。机器是一台 Apple Silicon 笔记本,运行 macOS 和 Node 24.21.0,同时有其他工作在进行;延迟取五轮交替运行的中位数,体积取做过检查点之后的数据库。

存储体积
Zstandard JSONL105.8 MB
帧,按实时写入形成的每帧 6.65 个事件109.7 MB
事件行,含派生表157.6 MB
事件行,不压缩442.4 MB
每个事件一段未压缩的 JSON 文本487.5 MB

events 表占行存储的 96.5%,它的两个索引占 2.4%,全部派生内容占 1.1%。完整读取最大的 Session 与帧耗时相同;读取最后 50 个事件耗时 0.35 ms,帧为 1.05 ms;跨整个存储按类型统计事件数耗时 10 ms,帧为 1,278 ms。按 Session 的 token 总量、工具调用次数和上下文压缩总量各自在约 1 ms 或更短时间内得出。

单个写者时,一次追加加刷盘的中位数在没有派生表时为 0.190 ms,有派生表时为 0.226 ms。派生本身每个事件耗费 0.10 µs 的 CPU;增加的时间来自写入量,因为一次提交每触及一张派生表,就多弄脏一个 4 KB 的页。

考虑过的替代方案

  • 保留帧并合并短帧。 否决。它能恢复到 JSONL 的体积,但事件对 SQL 仍然不透明,还要改写已存的行,实测的合并也抬高了追加延迟。
  • 不压缩的纯 JSON 行。 否决。任何 SQLite 客户端都能读取每个字节,但体积是三倍。
  • 压缩每一行,或使用训练过的字典。 暂时否决。把阈值降到 256 个字符可节省 3%,却让另外 28% 的行无法被 SQL 的 JSON 运算符读取。字典在估算中节省约 9%,但其字节会成为格式的一部分;按行记录的 codec 留有余地,以后可以加入字典而不必改写已有的行。
  • 在提交之后写入派生行。 实现并测量后移除。每次提交再开一个事务就多一次同步,四个写者时追加的中位数从 0.75 ms 升到 0.90 ms。把延后的批次做得更大也省不了多少,因为从已存事件重建需要重新读取并解压,每个事件 11 µs。
  • 用 SQL 触发器或生成列得到派生事实。 否决。触发器在同一事务内运行,什么也省不下,而且读不了压缩后的 data。
  • 单张通用派生表。 否决。它把每次提交写入的页数从 14.3 降到 12.1,但每个查询都得按种类列过滤,并读取没有名字的槽位。
  • 在 Session 行上保存计数器。 否决。fork 必须先复制再修正它们,而且它们会成为事件之外的第二个权威。
  • 把 SQL 作为字符串留在 TypeScript 中。 否决。无法按版本阅读或比较 schema,升级步骤还会不声不响地跟随当前的 schema 常量。
  • 拒绝帧布局的数据库。 否决。已有两个 alpha 版本写入过这种布局。
  • 写出后继数据库文件,而不是原地改写。 否决。升级期间磁盘占用翻倍,文件替换和指明数据库的路由记录还需要一个发布步骤;一个事务就能得到同样的全有或全无的结果,升级指南也要求先备份。
  • 像全文查询提供方那样,用带独立数据库的读模型插件。 对这些事实否决。它要重新读取并解压存储刚写下的每个事件,会落后于日志,还需要自己的变更检测;随事件一起写入的行不需要这些。全文搜索仍留在那个独立的提供方里,因为它的索引很大而且可选。
  • 由 Session projection 负责这些事实。 未被取代。projection 在内存中折叠单个 Session 的日志,仍是 DSH 所显示内容(例如 tokenUsage)的权威。它们不逐个打开日志就无法跨 Session 回答问题,而这正是这些表要解决的。
  • 提供一个服务,让其他插件注册 derivation。 暂缓。目前没有插件需要,在此之前 Derivation 保持内部使用。

后果

DSH 运行期间,可以用普通 SQL 按 Session 或跨整个存储查询事件、token 用量、工具调用和上下文压缩,尾部读取和单点读取也不再需要解码整帧。在实测语料上,存储比帧大 44%,比 JSONL 大 49%;与没有派生表相比,一次追加的中位数慢约 0.04 ms。

其他 SQLite 客户端没有 Zstandard 函数时读不了以 codec 1 存储的 data;其余各列、派生表和小事件仍可读取。派生表只存在于本提供方之下,所以在 JSONL 下需要这些事实的使用者仍要折叠日志。

首次打开帧布局的数据库时,进程会在改写每个事件期间被阻塞,每 100 MB 约四秒,而且更早的构建会拒绝升级后的文件。在释放出的页被重新利用之前,文件同时容纳两种布局。损坏的帧不会中止升级:帧中可读的事件照常迁移,每个没有可读行的序号由一行无法解码的记录代替,帧的字节保留在 frames_set_aside 中,所以升级后读取失败的位置与帧布局下完全相同。版本 1 的子 Segment 若不从父 Segment 结束处开始,升级会中止,而不是给它一段它从未有过的历史;Segment 行缺失的帧与其他不可读的帧一样被搁置。每个 schema 版本是一个文件 resources/sql/schema/vN.sql,一旦有发布版本写出过它就不再编辑。升级步骤指明它所写版本的文件,并把自己的语句放在 resources/sql/upgrade/A-to-B/ 下,所以新增版本 3 只需新增一个步骤模块和若干文件,不改动任何已有文件。有一项测试检查第一步只读取它自己的文件和版本 2 的 schema,并且它留下的数据库与新建数据库的 schema 相同。

没有服务可供其他插件注册 Derivation,也没有设置可以关闭内置的表。Session 仍然无法删除,所以共享的历史永远不会回收。

无法使用数据库的打开会执行恢复,而不是让整个 Session 服务失败。文件缺失时新建一个空数据库;当前构建读不了的文件会被移到 <name>.unreadable-<时间戳>,并由一个新的空数据库取代它:每个已存的字节都保留下来,除被移走文件里的那些 Session 外其余仍可用。recovery: report 为手工修复存储的运维保留原先的拒绝行为。

只有损坏才会替换文件。超出 busy 超时的锁在所有平台上都以 SESSION_STORAGE_LOCKED 报告,因为 SQLite 以操作系统锁持有它,进程退出时由内核释放:存活下来的锁属于仍在运行的写者,替换它的文件会让该写者继续写入没有任何 Session 读取的字节,而新数据库从空开始。Windows 根本无法移动被其他句柄打开的文件,因此那里的锁不可能用这种方式恢复;统一报告是唯一在各平台都成立的规则。schema 比当前构建更新的数据库同样永远不会被替换,因为它的字节可读,只有写出它的那个发布版本才能解释它们。

相关记录

  • JSONL-only first-party Session persistence 记录了早先的 SQLite 提供方被移除的原因。本提供方后来作为需手动启用的包回归;该记录对负责人、部署需求和格式过渡策略的要求同样适用于它,依次执行的升级步骤就是物理 schema 的过渡策略。
  • SQLite physical chunk-row compression 是被移除的提供方所用的布局,它把成串的流式 chunk 打包进一行。chunk 如今不再是单独的事件,所以每个事件一行不再像当时那样使行数成倍增加。
  • 基于句柄的会话持久化 定义了本提供方实现的服务。