index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /**
  2. * SQLite durable session-persistence backend. It maps each session header and
  3. * event to rows, and delegates write-path orchestration to
  4. * {@link PersistenceCoordinator}. It has no independent per-session artifact,
  5. * so its locator returns `undefined`.
  6. * @module @deepseek-ai/dsh-session-persistence-sqlite
  7. */
  8. import { Context } from 'cordis'
  9. import z from 'schemastery'
  10. import { randomUUID } from 'node:crypto'
  11. import { statSync } from 'node:fs'
  12. import { DatabaseSync } from 'node:sqlite'
  13. import { mkdir, open } from 'node:fs/promises'
  14. import { dirname, resolve } from 'node:path'
  15. import {
  16. DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS,
  17. SessionPersistence, SessionPersistenceRevision, PersistenceCoordinator,
  18. type PersistenceBackend, type SessionLocation, type SessionPersistenceSnapshot,
  19. type SessionInspection, type SessionPersistenceRevision as PersistenceRevision,
  20. type StoredPrefix, type StoredSuffix,
  21. } from '@deepseek-ai/dsh-session-persistence'
  22. import type { SessionEvent, SurfaceEventType, SessionId, SessionHeader, SessionPreparation } from '@deepseek-ai/dsh-session'
  23. import {
  24. type JournalMode, openDatabase, rowToMeta, scanRows, type EventRow, type SessionRow,
  25. } from './schema.ts'
  26. export { SCHEMA_VERSION } from './schema.ts'
  27. /**
  28. * Serialize an event's surface-metadata fields for SQL binding. Both fields are
  29. * nullable TEXT columns — null when the event has no surface metadata (non-surface
  30. * events, events written before surface support).
  31. */
  32. function surfaceBindings(event: SessionEvent): [string | null, string | null] {
  33. const se = event as SessionEvent<SurfaceEventType>
  34. return [
  35. se.sourceEventSeqs ? JSON.stringify(se.sourceEventSeqs) : null,
  36. se.surfaceOp !== undefined ? JSON.stringify(se.surfaceOp) : null,
  37. ]
  38. }
  39. /** Build the source-qualified revision shared by full and lightweight reads. */
  40. function sqliteRevision(storeIdentity: string, row: SessionRow): PersistenceRevision {
  41. return SessionPersistenceRevision(
  42. `${storeIdentity}:incarnation:${row.incarnation}:revision:${row.revision}`,
  43. )
  44. }
  45. /**
  46. * Exclusively create a missing database file with owner-only permissions.
  47. * Existing files retain their modes, and errors other than `EEXIST` propagate.
  48. * `DatabaseSync` reopens by path, so this does not protect confidentiality or
  49. * integrity when another principal can replace the database entry in its parent
  50. * directory.
  51. */
  52. async function createDatabaseFile(path: string): Promise<void> {
  53. try {
  54. const handle = await open(path, 'wx', 0o600)
  55. await handle.close()
  56. } catch (error) {
  57. if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
  58. }
  59. }
  60. /** Plugin configuration. */
  61. export interface Config {
  62. /**
  63. * Filesystem path to the SQLite database file. The special value `:memory:`
  64. * opens an in-process database (tests). On filesystems with POSIX modes,
  65. * missing directories and databases are created owner-only; existing path
  66. * modes are preserved. Filesystem setup errors other than an existing database
  67. * fail initialization. The backend does not protect confidentiality or
  68. * integrity when another principal can replace the database entry in its
  69. * parent directory.
  70. */
  71. path: string
  72. /**
  73. * SQLite `journal_mode` pragma. `wal` (the default) is the recorded
  74. * durability model; pick a rollback-journal mode (`delete`/`truncate`/
  75. * `persist`) on filesystems where WAL's shared-memory files do not work
  76. * (network mounts). See {@link JournalMode}.
  77. */
  78. journalMode?: JournalMode
  79. /** Maximum cold Session preparations retained for history-to-resume reuse. */
  80. preparedSessionCacheSize?: number
  81. /** Fixed live-event coalescing window; not a backend completion deadline. */
  82. writeBatchMaxDelayMs?: number
  83. }
  84. /**
  85. * The SQLite persistence backend. Load as a plugin; it registers as
  86. * `ctx.sessionPersistence` and (via the coordinator) installs the write-path
  87. * listeners. Its torn-tail marker is the seq to delete from.
  88. */
  89. export class SessionPersistenceSqlite extends SessionPersistence implements PersistenceBackend<number> {
  90. static inject = ['sessions']
  91. static Config: z<Config> = z.object({
  92. path: z.string().required(),
  93. journalMode: z.union(['wal', 'delete', 'truncate', 'persist'] as const).default('wal'),
  94. preparedSessionCacheSize: z.number().step(1).min(1).default(DEFAULT_PREPARED_SESSION_CACHE_SIZE),
  95. writeBatchMaxDelayMs: z.number().step(1).min(1).max(MAX_WRITE_BATCH_DELAY_MS)
  96. .default(DEFAULT_WRITE_BATCH_MAX_DELAY_MS),
  97. })
  98. /**
  99. * Backend label for the coordinator's dispose diagnostics. Intentionally
  100. * shadows cordis `Service.name` (set to `'sessionPersistence'` by the base);
  101. * see the JSONL backend for why this does not affect service resolution.
  102. */
  103. override readonly name = 'session-persistence-sqlite'
  104. private db!: DatabaseSync
  105. private storeIdentity!: string
  106. private ready: Promise<void>
  107. private coordinator: PersistenceCoordinator<number>
  108. constructor(ctx: Context, public config: Config) {
  109. super(ctx)
  110. // Programmatic wrappers may construct the backend without Schemastery normalization.
  111. const preparedSessionCacheSize = config.preparedSessionCacheSize
  112. ?? DEFAULT_PREPARED_SESSION_CACHE_SIZE
  113. const writeBatchMaxDelayMs = config.writeBatchMaxDelayMs
  114. ?? DEFAULT_WRITE_BATCH_MAX_DELAY_MS
  115. // Open asynchronously so directory creation does not block plugin apply;
  116. // every storage hook awaits the same readiness promise.
  117. this.ready = this.openDb(config.path, (config as Required<Config>).journalMode)
  118. this.coordinator = new PersistenceCoordinator<number>(this.ctx, this, {
  119. preparedSessionCacheSize,
  120. writeBatchMaxDelayMs,
  121. })
  122. }
  123. private async openDb(path: string, journalMode: JournalMode): Promise<void> {
  124. const actual = path === ':memory:' ? path : resolve(path)
  125. if (actual !== ':memory:') {
  126. await mkdir(dirname(actual), { recursive: true, mode: 0o700 })
  127. await createDatabaseFile(actual)
  128. }
  129. this.db = openDatabase(actual, journalMode)
  130. try {
  131. const row = this.db.prepare(
  132. 'SELECT store_id FROM persistence_state WHERE singleton = 1',
  133. ).get() as { store_id: string } | undefined
  134. /* v8 ignore next -- openDatabase inserts the singleton before returning. */
  135. if (row === undefined) {
  136. throw new Error(`session database at "${actual}" has no store identity`)
  137. }
  138. if (row.store_id.length === 0) {
  139. throw new Error(`session database at "${actual}" has no valid store identity`)
  140. }
  141. if (actual !== ':memory:') {
  142. const identity = statSync(actual, { bigint: true })
  143. this.storeIdentity = `file:${identity.dev}:${identity.ino}:${identity.birthtimeNs}:store:${row.store_id}`
  144. } else {
  145. this.storeIdentity = `memory:store:${row.store_id}`
  146. }
  147. } catch (error: unknown) {
  148. this.db.close()
  149. throw error
  150. }
  151. }
  152. // --- SessionPersistence service surface (delegated to the coordinator) ---
  153. /** SQLite has one database, not an independent local artifact per session. */
  154. locate(_meta: SessionHeader): SessionLocation | undefined {
  155. return undefined
  156. }
  157. create(meta: SessionHeader): Promise<void> {
  158. return this.coordinator.create(meta)
  159. }
  160. append(id: SessionId, events: readonly SessionEvent[]): Promise<void> {
  161. return this.coordinator.append(id, events)
  162. }
  163. override prepare(id: SessionId, signal?: AbortSignal): Promise<SessionPreparation> {
  164. return this.coordinator.prepare(id, signal)
  165. }
  166. load(id: SessionId): Promise<SessionInspection> {
  167. return this.coordinator.load(id)
  168. }
  169. inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection> {
  170. return this.coordinator.inspect(id, signal)
  171. }
  172. readFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  173. return this.coordinator.readFrom(id, fromSeq, signal)
  174. }
  175. // One method serves both public `list` and the backend hook; delegating it to
  176. // the coordinator would call this hook recursively.
  177. // --- PersistenceBackend hooks (the SQLite storage primitives) ---
  178. /** Read a stored prefix by id (ids are globally unique — no scope to scan). */
  179. loadStored(id: SessionId, signal?: AbortSignal): Promise<StoredPrefix<number> | undefined> {
  180. return this.readPrefix(id, signal)
  181. }
  182. /** Read one row's revision without loading its events. */
  183. async readStoredRevision(id: SessionId, signal?: AbortSignal): Promise<PersistenceRevision | undefined> {
  184. signal?.throwIfAborted()
  185. await this.ready
  186. signal?.throwIfAborted()
  187. const row = this.rowFor(id)
  188. return row === undefined ? undefined : sqliteRevision(this.storeIdentity, row)
  189. }
  190. /**
  191. * Seek-capable suffix read: SQL selects `seq >= fromSeq` directly, so the
  192. * read scales with the suffix, not the log. Torn rows past the preserved
  193. * region are dropped, never repaired (non-mutating read).
  194. */
  195. async loadStoredFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<StoredSuffix | undefined> {
  196. signal?.throwIfAborted()
  197. await this.ready
  198. signal?.throwIfAborted()
  199. const row = this.rowFor(id)
  200. if (row === undefined) return undefined
  201. const meta = rowToMeta(row)
  202. const eventRows = this.db
  203. .prepare('SELECT seq, type, time, data, source_event_seqs, surface_op FROM events WHERE session_id = ? AND seq >= ? ORDER BY seq')
  204. .all(id, fromSeq) as unknown as EventRow[]
  205. signal?.throwIfAborted()
  206. const { preserved } = scanRows(eventRows, fromSeq)
  207. return { meta, events: preserved }
  208. }
  209. /**
  210. * Read a session's row + ordered events into a {@link StoredPrefix}. The
  211. * torn-tail marker is the seq from which a never-committed tail must be deleted
  212. * (`scanRows` already returns it as `number | undefined`).
  213. */
  214. private async readPrefix(id: SessionId, signal?: AbortSignal): Promise<StoredPrefix<number> | undefined> {
  215. signal?.throwIfAborted()
  216. await this.ready
  217. signal?.throwIfAborted()
  218. this.db.exec('BEGIN')
  219. let snapshot: { row: SessionRow; eventRows: EventRow[] } | undefined
  220. try {
  221. const row = this.rowFor(id)
  222. if (row !== undefined) {
  223. const eventRows = this.db
  224. .prepare('SELECT seq, type, time, data, source_event_seqs, surface_op FROM events WHERE session_id = ? ORDER BY seq')
  225. .all(id) as unknown as EventRow[]
  226. snapshot = { row, eventRows }
  227. }
  228. this.db.exec('COMMIT')
  229. } catch (error: unknown) {
  230. /* v8 ignore start -- synchronous read failures only need transaction cleanup before propagation. */
  231. this.db.exec('ROLLBACK')
  232. throw error
  233. /* v8 ignore stop */
  234. }
  235. signal?.throwIfAborted()
  236. if (snapshot === undefined) return undefined
  237. const { row, eventRows } = snapshot
  238. const { preserved, tornFrom } = scanRows(eventRows)
  239. return {
  240. meta: rowToMeta(row),
  241. events: preserved,
  242. revision: sqliteRevision(this.storeIdentity, row),
  243. ...tornFrom !== undefined ? { tornMarker: tornFrom } : {},
  244. }
  245. }
  246. /**
  247. * Durably append a batch in ONE transaction: materialize the sessions row (if
  248. * lazy) and INSERT every event, or roll back entirely. The transaction is the
  249. * atomicity + durability boundary, so a mid-batch failure (a UNIQUE violation
  250. * on a duplicated seq) leaves the stored log untouched.
  251. */
  252. async appendBatch(meta: SessionHeader, events: readonly SessionEvent[], isMaterialized: boolean): Promise<void> {
  253. await this.ready
  254. const insertEvent = this.db.prepare(
  255. 'INSERT INTO events (session_id, seq, type, time, data, source_event_seqs, surface_op) VALUES (?, ?, ?, ?, ?, ?, ?)',
  256. )
  257. this.db.exec('BEGIN')
  258. try {
  259. if (!isMaterialized) this.writeRow(meta)
  260. for (const event of events) {
  261. const [surfaceSeqs, surfaceOp] = surfaceBindings(event)
  262. insertEvent.run(meta.id, event.seq, event.type, event.time, JSON.stringify(event.data), surfaceSeqs, surfaceOp)
  263. }
  264. this.db.prepare('UPDATE sessions SET revision = revision + 1 WHERE id = ?').run(meta.id)
  265. this.db.exec('COMMIT')
  266. } catch (error) {
  267. this.db.exec('ROLLBACK')
  268. throw error
  269. }
  270. }
  271. /**
  272. * Make a crash repair durable in ONE transaction: DELETE the torn tail (from
  273. * `tornMarker`) and INSERT the synthetic `closers`. After COMMIT the stored rows
  274. * == the balanced log.
  275. */
  276. async commitRepair(meta: SessionHeader, tornMarker: number | undefined, closers: readonly SessionEvent[]): Promise<void> {
  277. await this.ready
  278. this.db.exec('BEGIN')
  279. try {
  280. if (tornMarker !== undefined) {
  281. this.db.prepare('DELETE FROM events WHERE session_id = ? AND seq >= ?').run(meta.id, tornMarker)
  282. }
  283. if (closers.length > 0) {
  284. const insertEvent = this.db.prepare(
  285. 'INSERT INTO events (session_id, seq, type, time, data, source_event_seqs, surface_op) VALUES (?, ?, ?, ?, ?, ?, ?)',
  286. )
  287. for (const event of closers) {
  288. const [surfaceSeqs, surfaceOp] = surfaceBindings(event)
  289. insertEvent.run(meta.id, event.seq, event.type, event.time, JSON.stringify(event.data), surfaceSeqs, surfaceOp)
  290. }
  291. }
  292. if (tornMarker !== undefined || closers.length > 0) {
  293. this.db.prepare('UPDATE sessions SET revision = revision + 1 WHERE id = ?').run(meta.id)
  294. }
  295. this.db.exec('COMMIT')
  296. } catch (error) {
  297. // The DELETE+INSERT cannot collide (a row at a closer's seq is preserved or
  298. // deleted as torn first); this rolls back a DB-level failure (disk full,
  299. // etc.), unreachable in test.
  300. /* v8 ignore start */
  301. this.db.exec('ROLLBACK')
  302. throw error
  303. /* v8 ignore stop */
  304. }
  305. }
  306. /** List all materialized sessions' metadata (every row is a materialized session). */
  307. async list(signal?: AbortSignal): Promise<SessionHeader[]> {
  308. signal?.throwIfAborted()
  309. await this.ready
  310. signal?.throwIfAborted()
  311. const rows = this.db
  312. .prepare('SELECT * FROM sessions')
  313. .all() as unknown as SessionRow[]
  314. signal?.throwIfAborted()
  315. return rows.map(rowToMeta)
  316. }
  317. /** List metadata with a source-qualified monotonic revision per session. */
  318. async listSnapshots(signal?: AbortSignal): Promise<SessionPersistenceSnapshot[]> {
  319. signal?.throwIfAborted()
  320. await this.ready
  321. signal?.throwIfAborted()
  322. const rows = this.db.prepare('SELECT * FROM sessions').all() as unknown as SessionRow[]
  323. signal?.throwIfAborted()
  324. return rows.map(row => ({
  325. header: rowToMeta(row),
  326. revision: SessionPersistenceRevision(
  327. `${this.storeIdentity}:incarnation:${row.incarnation}:revision:${row.revision}`,
  328. ),
  329. }))
  330. }
  331. /** Close the database handle (awaited by the coordinator's dispose, post-drain). */
  332. async close(): Promise<void> {
  333. await this.ready
  334. this.db.close()
  335. }
  336. // --- row helpers ---
  337. /** Fetch a session's row, or undefined if absent. */
  338. private rowFor(id: SessionId): SessionRow | undefined {
  339. return this.db.prepare('SELECT * FROM sessions WHERE id = ?').get(id) as unknown as SessionRow | undefined
  340. }
  341. /**
  342. * Insert-or-replace a session's metadata row. The only caller is the first
  343. * materializing `appendBatch`, so writing the row IS the materialization (its
  344. * existence is the signal `list` reads).
  345. */
  346. private writeRow(meta: SessionHeader): void {
  347. this.db.prepare(`
  348. INSERT INTO sessions
  349. (id, version, created_at, cwd, parent_session, seed_length, origin, delegation_depth, incarnation, revision)
  350. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
  351. ON CONFLICT(id) DO UPDATE SET
  352. version = excluded.version,
  353. created_at = excluded.created_at,
  354. cwd = excluded.cwd,
  355. parent_session = excluded.parent_session,
  356. seed_length = excluded.seed_length,
  357. origin = excluded.origin,
  358. delegation_depth = excluded.delegation_depth
  359. `).run(
  360. meta.id,
  361. meta.version,
  362. meta.createdAt,
  363. meta.cwd ?? null,
  364. meta.parentSession ?? null,
  365. meta.seedLength ?? null,
  366. meta.origin ?? null,
  367. meta.delegationDepth ?? null,
  368. randomUUID(),
  369. )
  370. }
  371. }
  372. export default SessionPersistenceSqlite