schema.ts 9.1 KB

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