fix(session): carry over the readable events of a damaged frame

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.
This commit is contained in:
Magolor committed 2026-11-25 17:48:54 +08:00
1 parent cbc6457226
commit aeb1cfbfcf
13 files changed
+81 -45

No files matched your search

@@ -18,8 +18,8 @@
en: 65792e0c1036b43f
zh: f68527200f9dff10
/agent-note-sqlite-event-rows-with-derived-tables/consequences:
en: 6c8994013f062f54
zh: 1a8dad5f04e50376
en: 52dd6d66507dff57
zh: 35f77c054ebed45f
/agent-note-sqlite-event-rows-with-derived-tables/related:
en: 8fd225f29ca16cc9
zh: 446ebc55bf77bc2b
@@ -57,7 +57,7 @@ Events, token usage, tool calls, and compactions are queryable with ordinary SQL
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. A frame that cannot be read does not stop the upgrade: its bytes move to `frames_set_aside` and one undecodable row stands in for it, so only its Session stays refused, as it was under frames. Adding a schema version means adding one step module; the step that writes the current version uses the current schema module, and takes its own copy of that schema in the change that introduces the next version. A test pins the schema objects the first step produces, so that change cannot be forgotten.
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 event that is not, and the frame's bytes are kept in `frames_set_aside`, so a read fails afterwards exactly where it failed under frames. Adding a schema version means adding one step module; the step that writes the current version uses the current schema module, and takes its own copy of that schema in the change that introduces the next version. A test pins the schema objects the first step produces, so that change cannot be forgotten.
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.
@@ -57,7 +57,7 @@ DSH 运行期间,可以用普通 SQL 按 Session 或跨整个存储查询事
其他 SQLite 客户端没有 Zstandard 函数时读不了以 `codec` 1 存储的 `data`;其余各列、派生表和小事件仍可读取。派生表只存在于本提供方之下,所以在 JSONL 下需要这些事实的使用者仍要折叠日志。
首次打开帧布局的数据库时,进程会在改写每个事件期间被阻塞,每 100 MB 约四秒,而且更早的构建会拒绝升级后的文件。在释放出的页被重新利用之前,文件同时容纳两种布局。无法读取的帧不会中止升级:它的字节移入 `frames_set_aside`,由一行无法解码的记录代替,所以只有它所属的 Session 像在帧布局下一样继续被拒绝。新增一个 schema 版本只需新增一个步骤模块;写出当前版本的步骤使用当前的 schema 模块,并在引入下一个版本的那次变更中改用自己的一份 schema 副本。有一项测试固定了第一步产生的 schema 对象,所以那次变更不会被遗漏。
首次打开帧布局的数据库时,进程会在改写每个事件期间被阻塞,每 100 MB 约四秒,而且更早的构建会拒绝升级后的文件。在释放出的页被重新利用之前,文件同时容纳两种布局。损坏的帧不会中止升级:帧中可读的事件照常迁移,每个不可读的事件由一行无法解码的记录代替,帧的字节保留在 `frames_set_aside` 中,所以升级后读取失败的位置与帧布局下完全相同。新增一个 schema 版本只需新增一个步骤模块;写出当前版本的步骤使用当前的 schema 模块,并在引入下一个版本的那次变更中改用自己的一份 schema 副本。有一项测试固定了第一步产生的 schema 对象,所以那次变更不会被遗漏。
没有服务可供其他插件注册 `Derivation`,也没有设置可以关闭内置的表。Session 仍然无法删除,所以共享的历史永远不会回收。
@@ -12,5 +12,5 @@
en: 132c4444d114f91a
zh: f4bfef1ce328a853
/sqlite-session-store-with-one-row-per-event/migration:
en: 1050812c0b9407e8
zh: 43e3b4f84558af62
en: 24c1019ec8540b54
zh: 9b2d34d4d9cb1e83
@@ -18,5 +18,5 @@ A database written by an earlier release has schema version 1. The first open up
1. Stop every DSH process that uses the storage root.
2. Copy `<root>/.segments/sessions.sqlite` and any `sessions.sqlite-wal` and `sessions.sqlite-shm` files beside it to a backup location. This copy is the only way back to an earlier release.
3. Remove `frameEvents` from the provider's `config` in your `cordis.yml` or patch. A leftover value is ignored.
4. Start DSH. The upgrade runs before the first Session opens and blocks the process meanwhile, about four seconds per 100 MB of database in our measurement; the log names it when it starts. The upgraded file holds both layouts until SQLite reuses the freed pages, so expect about 2.5 times the earlier size at first; `VACUUM` shrinks it to roughly 45% more than the frame layout. A warning names any frame that could not be read: its Session stays unreadable, as before, and its bytes are kept in the `frames_set_aside` table. If the upgrade fails with `SESSION_STORAGE_UPGRADE`, the file is unchanged: restore the backup or keep using the earlier release.
4. Start DSH. The upgrade runs before the first Session opens and blocks the process meanwhile, about four seconds per 100 MB of database in our measurement; the log names it when it starts. The upgraded file holds both layouts until SQLite reuses the freed pages, so expect about 2.5 times the earlier size at first; `VACUUM` shrinks it to roughly 45% more than the frame layout. A warning names any frame that holds unreadable data: reads fail where they failed before, and the frame's bytes are kept in the `frames_set_aside` table. If the upgrade fails with `SESSION_STORAGE_UPGRADE`, the file is unchanged: restore the backup or keep using the earlier release.
5. Confirm the result with `sqlite3 <root>/.segments/sessions.sqlite "PRAGMA user_version; SELECT count(*) FROM session_summary;"`. It prints `2` and the number of stored Sessions.
@@ -18,5 +18,5 @@ description: "需手动启用的 SQLite Session 存储改为每个事件一行
1. 停止所有使用该存储根目录的 DSH 进程。
2. 把 `<root>/.segments/sessions.sqlite` 以及同目录下的 `sessions.sqlite-wal`、`sessions.sqlite-shm` 文件复制到备份位置。这份副本是回退到早期版本的唯一途径。
3. 从 `cordis.yml` 或 patch 中该提供方的 `config` 里删除 `frameEvents`。遗留的值会被忽略。
4. 启动 DSH。升级在第一个 Session 打开之前执行,期间进程被阻塞;按我们的测量,每 100 MB 数据库约需四秒,开始时日志会指明。在 SQLite 重新利用释放出的页之前,升级后的文件同时容纳两种布局,所以起初预计是原来的约 2.5 倍;执行 `VACUUM` 可缩小到比帧布局多约 45%。如果有帧无法读取,会有一条警告指明它:它所属的 Session 和以前一样无法读取,其字节保留在 `frames_set_aside` 表中。如果升级以 `SESSION_STORAGE_UPGRADE` 失败,文件保持不变:请恢复备份,或继续使用早期版本。
4. 启动 DSH。升级在第一个 Session 打开之前执行,期间进程被阻塞;按我们的测量,每 100 MB 数据库约需四秒,开始时日志会指明。在 SQLite 重新利用释放出的页之前,升级后的文件同时容纳两种布局,所以起初预计是原来的约 2.5 倍;执行 `VACUUM` 可缩小到比帧布局多约 45%。如果有帧含有无法读取的数据,会有一条警告指明它:读取失败的位置与以前相同,该帧的字节保留在 `frames_set_aside` 表中。如果升级以 `SESSION_STORAGE_UPGRADE` 失败,文件保持不变:请恢复备份,或继续使用早期版本。
5. 运行 `sqlite3 <root>/.segments/sessions.sqlite "PRAGMA user_version; SELECT count(*) FROM session_summary;"` 确认结果,输出应为 `2` 和已存储的 Session 数量。
@@ -30,8 +30,8 @@
en: c9adc0dab479e1a6
zh: 53d323222a1535ea
/deepseek-ai-dsh-session-persistence-sqlite/understand-the-implementation:
en: 89f97da3060cd273
zh: 908f519ab5e472b7
en: 7e2ab5b850172f6e
zh: 1285d4886718005a
/deepseek-ai-dsh-session-persistence-sqlite/further-exploration:
en: 6c9f517924d25414
zh: 0a8400a08ec55dbf
@@ -51,8 +51,8 @@
en: 3a849c807fae4040
zh: cb3a122553040b79
/deepseek-ai-dsh-session-persistence-sqlite/known-limitations-and-deferred-work:
en: ec150986bc781eea
zh: 92bd00dff94b817b
en: 94f2d3feb95c8648
zh: d5a93b5d2926db2d
/deepseek-ai-dsh-session-persistence-sqlite/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: e88aeb617ffb74ea
@@ -99,7 +99,7 @@ SQLite keeps Session metadata, predecessor-linked Segment metadata and events. `
Derived tables are filled from events and never read by the provider. Each `Derivation` declares one table keyed by `(segment_id, seq)`, the event types it reads, and a pure function from an event to a row; the store adds the `session_<name>` view. `derivations` records each table's version and, while a table is behind, the `event_no` it has reached. A table that is missing, whose stored version differs from its derivation, or that is added to a store that already holds events such as an upgraded one, is dropped and refilled from events in bounded transactions after open. A stored table whose derivation this build does not hold is kept and marked behind from that point, so it catches up when its derivation returns. A derivation that throws, or a row its table refuses, skips that row and never fails the append; the first such failure of each table logs a warning that names the event. A failure that ends the transaction fails the append with its events.
Opening a database runs the ordered upgrade steps in [migrations/](src/migrations/index.ts): each step upgrades the stored schema by one version inside the transaction that opens the database, so a failed step leaves the file unchanged. The step from version 1 rewrites the earlier frame layout as event rows, carrying over Segment identities, ancestry and inherited counts; it copies each event by its envelope, so an event type the build does not know is upgraded and judged when its Session is read. A frame that cannot be read is logged and copied unchanged into `frames_set_aside`, and one row that no reader decodes stands in for it, so its Session is refused as it was before the upgrade and every other Session upgrades. The provider logs each step before it runs, because a step blocks the process while it rewrites the database. A step that fails rejects the open with `SESSION_STORAGE_UPGRADE`, and the provider does not retry it until restart. A foreign database, a version newer than this build, or a database without the current tables is refused with `SESSION_STORAGE_FORMAT`.
Opening a database runs the ordered upgrade steps in [migrations/](src/migrations/index.ts): each step upgrades the stored schema by one version inside the transaction that opens the database, so a failed step leaves the file unchanged. The step from version 1 rewrites the earlier frame layout as event rows, carrying over Segment identities, ancestry and inherited counts; it copies each event by its envelope, so an event type the build does not know is upgraded and judged when its Session is read. A frame that holds an unreadable event is logged and copied unchanged into `frames_set_aside`; a row that no reader decodes stands in for each such event, or for the whole frame when its bytes cannot be split into events, so a read fails after the upgrade exactly where it failed before and every other Session upgrades. The provider logs each step before it runs, because a step blocks the process while it rewrites the database. A step that fails rejects the open with `SESSION_STORAGE_UPGRADE`, and the provider does not retry it until restart. A foreign database, a version newer than this build, or a database without the current tables is refused with `SESSION_STORAGE_FORMAT`.
WAL is enabled before schema publication so a concurrent reader cannot prevent the first mode switch. Journal-mode lock contention retries within the five-second busy budget before any schema or Session write; persistent contention and other failures are reported. The backend owns write queues, live-event buffering, transaction completion and handle cleanup; callers do not address Segments.
@@ -156,7 +156,7 @@ These constraints apply when selecting this provider.
- SQLite accepts the current Session format; a future event-format upgrade needs its own SQLite history migration.
- Other SQL clients cannot read `data` stored with `codec` 1 without a Zstandard function; every other column, the derived tables and small events remain readable.
- The derived tables are the built-in four: no setting turns them off, and no service registers a `Derivation` from another plugin.
- Processes of different builds must not write one database: a build without a derivation stores events whose derived rows the other build never adds, and an earlier build fails once a later one upgrades the schema.
- Processes of different builds must not write one database at the same time. An earlier build fails once a later one upgrades the schema. A derived table is caught up when a build that holds its derivation opens the database; if a process of a build without that derivation is still running then and appends afterwards, the rows of those events are missing until the table's version changes.
- An open that meets another process's write lock, such as a running upgrade, blocks its process for the five-second busy timeout and then fails.
- Sessions cannot be deleted, so storage shared between forks is never reclaimed.
- Each event with a large `data` leaves part of its last overflow page unused; the [decision record](../../../.agents/notes/implemented/architecture/2026-11-25-sqlite-event-rows-and-derived-tables.md) holds the measured sizes.
@@ -99,7 +99,7 @@ SQLite 保存 Session 元数据、前驱关联的 Segment 元数据和事件。`
派生表由事件填充,提供者自身从不读取。每个 `Derivation` 声明一张以 `(segment_id, seq)` 为键的表、它读取的事件类型,以及一个把事件映射为一行的纯函数;存储会添加 `session_<name>` 视图。`derivations` 记录每张表的版本,以及表落后时已处理到的 `event_no`。表缺失、表的已存版本与其 derivation 不同,或表被加入已有事件的存储(例如升级后的存储)时,会在打开后以有界事务删除并从事件重新填充。已存的表若在当前构建中没有对应的 derivation,会被保留并标记为从该处起落后,待其 derivation 恢复后补齐。derivation 抛出异常,或其表拒绝某一行时,会跳过该行,绝不会导致追加失败;每张表首次出现这类失败时记录一条指明该事件的警告。导致事务终止的失败则会使该次追加连同其事件一起失败。
打开数据库时会依次执行 [migrations/](src/migrations/index.ts) 中的升级步骤:每一步在打开数据库的事务内把已存 schema 升级一个版本,因此某一步失败时文件保持不变。从版本 1 出发的一步把早先的帧布局改写为事件行,并保留 Segment 标识、祖先关系和继承计数;它按信封复制每个事件,因此当前构建不认识的事件类型也会被升级,待其 Session 被读取时再作判断。无法读取的帧会被记入日志并原样复制到 `frames_set_aside`,由一行任何读取方都不解码的记录代替它,所以它所属的 Session 像升级前一样被拒绝,其余 Session 照常升级。每一步改写数据库期间进程被阻塞,所以提供者会在该步开始前记录日志。某一步失败时,打开操作以 `SESSION_STORAGE_UPGRADE` 被拒绝,提供者在重启前不再重试。外来的数据库、比当前构建更新的版本,或缺少当前表的数据库会以 `SESSION_STORAGE_FORMAT` 被拒绝。
打开数据库时会依次执行 [migrations/](src/migrations/index.ts) 中的升级步骤:每一步在打开数据库的事务内把已存 schema 升级一个版本,因此某一步失败时文件保持不变。从版本 1 出发的一步把早先的帧布局改写为事件行,并保留 Segment 标识、祖先关系和继承计数;它按信封复制每个事件,因此当前构建不认识的事件类型也会被升级,待其 Session 被读取时再作判断。含有无法读取事件的帧会被记入日志并原样复制到 `frames_set_aside`;每个这样的事件由一行任何读取方都不解码的记录代替,帧的字节无法拆成事件时则由一行代替整帧,所以升级后读取失败的位置与升级前完全相同,其余 Session 照常升级。每一步改写数据库期间进程被阻塞,所以提供者会在该步开始前记录日志。某一步失败时,打开操作以 `SESSION_STORAGE_UPGRADE` 被拒绝,提供者在重启前不再重试。外来的数据库、比当前构建更新的版本,或缺少当前表的数据库会以 `SESSION_STORAGE_FORMAT` 被拒绝。
发布 schema 前先启用 WAL,防止并发读者阻碍首次模式切换。日志模式的锁竞争会在五秒 busy 等待预算内重试,此时尚未写入 schema 或 Session;持续的锁竞争及其他失败仍会报告。后端负责写入队列、实时事件缓冲、事务完成和句柄清理;调用方不直接访问 Segment。
@@ -156,7 +156,7 @@ SQLite 保存 Session 元数据、前驱关联的 Segment 元数据和事件。`
- SQLite 接受当前 Session 格式;未来事件格式升级需要独立的 SQLite 历史迁移。
- 其他 SQL 客户端没有 Zstandard 函数时无法读取以 `codec` 1 存储的 `data`;其余各列、派生表和小事件仍可读取。
- 派生表即内置的四张:没有设置可以关闭它们,也没有服务可供其他插件注册 `Derivation`。
- 不同构建的进程不得写入同一个数据库:缺少某个 derivation 的构建写入的事件,其派生行另一个构建不会补上;较新的构建升级 schema 之后,较早的构建会失败。
- 不同构建的进程不得同时写入同一个数据库。较新的构建升级 schema 之后,较早的构建会失败。持有某个 derivation 的构建打开数据库时会补齐对应的派生表;如果此时缺少该 derivation 的构建仍有进程在运行并在此后继续追加,这些事件的派生行会一直缺失,直到该表的版本变化。
- 打开时如果遇到其他进程持有的写锁(例如正在进行的升级),所在进程会被阻塞五秒的 busy 超时,然后失败。
- Session 无法删除,因此 fork 之间共享的存储永远不会回收。
- `data` 较大的事件会让其最后一个溢出页留有未用空间;实测体积见[决策记录](../../../.agents/notes/implemented/architecture/2026-11-25-sqlite-event-rows-and-derived-tables.zh.md)。
@@ -14,8 +14,8 @@ import { EVENT_CODEC_UNREADABLE, encodeRow } from '../row.ts'
import { SCHEMA } from '../schema.ts'
import type { Migration } from './types.ts'
/** `events.type` of the row that stands in for a frame this step could not read. */
const UNREADABLE_TYPE = 'storage/unreadable-frame'
/** `events.type` of a row that stands in for stored data this step could not read. */
const UNREADABLE_TYPE = 'storage/unreadable'
/** Version 1 `frames.codec` for one Zstandard frame; every other stored value was UTF-8 text. */
const FRAME_CODEC_ZSTD = 1
const FRAME_TABLES = ['frames', 'traces', 'segments', 'segment_ancestors']
@@ -32,12 +32,14 @@ const frame = z.object({ frame: z.number().int(), segment_id: z.number().int(),
* were Segment-local, and each event's own `seq` supplies the Session sequence.
* Events are carried over by their envelope alone, so an event type this build
* does not know upgrades with the rest and is judged when its Session is read.
* A frame that cannot be read (damaged bytes, a range it does not hold, an event
* out of sequence, or an envelope the event row cannot hold) was unreadable before
* the upgrade too. It is reported and copied unchanged into `frames_set_aside`,
* a table that exists only then. One row that no reader decodes stands in for
* its events, so the Segment keeps its event count: a read that reaches the frame
* is refused, as it was before the upgrade, and every other Session upgrades.
* Damage that made a read fail before the upgrade makes the same read fail after
* it, and nothing else. A frame whose bytes cannot be split into its recorded
* number of lines gets one row that no reader decodes, at its last sequence. A
* frame that splits is carried over event by event, and only an event that
* cannot be read (not JSON, out of sequence, or an envelope the event row cannot
* hold) gets such a row. The Segment keeps its event count either way. Each
* damaged frame is reported once and copied unchanged into `frames_set_aside`,
* a table that exists only then.
*/
export const frames: Migration = {
from: 1,
@@ -70,28 +72,42 @@ export const frames: Migration = {
const stored = db.prepare(`SELECT f.rowid AS frame, s.segment_id, s.segment_uuid, s.base_seq, f.start_seq, f.end_seq, f.codec, f.payload
FROM frames f JOIN segments s ON s.segment_uuid = f.segment_uuid ORDER BY s.segment_id, f.start_seq`)
const damaged: number[] = []
const standIn = (segment: number, seq: number): void => {
insert.run(segment, seq, UNREADABLE_TYPE, 0, null, null, null, EVENT_CODEC_UNREADABLE, new Uint8Array())
}
for (const raw of stored.iterate()) {
const { frame: rowid, segment_id: segment, segment_uuid: uuid, base_seq: base, start_seq: start, end_seq: end,
codec, payload } = frame.parse(raw)
let events: StoredEnvelope[]
const setAside = (error: unknown): void => {
if (damaged.at(-1) === rowid) return
damaged.push(rowid)
onSetAside(`frame at ${base + start} of Segment ${uuid}`, error)
}
let texts: string[]
try {
const bytes = codec === FRAME_CODEC_ZSTD ? zstdDecompressSync(payload) : payload
const texts = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('utf8').split('\n')
texts = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('utf8').split('\n')
if (texts.length !== end - start) throw new RangeError(`SQLite frame at ${start} does not hold its recorded range`)
events = texts.map((text, index) => {
const event = decodeEnvelope(JSON.parse(text))
if (event.seq !== base + start + index) throw new RangeError(`SQLite frame event ${event.seq} is out of sequence`)
return event
})
} catch (error: unknown) {
// The frame was unreadable before the upgrade too. A row no reader decodes holds its last sequence, so
// the Segment keeps its event count and a read that reaches the frame is refused; the bytes are kept below.
damaged.push(rowid)
insert.run(segment, base + end - 1, UNREADABLE_TYPE, 0, null, null, null, EVENT_CODEC_UNREADABLE, new Uint8Array())
onSetAside(`frame at ${base + start} of Segment ${uuid}`, error)
// No line of the frame can be placed. A row no reader decodes holds its last sequence, so the Segment
// keeps its event count and a read that reaches the frame is refused, as it was before the upgrade.
setAside(error)
standIn(segment, base + end - 1)
continue
}
for (const event of events) {
for (const [index, text] of texts.entries()) {
const seq = base + start + index
let event: StoredEnvelope
try {
event = decodeEnvelope(JSON.parse(text))
if (event.seq !== seq) throw new RangeError(`SQLite frame event ${event.seq} is out of sequence`)
} catch (error: unknown) {
// The frame layout parsed only the lines a read asked for, so the other events of this frame stayed
// readable; they are carried over, and only this event is replaced.
setAside(error)
standIn(segment, seq)
continue
}
const row = encodeRow(event, compression)
insert.run(segment, row.seq, row.type, row.time, row.surface_op, row.source_seqs, row.ignorable, row.codec, row.data)
}
@@ -66,7 +66,8 @@ export class SqliteSessionPersistence extends SessionPersistence {
report: (id, error) => { owner.logger.error(`Segment persistence failed for ${id}; durability checkpoint will reject: ${String(error)}`) },
reportDerivation: (failure) => { owner.logger.warn(describeDerivationFailure(failure)) },
reportSetAside: (detail, error) => {
owner.logger.warn(`The Session database upgrade set aside the ${detail}, which cannot be read; its Session reads as damaged: ${String(error)}`)
owner.logger.warn(`The Session database upgrade set aside the ${detail}, which holds data that cannot be read; `
+ `reads that reach it are refused: ${String(error)}`)
},
reportUpgrade: (from, to) => {
owner.logger.info(`Upgrading the Session database from schema version ${from} to ${to}; Sessions open when it finishes`)
@@ -68,8 +68,6 @@ CREATE TABLE sessions (
origin TEXT GENERATED ALWAYS AS (${member('origin', 'text')}) VIRTUAL,
agent_preset TEXT GENERATED ALWAYS AS (${member('agentPreset', 'text')}) VIRTUAL
) STRICT;
CREATE INDEX sessions_by_cwd ON sessions(cwd, created_at);
CREATE INDEX sessions_by_parent ON sessions(parent_session) WHERE parent_session IS NOT NULL;
CREATE TABLE events (
event_no INTEGER PRIMARY KEY,
segment_id INTEGER NOT NULL REFERENCES segments(segment_id),
@@ -465,7 +465,7 @@ describe('frame layout conversion', () => {
writeFrameLayout(inspect, (db) => { db.prepare("UPDATE frames SET payload = ? WHERE segment_uuid = 'seg-root' AND start_seq = ?").run(Buffer.from('damaged'), start) })
await logs.start()
expect((await logs.stat(SessionId('root')))?.eventCount).toBe(framed.root.length)
expect(rows("SELECT count(*) AS stand_ins FROM events WHERE type = 'storage/unreadable-frame' AND codec = 255")).toEqual([{ stand_ins: 1 }])
expect(rows("SELECT count(*) AS stand_ins FROM events WHERE type = 'storage/unreadable' AND codec = 255")).toEqual([{ stand_ins: 1 }])
const damaged = await logs.open(SessionId('root'), 'read')
try { await expect(damaged.read()).rejects.toThrow(message) } finally { await damaged.close() }
await expect(logs.open(SessionId('root'), 'write')).rejects.toThrow()
@@ -473,6 +473,29 @@ describe('frame layout conversion', () => {
try { expect((await apart.read(0, 2)).events).toEqual(framed.tools.slice(0, 2)) } finally { await apart.close() }
})
it('carries over the readable events of a frame in which other events are damaged, so reads that avoid those still succeed', async () => {
const reportSetAside = vi.fn<(detail: string, error: unknown) => void>()
const { logs, inspect, rows } = await fixture({ reportSetAside })
const lines = framed.root.slice(0, 3).map(entry => JSON.stringify(entry))
writeFrameLayout(inspect, (db) => {
db.prepare("UPDATE frames SET codec = 0, payload = ? WHERE segment_uuid = 'seg-root' AND start_seq = 0")
.run(Buffer.from([lines[0], '{"type":', JSON.stringify(marker(9))].join('\n')))
})
await logs.start()
expect(reportSetAside.mock.calls.map(([detail]) => detail)).toEqual(['frame at 0 of Segment seg-root'])
expect(rows(`SELECT group_concat(seq) AS stand_ins FROM (SELECT seq FROM events WHERE type = 'storage/unreadable'
AND segment_id = (SELECT segment_id FROM segments WHERE segment_uuid = 'seg-root') ORDER BY seq)`)).toEqual([{ stand_ins: '1,2' }])
expect(rows("SELECT count(*) AS stored FROM events WHERE segment_id = (SELECT segment_id FROM segments WHERE segment_uuid = 'seg-root')"))
.toEqual([{ stored: framed.root.length }])
expect(rows('SELECT count(*) AS kept FROM frames_set_aside')).toEqual([{ kept: 1 }])
const reader = await logs.open(SessionId('root'), 'read')
try {
expect((await reader.read(0, 1)).events).toEqual(framed.root.slice(0, 1))
expect((await reader.read(3, 2)).events).toEqual(framed.root.slice(3))
await expect(reader.read()).rejects.toThrow(/stored event at index 1 is invalid/)
} finally { await reader.close() }
})
it('refuses a Session whose only frame is set aside instead of reading it as empty', async () => {
const { logs, inspect } = await fixture()
writeFrameLayout(inspect, (db) => { db.prepare("UPDATE frames SET payload = ? WHERE segment_uuid = 'seg-grand'").run(Buffer.from('damaged')) })
@@ -539,8 +562,8 @@ describe('frame layout conversion', () => {
})
await persistence.start()
expect(warn.mock.calls.map(([message]) => String(message))).toEqual([
'The Session database upgrade set aside the frame at 3 of Segment seg-root, which cannot be read; its Session reads as damaged: '
+ 'RangeError: SQLite frame at 3 does not hold its recorded range',
'The Session database upgrade set aside the frame at 3 of Segment seg-root, which holds data that cannot be read; '
+ 'reads that reach it are refused: RangeError: SQLite frame at 3 does not hold its recorded range',
])
})
@@ -603,8 +626,6 @@ describe('upgrade steps', () => {
prepareSchema(fresh, options)
expect(layout(upgraded)).toEqual([
['index', 'events_by_type', null],
['index', 'sessions_by_cwd', null],
['index', 'sessions_by_parent', null],
['table', 'events', 'event_no segment_id seq type time surface_op source_seqs ignorable codec data'],
['table', 'segment_paths', 'segment_id member_id end_seq'],
['table', 'segments', 'segment_id segment_uuid parent_id base_seq'],