index.ts 15 KB

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