schema.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /**
  2. * Schema + load-time helpers for the SQLite session-persistence backend: the
  3. * DDL (a `sessions` metadata table and a 1:1 `events` row per `SessionEvent`),
  4. * the database open/configure step, and the last-`turn/end` cut that gives the
  5. * SQLite backend the SAME crash-tail-on-load semantics as the JSONL backend.
  6. *
  7. * @module dsh-session-persistence-sqlite/schema
  8. */
  9. import { DatabaseSync } from 'node:sqlite'
  10. import type { SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session'
  11. /**
  12. * The on-disk schema version. Bumped only on a breaking change to the table
  13. * layout; orthogonal to a session's own `version` (which versions the EVENT
  14. * vocabulary, stored per session in the `sessions` row).
  15. */
  16. export const SCHEMA_VERSION = 3
  17. /**
  18. * A row of the `sessions` table — the out-of-log metadata ({@link SessionHeader}).
  19. * The row's EXISTENCE is the materialization signal: it is written only by the
  20. * first `append` (lazy materialization), so a created-but-never-appended
  21. * session has no row and is absent from `list`, mirroring the JSONL
  22. * backend's "no file until first append".
  23. */
  24. export interface SessionRow {
  25. id: string
  26. version: number
  27. created_at: number
  28. cwd: string | null
  29. parent_session: string | null
  30. seed_length: number | null
  31. }
  32. /** An `events` table row: one `SessionEvent` mapped 1:1 (`data` is JSON text). */
  33. export interface EventRow {
  34. seq: number
  35. type: string
  36. time: number
  37. data: string
  38. }
  39. /**
  40. * Open the database at `path` and apply the schema + pragmas. `foreign_keys`
  41. * makes `ON DELETE CASCADE` drop a session's events with its row; `journal_mode
  42. * = WAL` matches the durability model the ADR records (the row shape maps 1:1
  43. * onto `SessionEvent`; opencode runs this exact shape on SQLite/WAL).
  44. *
  45. * The table-layout version is persisted in SQLite's `PRAGMA user_version` and
  46. * checked on open: a fresh database (user_version 0) is stamped with the
  47. * current {@link SCHEMA_VERSION}; an existing database whose version is NOT the
  48. * current one (written by a different, incompatible build — older or newer) is
  49. * REJECTED rather than opened against a layout this build does not understand.
  50. * There are no migrations: an earlier layout (v1's different `sessions` shape,
  51. * v2 without the `seed_length` column) is not upgraded in place — it is rejected.
  52. */
  53. export function openDatabase(path: string): DatabaseSync {
  54. const db = new DatabaseSync(path)
  55. db.exec('PRAGMA foreign_keys = ON')
  56. db.exec('PRAGMA journal_mode = WAL')
  57. // `PRAGMA user_version` always returns exactly one row { user_version }.
  58. const { user_version: onDisk } = db.prepare('PRAGMA user_version').get() as { user_version: number }
  59. if (onDisk !== 0 && onDisk !== SCHEMA_VERSION) {
  60. db.close()
  61. throw new Error(`session database at "${path}" has schema version ${onDisk}, incompatible with this build (${SCHEMA_VERSION})`)
  62. }
  63. if (onDisk === 0) {
  64. // Fresh (or pre-versioning) database: stamp the current layout version.
  65. // PRAGMA does not accept bound parameters, so interpolate the integer
  66. // constant (SCHEMA_VERSION is a trusted in-code number, not user input).
  67. db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`)
  68. }
  69. db.exec(`
  70. CREATE TABLE IF NOT EXISTS sessions (
  71. id TEXT PRIMARY KEY,
  72. version INTEGER NOT NULL,
  73. created_at INTEGER NOT NULL,
  74. cwd TEXT,
  75. parent_session TEXT,
  76. seed_length INTEGER
  77. ) STRICT
  78. `)
  79. db.exec(`
  80. CREATE TABLE IF NOT EXISTS events (
  81. session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
  82. seq INTEGER NOT NULL,
  83. type TEXT NOT NULL,
  84. time INTEGER NOT NULL,
  85. data TEXT NOT NULL,
  86. PRIMARY KEY (session_id, seq)
  87. ) STRICT
  88. `)
  89. return db
  90. }
  91. /** Reconstruct the {@link SessionHeader} from a `sessions` row. */
  92. export function rowToMeta(row: SessionRow): SessionHeader {
  93. return {
  94. version: row.version,
  95. id: row.id as SessionId,
  96. createdAt: row.created_at,
  97. ...row.cwd !== null ? { cwd: row.cwd } : {},
  98. ...row.parent_session !== null ? { parentSession: row.parent_session as SessionId } : {},
  99. ...row.seed_length !== null ? { seedLength: row.seed_length } : {},
  100. }
  101. }
  102. /** Reconstruct a {@link SessionEvent} from an `events` row (parses `data`). */
  103. export function rowToEvent(row: EventRow): SessionEvent {
  104. return {
  105. type: row.type,
  106. seq: row.seq,
  107. time: row.time,
  108. data: JSON.parse(row.data) as SessionEvent['data'],
  109. } as SessionEvent
  110. }
  111. /**
  112. * The preserved prefix of an ordered event-row list (mirrors the JSONL
  113. * backend's `scanLog`): the longest prefix of complete, seq-contiguous,
  114. * parseable rows, PLUS the seq from which a never-committed torn tail must be
  115. * deleted (or `undefined` if the whole list is intact).
  116. *
  117. * A crash can leave a durable log whose final turn never closed: real,
  118. * fully-written rows sit after the last `turn/end`. Those are PRESERVED — a
  119. * single turn can be huge in a long-horizon task, so truncating it would
  120. * destroy real work; the backend closes the orphaned open turn with a synthetic
  121. * `turn/end {kind:'interrupted'}` on load (the session-persistence RFC). The ONLY thing excluded is
  122. * a torn trailing fragment — a row whose `data` never parses, or a seq gap —
  123. * AFTER the last committed `turn/end`; that bounds the preserved region and its
  124. * seq is returned as `tornFrom` so `load` can physically delete it.
  125. *
  126. * The last `turn/end` is computed from the `type` COLUMN (never parsing tail
  127. * `data`), so a malformed `data` in an uncommitted tail row is discarded rather
  128. * than making the session unloadable. A parse error or seq gap AT OR BEFORE the
  129. * last committed `turn/end` is committed-data corruption and throws.
  130. *
  131. * This relies on the session-log invariant that every event lives inside a turn
  132. * (`Session.append` enforces it): only the final turn can be open, so the
  133. * preserved tail is at most one unclosed turn.
  134. */
  135. export function scanRows(rows: readonly EventRow[]): { preserved: SessionEvent[]; tornFrom?: number } {
  136. // Pass 1: parse each row's data; a row whose data is not valid JSON is a hole.
  137. // (The seq/type COLUMNS are always present even when `data` is corrupt.)
  138. interface Parsed { ok: boolean; event?: SessionEvent }
  139. const parsed: Parsed[] = rows.map((row) => {
  140. try {
  141. return { ok: true, event: rowToEvent(row) }
  142. } catch {
  143. return { ok: false }
  144. }
  145. })
  146. // The last index that is a valid `turn/end` — the last fully-committed
  147. // boundary (the loop flushes only at turn/end).
  148. let lastTurnEnd = -1
  149. for (let i = parsed.length - 1; i >= 0; i--) {
  150. if (parsed[i]?.ok && rows[i]?.type === 'turn/end') { lastTurnEnd = i; break }
  151. }
  152. // Walk the longest PREFIX of complete, seq-contiguous, parseable rows
  153. // (row i has seq === i). This includes the fully-written rows of an
  154. // interrupted final turn AFTER the last turn/end — real work, never
  155. // truncated. The walk stops at the first hole:
  156. // - at or before the last committed turn/end → committed corruption (throw);
  157. // - after it (or no committed turn/end) → tolerated torn tail (stop).
  158. const preserved: SessionEvent[] = []
  159. for (let i = 0; i < rows.length; i++) {
  160. const p = parsed[i]
  161. if (!p?.ok || p.event === undefined) {
  162. if (i <= lastTurnEnd) throw new Error(`corrupt session log: unparsable committed event at seq ${rows[i]?.seq}`)
  163. break // torn tail fragment after the last turn/end — stop, tolerate
  164. }
  165. if (p.event.seq !== i) {
  166. if (i <= lastTurnEnd) throw new Error(`corrupt session log: seq gap in committed region (expected ${i}, got ${p.event.seq})`)
  167. break // gap after the last turn/end — torn tail, stop
  168. }
  169. preserved.push(p.event)
  170. }
  171. // Any rows past the preserved prefix are a never-committed torn tail; their
  172. // first seq is the deletion point for load's physical repair.
  173. return preserved.length < rows.length ? { preserved, tornFrom: preserved.length } : { preserved }
  174. }