schema.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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, SurfaceOp } 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 = 4
  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. /** JSON-encoded `number[]` — the event's sourceEventSeqs, or null. */
  39. source_event_seqs: string | null
  40. /** JSON-encoded `SurfaceOp` — how the event entered the surface, or null. */
  41. surface_op: string | null
  42. }
  43. /**
  44. * Journal modes the backend will run under. `wal` is the default and the
  45. * durability model the persistence ADR records; the rollback-journal modes
  46. * (`delete`/`truncate`/`persist`) exist for filesystems where WAL's
  47. * shared-memory files do not work (network mounts). `memory`/`off` are
  48. * excluded: dropping journal durability silently contradicts what this
  49. * backend promises.
  50. */
  51. export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist'
  52. /**
  53. * Open the database at `path` and apply the schema + pragmas. `foreign_keys`
  54. * makes `ON DELETE CASCADE` drop a session's events with its row; the
  55. * `journal_mode` pragma is set from the plugin's `journalMode` config (`wal`
  56. * default — the durability model the ADR records; the row shape maps 1:1
  57. * onto `SessionEvent`; opencode runs this exact shape on SQLite/WAL).
  58. *
  59. * The table-layout version is persisted in SQLite's `PRAGMA user_version` and
  60. * checked on open: a fresh database (user_version 0) is stamped with the
  61. * current {@link SCHEMA_VERSION}; an existing database whose version is NOT the
  62. * current one (written by a different, incompatible build — older or newer) is
  63. * REJECTED rather than opened against a layout this build does not understand.
  64. * There are no migrations: an earlier layout is not upgraded in place — it is
  65. * rejected. v1 had a different `sessions` shape; v2 lacked all of
  66. * `seed_length`/`source_event_seqs`/`surface_op`. v3 is SKIPPED: two unmerged
  67. * branches each shipped a DISTINCT v3 (one adding only `seed_length`, the other
  68. * adding only the surface columns), so an on-disk v3 is ambiguous — it could be
  69. * either sibling layout, neither of which has all of this build's columns. v4
  70. * is the merged layout carrying every column; bumping past the collided v3
  71. * makes the version check reject both sibling v3 databases instead of opening
  72. * one against columns it does not have.
  73. * @param path - the SQLite database file to open (created when absent).
  74. * @param journalMode - the journal pragma to apply — a closed in-code union, validated by the plugin Config.
  75. * @returns the open handle with pragmas applied and both tables ensured.
  76. */
  77. export function openDatabase(path: string, journalMode: JournalMode): DatabaseSync {
  78. const db = new DatabaseSync(path)
  79. db.exec('PRAGMA foreign_keys = ON')
  80. // journalMode is a closed in-code union (validated by the plugin Config), not
  81. // user-controlled SQL — safe to interpolate (PRAGMA takes no bound params).
  82. db.exec(`PRAGMA journal_mode = ${journalMode.toUpperCase()}`)
  83. // `PRAGMA user_version` always returns exactly one row { user_version }.
  84. const { user_version: onDisk } = db.prepare('PRAGMA user_version').get() as { user_version: number }
  85. if (onDisk !== 0 && onDisk !== SCHEMA_VERSION) {
  86. db.close()
  87. throw new Error(`session database at "${path}" has schema version ${onDisk}, incompatible with this build (${SCHEMA_VERSION})`)
  88. }
  89. if (onDisk === 0) {
  90. // Fresh (or pre-versioning) database: stamp the current layout version.
  91. // PRAGMA does not accept bound parameters, so interpolate the integer
  92. // constant (SCHEMA_VERSION is a trusted in-code number, not user input).
  93. db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`)
  94. }
  95. db.exec(`
  96. CREATE TABLE IF NOT EXISTS sessions (
  97. id TEXT PRIMARY KEY,
  98. version INTEGER NOT NULL,
  99. created_at INTEGER NOT NULL,
  100. cwd TEXT,
  101. parent_session TEXT,
  102. seed_length INTEGER
  103. ) STRICT
  104. `)
  105. db.exec(`
  106. CREATE TABLE IF NOT EXISTS events (
  107. session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
  108. seq INTEGER NOT NULL,
  109. type TEXT NOT NULL,
  110. time INTEGER NOT NULL,
  111. data TEXT NOT NULL,
  112. source_event_seqs TEXT,
  113. surface_op TEXT,
  114. PRIMARY KEY (session_id, seq)
  115. ) STRICT
  116. `)
  117. return db
  118. }
  119. /**
  120. * Reconstruct the {@link SessionHeader} from a `sessions` row.
  121. * @param row - the `sessions` table row.
  122. * @returns the header, `NULL` columns mapped to omitted optional fields.
  123. */
  124. export function rowToMeta(row: SessionRow): SessionHeader {
  125. return {
  126. version: row.version,
  127. id: row.id as SessionId,
  128. createdAt: row.created_at,
  129. ...row.cwd !== null ? { cwd: row.cwd } : {},
  130. ...row.parent_session !== null ? { parentSession: row.parent_session as SessionId } : {},
  131. ...row.seed_length !== null ? { seedLength: row.seed_length } : {},
  132. }
  133. }
  134. /**
  135. * Reconstruct a {@link SessionEvent} from an `events` row (parses `data`).
  136. * @param row - the `events` table row; `data` and the surface columns hold JSON text.
  137. * @returns the reconstructed event; throws when a JSON column fails to parse
  138. * ({@link scanRows} treats that as a hole, not corruption, in the tail).
  139. */
  140. export function rowToEvent(row: EventRow): SessionEvent {
  141. // Surface-metadata fields are conditional on the event type in the type
  142. // system; spread them so each variant gets only the fields it declares.
  143. const surfaceFields = {
  144. ...row.source_event_seqs !== null ? { sourceEventSeqs: JSON.parse(row.source_event_seqs) as number[] } : {},
  145. ...row.surface_op !== null ? { surfaceOp: JSON.parse(row.surface_op) as SurfaceOp } : {},
  146. }
  147. return {
  148. type: row.type as SessionEvent['type'],
  149. seq: row.seq,
  150. time: row.time,
  151. data: JSON.parse(row.data) as SessionEvent['data'],
  152. ...surfaceFields,
  153. } as SessionEvent
  154. }
  155. /**
  156. * The preserved prefix of an ordered event-row list (mirrors the JSONL
  157. * backend's `scanLog`): the longest prefix of complete, seq-contiguous,
  158. * parseable rows, PLUS the seq from which a never-committed torn tail must be
  159. * deleted (or `undefined` if the whole list is intact).
  160. *
  161. * A crash can leave a durable log whose final turn never closed: real,
  162. * fully-written rows sit after the last `turn/end`. Those are PRESERVED — a
  163. * single turn can be huge in a long-horizon task, so truncating it would
  164. * destroy real work; the backend closes the orphaned open turn with a synthetic
  165. * `turn/end {kind:'interrupted'}` on load (the session-persistence RFC). The ONLY thing excluded is
  166. * a torn trailing fragment — a row whose `data` never parses, or a seq gap —
  167. * AFTER the last committed `turn/end`; that bounds the preserved region and its
  168. * seq is returned as `tornFrom` so `load` can physically delete it.
  169. *
  170. * The last `turn/end` is computed from the `type` COLUMN (never parsing tail
  171. * `data`), so a malformed `data` in an uncommitted tail row is discarded rather
  172. * than making the session unloadable. A parse error or seq gap AT OR BEFORE the
  173. * last committed `turn/end` is committed-data corruption and throws.
  174. *
  175. * This relies on the session-log invariant that every event lives inside a turn
  176. * (`Session.append` enforces it): only the final turn can be open, so the
  177. * preserved tail is at most one unclosed turn.
  178. * @param rows - one session's event rows, ordered by seq ascending.
  179. * @returns the preserved event prefix, plus `tornFrom` — the seq the physical
  180. * delete starts at — when a torn tail exists.
  181. */
  182. export function scanRows(rows: readonly EventRow[]): { preserved: SessionEvent[]; tornFrom?: number } {
  183. // Pass 1: parse each row's data; a row whose data is not valid JSON is a hole.
  184. // (The seq/type COLUMNS are always present even when `data` is corrupt.)
  185. interface Parsed { ok: boolean; event?: SessionEvent }
  186. const parsed: Parsed[] = rows.map((row) => {
  187. try {
  188. return { ok: true, event: rowToEvent(row) }
  189. } catch {
  190. return { ok: false }
  191. }
  192. })
  193. // The last index that is a valid `turn/end` — the last fully-committed
  194. // boundary (the loop flushes only at turn/end).
  195. let lastTurnEnd = -1
  196. for (let i = parsed.length - 1; i >= 0; i--) {
  197. if (parsed[i]?.ok && rows[i]?.type === 'turn/end') { lastTurnEnd = i; break }
  198. }
  199. // Walk the longest PREFIX of complete, seq-contiguous, parseable rows
  200. // (row i has seq === i). This includes the fully-written rows of an
  201. // interrupted final turn AFTER the last turn/end — real work, never
  202. // truncated. The walk stops at the first hole:
  203. // - at or before the last committed turn/end → committed corruption (throw);
  204. // - after it (or no committed turn/end) → tolerated torn tail (stop).
  205. const preserved: SessionEvent[] = []
  206. for (let i = 0; i < rows.length; i++) {
  207. const p = parsed[i]
  208. if (!p?.ok || p.event === undefined) {
  209. if (i <= lastTurnEnd) throw new Error(`corrupt session log: unparsable committed event at seq ${rows[i]?.seq}`)
  210. break // torn tail fragment after the last turn/end — stop, tolerate
  211. }
  212. if (p.event.seq !== i) {
  213. if (i <= lastTurnEnd) throw new Error(`corrupt session log: seq gap in committed region (expected ${i}, got ${p.event.seq})`)
  214. break // gap after the last turn/end — torn tail, stop
  215. }
  216. preserved.push(p.event)
  217. }
  218. // Any rows past the preserved prefix are a never-committed torn tail; their
  219. // first seq is the deletion point for load's physical repair.
  220. return preserved.length < rows.length ? { preserved, tornFrom: preserved.length } : { preserved }
  221. }