index.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. /**
  2. * SQLite FTS5 search over the live-preferred logical session corpus.
  3. *
  4. * @module @deepseek-ai/dsh-session-query-sqlite
  5. */
  6. import { createHash, randomUUID } from 'node:crypto'
  7. import { DatabaseSync } from 'node:sqlite'
  8. import { Context, type Fiber } from 'cordis'
  9. import z from 'schemastery'
  10. import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  11. import type SessionPersistence from '@deepseek-ai/dsh-session-persistence'
  12. import type {
  13. SessionPersistenceRevision,
  14. SessionPersistenceSnapshot,
  15. } from '@deepseek-ai/dsh-session-persistence'
  16. import {
  17. SessionQueryError,
  18. SessionSearchCursor,
  19. SessionSearchService,
  20. assertSessionHeadersCompatible,
  21. buildSessionEventSearchDocuments,
  22. } from '@deepseek-ai/dsh-session-query'
  23. import type {
  24. SessionEventSearchDocument,
  25. SessionEventSearchHit,
  26. SessionEventSearchRequest,
  27. SessionSearchExecContext,
  28. SessionSearchHit,
  29. SessionSearchCursor as SessionSearchCursorValue,
  30. SessionSearchPage,
  31. SessionSearchRequest,
  32. } from '@deepseek-ai/dsh-session-query'
  33. import {
  34. type JournalMode,
  35. openSearchDatabase,
  36. } from './schema.ts'
  37. import {
  38. type NormalizedEventRequest,
  39. type NormalizedSessionRequest,
  40. FTS_HIGHLIGHT_END,
  41. FTS_HIGHLIGHT_START,
  42. buildEventWhere,
  43. buildSessionWhere,
  44. makeSnippet,
  45. normalizeEventRequest,
  46. normalizeSessionRequest,
  47. quoteFtsData,
  48. requestFingerprint,
  49. sanitizeFtsText,
  50. SQLITE_MAX_PAGE_LIMIT,
  51. } from './query.ts'
  52. export {
  53. SESSION_QUERY_SQLITE_APPLICATION_ID,
  54. SESSION_QUERY_SQLITE_SCHEMA_VERSION,
  55. type JournalMode,
  56. } from './schema.ts'
  57. /** Default result page size. */
  58. export const SESSION_QUERY_SQLITE_DEFAULT_LIMIT = 20
  59. /** Maximum accepted result page size. */
  60. export const SESSION_QUERY_SQLITE_MAX_LIMIT = 100
  61. /** Default maximum snippet length in Unicode code points. */
  62. export const SESSION_QUERY_SQLITE_SNIPPET_CHARS = 240
  63. // A serialized search tolerates one transient source change; repeated churn
  64. // fails instead of monopolizing the operation queue.
  65. const STABLE_OBSERVATION_ATTEMPTS = 2
  66. /** SQLite session-search configuration. */
  67. export interface Config {
  68. /** Dedicated derived-index path; `:memory:` is supported for tests. */
  69. path: string
  70. /** SQLite journal mode. Defaults to `wal`. */
  71. journalMode?: JournalMode
  72. /** Page size when a request omits `limit`. At most `Number.MAX_SAFE_INTEGER - 1`; defaults to 20. */
  73. defaultLimit?: number
  74. /** Largest accepted page size. At most `Number.MAX_SAFE_INTEGER - 1`; defaults to 100. */
  75. maxLimit?: number
  76. /** Maximum snippet length in Unicode code points. Defaults to 240. */
  77. snippetChars?: number
  78. }
  79. interface ResolvedConfig {
  80. path: string
  81. journalMode: JournalMode
  82. defaultLimit: number
  83. maxLimit: number
  84. snippetChars: number
  85. }
  86. interface ObservedSession {
  87. header: SessionHeader
  88. documents: SessionEventSearchDocument[]
  89. fingerprint: string
  90. }
  91. interface ObservedPersistedSession {
  92. header: SessionHeader
  93. revision: SessionPersistenceRevision
  94. loaded?: ObservedSession
  95. }
  96. interface PersistenceBinding {
  97. readonly identity: symbol
  98. readonly service?: SessionPersistence
  99. }
  100. interface Observation {
  101. persistenceBinding: PersistenceBinding
  102. persisted: Map<SessionId, ObservedPersistedSession>
  103. live: Map<SessionId, ObservedSession>
  104. }
  105. interface IndexedPersistedRow {
  106. id: string
  107. revision: string
  108. generation: number
  109. }
  110. interface IndexedLiveRow {
  111. id: string
  112. fingerprint: string
  113. generation: number
  114. }
  115. interface SearchRow {
  116. session_id: string
  117. version: number
  118. created_at: number
  119. cwd: string | null
  120. parent_session: string | null
  121. seed_length: number | null
  122. live: number
  123. persisted: number
  124. seq: number
  125. type: string
  126. time: number
  127. surface: string
  128. marked_text: string
  129. match_count: number
  130. document_length: number
  131. }
  132. interface CursorPayload {
  133. version: 1
  134. instance: string
  135. scope: 'sessions' | 'events'
  136. fingerprint: string
  137. generation: string
  138. offset: number
  139. }
  140. /** Concrete SQLite owner of `ctx.sessionSearch`. */
  141. export class SessionSearchSqlite extends SessionSearchService {
  142. static inject = ['sessions']
  143. static Config: z<Config> = z.object({
  144. path: z.string().required(),
  145. journalMode: z.union(['wal', 'delete', 'truncate', 'persist'] as const).default('wal'),
  146. defaultLimit: z.number().step(1).min(1).max(SQLITE_MAX_PAGE_LIMIT).default(SESSION_QUERY_SQLITE_DEFAULT_LIMIT),
  147. maxLimit: z.number().step(1).min(1).max(SQLITE_MAX_PAGE_LIMIT).default(SESSION_QUERY_SQLITE_MAX_LIMIT),
  148. snippetChars: z.number().step(1).min(1).default(SESSION_QUERY_SQLITE_SNIPPET_CHARS),
  149. })
  150. /** Validated and defaulted backend configuration. */
  151. readonly config: ResolvedConfig
  152. private readonly _instance = randomUUID()
  153. private readonly _ready: Promise<void>
  154. private _db: DatabaseSync | undefined
  155. private _persistenceBinding: PersistenceBinding = { identity: Symbol() }
  156. private _lastPersistenceIdentity: symbol | undefined
  157. private _persistenceEpoch = 0
  158. private _globalGeneration = 0
  159. private _localGeneration = 0
  160. private _tail: Promise<void> = Promise.resolve()
  161. private _closed = false
  162. private _closePromise: Promise<void> | undefined
  163. private readonly _optionalPersistenceFiber: Fiber
  164. constructor(ctx: Context, config: Config) {
  165. super(ctx)
  166. this.config = resolveConfig(config)
  167. this._ready = this._open()
  168. // Attach a rejection observer immediately; callers still receive the same
  169. // rejection from `_ready`, including when no search is ever attempted.
  170. void this._ready.catch(() => undefined)
  171. this._optionalPersistenceFiber = ctx.inject(['sessionPersistence'], (childCtx: Context) => {
  172. const service = childCtx.sessionPersistence
  173. const binding = { identity: Symbol(), service }
  174. this._persistenceBinding = binding
  175. childCtx.effect(() => () => {
  176. /* v8 ignore next -- a stale optional-service disposer cannot clear a replacement */
  177. if (this._persistenceBinding !== binding) return
  178. this._persistenceBinding = { identity: Symbol() }
  179. }, 'sessionSearchSqlite.persistenceBinding')
  180. })
  181. ctx.effect(() => {
  182. return () => this._optionalPersistenceFiber.dispose()
  183. }, 'sessionSearchSqlite.optionalPersistence')
  184. ctx.effect(() => async () => this.close(), 'sessionSearchSqlite.close')
  185. }
  186. override async searchSessions(
  187. request: SessionSearchRequest,
  188. exec?: SessionSearchExecContext,
  189. ): Promise<SessionSearchPage<SessionSearchHit>> {
  190. const normalized = normalizeSessionRequest(request, this.config)
  191. const signal = exec?.signal
  192. return this._serialized(signal, async () => {
  193. await this._ensureReady(signal)
  194. const persistenceBinding = await this._reconcile(signal)
  195. assertNotAborted(signal)
  196. const generation = String(this._globalGeneration)
  197. const fingerprint = requestFingerprint(normalized)
  198. const offset = normalized.cursor === undefined
  199. ? 0
  200. : decodeCursor(normalized.cursor, this._instance, 'sessions', fingerprint, generation)
  201. const rows = this._querySessions(normalized, offset, persistenceBinding)
  202. return page(rows, normalized.limit, row => this._sessionHit(row), cursorOffset => encodeCursor({
  203. version: 1,
  204. instance: this._instance,
  205. scope: 'sessions',
  206. fingerprint,
  207. generation,
  208. offset: cursorOffset,
  209. }), offset)
  210. })
  211. }
  212. override async searchEvents(
  213. request: SessionEventSearchRequest,
  214. exec?: SessionSearchExecContext,
  215. ): Promise<SessionSearchPage<SessionEventSearchHit>> {
  216. const normalized = normalizeEventRequest(request, this.config)
  217. const signal = exec?.signal
  218. return this._serialized(signal, async () => {
  219. await this._ensureReady(signal)
  220. const persistenceBinding = await this._reconcile(signal)
  221. assertNotAborted(signal)
  222. const generation = this._targetGeneration(normalized.sessionId, persistenceBinding)
  223. const fingerprint = requestFingerprint(normalized)
  224. const offset = normalized.cursor === undefined
  225. ? 0
  226. : decodeCursor(normalized.cursor, this._instance, 'events', fingerprint, generation)
  227. const rows = this._queryEvents(normalized, offset, persistenceBinding)
  228. return page(rows, normalized.limit, row => this._eventHit(row), cursorOffset => encodeCursor({
  229. version: 1,
  230. instance: this._instance,
  231. scope: 'events',
  232. fingerprint,
  233. generation,
  234. offset: cursorOffset,
  235. }), offset)
  236. })
  237. }
  238. /** Close the database after every accepted operation reaches quiescence. */
  239. close(): Promise<void> {
  240. this._closePromise ??= this._close()
  241. return this._closePromise
  242. }
  243. private async _close(): Promise<void> {
  244. this._closed = true
  245. await this._tail
  246. try {
  247. await this._ready
  248. } catch {
  249. // Opening already closed a partially-created handle; disposal only waits.
  250. }
  251. this._db?.close()
  252. this._db = undefined
  253. }
  254. private async _open(): Promise<void> {
  255. this._db = await openSearchDatabase(this.config.path, this.config.journalMode)
  256. const state = this._db.prepare(
  257. 'SELECT global_generation FROM search_state WHERE singleton = 1',
  258. ).get() as { global_generation: number }
  259. this._globalGeneration = state.global_generation
  260. this._localGeneration = state.global_generation
  261. }
  262. private async _ensureReady(signal: AbortSignal | undefined): Promise<void> {
  263. try {
  264. await waitWithAbort(this._ready, signal)
  265. } catch (error: unknown) {
  266. if (isAbort(error)) throw error
  267. throw new SessionQueryError(
  268. `session-search SQLite index failed to open: ${errorMessage(error)}`,
  269. 'SESSION_QUERY_INDEX_FAILED',
  270. { cause: error },
  271. )
  272. }
  273. }
  274. private async _serialized<T>(signal: AbortSignal | undefined, operation: () => Promise<T>): Promise<T> {
  275. if (this._isClosed()) throw indexClosed()
  276. let release!: () => void
  277. const gate = new Promise<void>((resolve) => { release = resolve })
  278. const prior = this._tail
  279. this._tail = prior.then(() => gate)
  280. try {
  281. await waitWithAbort(prior, signal)
  282. } catch (error: unknown) {
  283. release()
  284. throw error
  285. }
  286. if (this._isClosed()) {
  287. release()
  288. throw indexClosed()
  289. }
  290. try {
  291. assertNotAborted(signal)
  292. return await operation()
  293. } finally {
  294. release()
  295. }
  296. }
  297. private async _reconcile(signal: AbortSignal | undefined): Promise<PersistenceBinding> {
  298. const db = this._requireDb()
  299. const persistedRows = db.prepare(
  300. 'SELECT id, revision, generation FROM persisted_sessions',
  301. ).all() as unknown as IndexedPersistedRow[]
  302. const liveRows = db.prepare(
  303. 'SELECT id, fingerprint, generation FROM temp.live_sessions',
  304. ).all() as unknown as IndexedLiveRow[]
  305. const persistedById = new Map(persistedRows.map(row => [row.id as SessionId, row]))
  306. const liveById = new Map(liveRows.map(row => [row.id as SessionId, row]))
  307. const observation = await this._observeStable(persistedById, signal)
  308. assertNotAborted(signal)
  309. const persistentChanges = observation.persistenceBinding.service === undefined
  310. ? []
  311. : [...observation.persisted.values()].filter(entry => entry.loaded !== undefined)
  312. const persistentDeletes = observation.persistenceBinding.service === undefined
  313. ? []
  314. : persistedRows.filter(row => !observation.persisted.has(row.id as SessionId))
  315. const liveChanges = [...observation.live.values()].filter(entry => liveById.get(entry.header.id)?.fingerprint !== entry.fingerprint)
  316. const liveDeletes = liveRows.filter(row => !observation.live.has(row.id as SessionId))
  317. const pointerChanged = this._lastPersistenceIdentity !== undefined
  318. && this._lastPersistenceIdentity !== observation.persistenceBinding.identity
  319. const hasWrites = persistentChanges.length > 0
  320. || persistentDeletes.length > 0
  321. || liveChanges.length > 0
  322. || liveDeletes.length > 0
  323. let nextMainGeneration = this._mainGeneration()
  324. let nextLocalGeneration = this._localGeneration
  325. if (persistentChanges.length > 0 || persistentDeletes.length > 0) nextMainGeneration += 1
  326. const liveReplacements = liveChanges.map((entry) => {
  327. nextLocalGeneration = Math.max(nextLocalGeneration, nextMainGeneration) + 1
  328. return { entry, generation: nextLocalGeneration }
  329. })
  330. if (hasWrites) {
  331. let began = false
  332. try {
  333. db.exec('BEGIN IMMEDIATE')
  334. began = true
  335. for (const row of persistentDeletes) this._deleteSession('persisted', row.id as SessionId)
  336. for (const entry of persistentChanges) {
  337. /* v8 ignore next -- observation loads every entry whose revision differs */
  338. if (entry.loaded === undefined) throw new Error(`missing loaded revision for session "${entry.header.id}"`)
  339. this._replacePersistedSession(entry.loaded, entry.revision, nextMainGeneration)
  340. }
  341. if (persistentChanges.length > 0 || persistentDeletes.length > 0) {
  342. db.prepare('UPDATE search_state SET global_generation = ? WHERE singleton = 1').run(nextMainGeneration)
  343. }
  344. for (const row of liveDeletes) this._deleteSession('live', row.id as SessionId)
  345. for (const { entry, generation } of liveReplacements) {
  346. this._replaceLiveSession(entry, generation)
  347. }
  348. db.exec('COMMIT')
  349. } catch (error: unknown) {
  350. /* v8 ignore next -- a BEGIN failure has no transaction to roll back; the common wrapper still reports it. */
  351. if (began) {
  352. /* v8 ignore next 5 -- ROLLBACK failure requires a SQLite double fault; the original failure remains actionable. */
  353. try {
  354. db.exec('ROLLBACK')
  355. } catch {
  356. // The original SQLite failure remains the actionable cause.
  357. }
  358. }
  359. throw new SessionQueryError(
  360. `session-search reconciliation failed: ${errorMessage(error)}`,
  361. 'SESSION_QUERY_INDEX_FAILED',
  362. { cause: error },
  363. )
  364. }
  365. }
  366. if (hasWrites || pointerChanged) this._globalGeneration += 1
  367. if (pointerChanged) this._persistenceEpoch += 1
  368. this._localGeneration = nextLocalGeneration
  369. this._lastPersistenceIdentity = observation.persistenceBinding.identity
  370. return observation.persistenceBinding
  371. }
  372. private async _observeStable(
  373. indexed: ReadonlyMap<SessionId, IndexedPersistedRow>,
  374. signal: AbortSignal | undefined,
  375. ): Promise<Observation> {
  376. for (let attempt = 0; attempt < STABLE_OBSERVATION_ATTEMPTS; attempt += 1) {
  377. assertNotAborted(signal)
  378. const persistenceBinding = this._persistenceBinding
  379. const persistence = persistenceBinding.service
  380. let persisted = new Map<SessionId, ObservedPersistedSession>()
  381. if (persistence !== undefined) {
  382. try {
  383. const canReuseIndexed = this._lastPersistenceIdentity === undefined
  384. || this._lastPersistenceIdentity === persistenceBinding.identity
  385. const before = await waitWithAbort(persistence.listSnapshots(), signal)
  386. persisted = materializePersistenceSnapshots(before)
  387. for (const entry of persisted.values()) {
  388. if (canReuseIndexed && indexed.get(entry.header.id)?.revision === entry.revision) continue
  389. const loaded = await waitWithAbort(persistence.load(entry.header.id), signal)
  390. assertSessionHeadersCompatible(entry.header, loaded.meta)
  391. entry.loaded = observeSession(loaded.meta, loaded.events)
  392. }
  393. const after = materializePersistenceSnapshots(
  394. await waitWithAbort(persistence.listSnapshots(), signal),
  395. )
  396. if (!samePersistenceSnapshots(persisted, after)) continue
  397. if (this._persistenceBinding !== persistenceBinding) continue
  398. } catch (error: unknown) {
  399. if (isAbort(error) || signal?.aborted) {
  400. throw new SessionQueryError('session-search aborted', 'SESSION_QUERY_ABORTED', {
  401. cause: error,
  402. })
  403. }
  404. if (this._persistenceBinding !== persistenceBinding) continue
  405. if (error instanceof SessionQueryError) throw error
  406. throw new SessionQueryError(
  407. `session-search persistence observation failed: ${errorMessage(error)}`,
  408. 'SESSION_QUERY_PERSISTENCE_FAILED',
  409. { cause: error },
  410. )
  411. }
  412. }
  413. const live = new Map<SessionId, ObservedSession>()
  414. for (const session of this.ctx.sessions.list()) {
  415. const observed = observeLive(session)
  416. const durable = persisted.get(session.id)
  417. if (durable !== undefined) assertSessionHeadersCompatible(observed.header, durable.header)
  418. live.set(session.id, observed)
  419. }
  420. if (this._persistenceBinding === persistenceBinding) {
  421. return { persistenceBinding, persisted, live }
  422. }
  423. }
  424. throw new SessionQueryError(
  425. 'session-search persistence observation did not stabilize after one retry',
  426. 'SESSION_QUERY_PERSISTENCE_FAILED',
  427. )
  428. }
  429. private _mainGeneration(): number {
  430. const row = this._requireDb().prepare(
  431. 'SELECT global_generation FROM search_state WHERE singleton = 1',
  432. ).get() as { global_generation: number }
  433. return row.global_generation
  434. }
  435. private _deleteSession(source: 'persisted' | 'live', id: SessionId): void {
  436. const db = this._requireDb()
  437. if (source === 'persisted') {
  438. db.prepare('DELETE FROM persisted_docs WHERE session_id = ?').run(id)
  439. db.prepare('DELETE FROM persisted_sessions WHERE id = ?').run(id)
  440. } else {
  441. db.prepare('DELETE FROM temp.live_docs WHERE session_id = ?').run(id)
  442. db.prepare('DELETE FROM temp.live_sessions WHERE id = ?').run(id)
  443. }
  444. }
  445. private _replacePersistedSession(
  446. entry: ObservedSession,
  447. revision: SessionPersistenceRevision,
  448. generation: number,
  449. ): void {
  450. this._deleteSession('persisted', entry.header.id)
  451. const db = this._requireDb()
  452. db.prepare(`
  453. INSERT INTO persisted_sessions
  454. (id, version, created_at, cwd, parent_session, seed_length, revision, generation)
  455. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  456. `).run(
  457. entry.header.id,
  458. entry.header.version,
  459. entry.header.createdAt,
  460. entry.header.cwd ?? null,
  461. entry.header.parentSession ?? null,
  462. entry.header.seedLength ?? null,
  463. revision,
  464. generation,
  465. )
  466. const insert = db.prepare(`
  467. INSERT INTO persisted_docs (text, session_id, seq, type, time, surface, codepoint_length)
  468. VALUES (?, ?, ?, ?, ?, ?, ?)
  469. `)
  470. for (const document of entry.documents) {
  471. const text = sanitizeFtsText(document.text)
  472. insert.run(
  473. text,
  474. document.sessionId,
  475. document.seq,
  476. document.type,
  477. document.time,
  478. document.surface,
  479. Array.from(text).length,
  480. )
  481. }
  482. }
  483. private _replaceLiveSession(entry: ObservedSession, generation: number): void {
  484. this._deleteSession('live', entry.header.id)
  485. const db = this._requireDb()
  486. db.prepare(`
  487. INSERT INTO temp.live_sessions
  488. (id, version, created_at, cwd, parent_session, seed_length, fingerprint, generation)
  489. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  490. `).run(
  491. entry.header.id,
  492. entry.header.version,
  493. entry.header.createdAt,
  494. entry.header.cwd ?? null,
  495. entry.header.parentSession ?? null,
  496. entry.header.seedLength ?? null,
  497. entry.fingerprint,
  498. generation,
  499. )
  500. const insert = db.prepare(`
  501. INSERT INTO temp.live_docs (text, session_id, seq, type, time, surface, codepoint_length)
  502. VALUES (?, ?, ?, ?, ?, ?, ?)
  503. `)
  504. for (const document of entry.documents) {
  505. const text = sanitizeFtsText(document.text)
  506. insert.run(
  507. text,
  508. document.sessionId,
  509. document.seq,
  510. document.type,
  511. document.time,
  512. document.surface,
  513. Array.from(text).length,
  514. )
  515. }
  516. }
  517. private _querySessions(
  518. request: NormalizedSessionRequest,
  519. offset: number,
  520. persistenceBinding: PersistenceBinding,
  521. ): SearchRow[] {
  522. const selected = selectedDocumentsSql()
  523. const sessionWhere = buildSessionWhere(request.sessionFilters)
  524. const eventWhere = buildEventWhere(request.eventFilters)
  525. const where = [sessionWhere.sql, eventWhere.sql].filter(Boolean).join(' AND ')
  526. const bindings = [
  527. ...selectedDocumentsParams(request.query, persistenceBinding.service !== undefined),
  528. ...sessionWhere.params,
  529. ...eventWhere.params,
  530. request.limit + 1,
  531. offset,
  532. ]
  533. assertPortableBindingCount(bindings)
  534. return this._requireDb().prepare(`
  535. ${selected.sql},
  536. filtered AS (
  537. SELECT * FROM matched ${where.length === 0 ? '' : `WHERE ${where}`}
  538. ),
  539. ranked AS (
  540. SELECT *, ROW_NUMBER() OVER (
  541. PARTITION BY session_id
  542. ORDER BY match_count DESC, document_length ASC, time DESC, seq DESC
  543. ) AS event_rank
  544. FROM filtered
  545. )
  546. SELECT * FROM ranked
  547. WHERE event_rank = 1
  548. ORDER BY match_count DESC, document_length ASC, time DESC, session_id ASC, seq DESC
  549. LIMIT ? OFFSET ?
  550. `).all(...bindings) as unknown as SearchRow[]
  551. }
  552. private _queryEvents(
  553. request: NormalizedEventRequest,
  554. offset: number,
  555. persistenceBinding: PersistenceBinding,
  556. ): SearchRow[] {
  557. const selected = selectedDocumentsSql()
  558. const eventWhere = buildEventWhere(request.filters)
  559. const where = ['session_id = ?', eventWhere.sql].filter(Boolean).join(' AND ')
  560. const bindings = [
  561. ...selectedDocumentsParams(request.query, persistenceBinding.service !== undefined),
  562. request.sessionId,
  563. ...eventWhere.params,
  564. request.limit + 1,
  565. offset,
  566. ]
  567. assertPortableBindingCount(bindings)
  568. return this._requireDb().prepare(`
  569. ${selected.sql}
  570. SELECT * FROM matched
  571. WHERE ${where}
  572. ORDER BY match_count DESC, document_length ASC, time DESC, seq DESC
  573. LIMIT ? OFFSET ?
  574. `).all(...bindings) as unknown as SearchRow[]
  575. }
  576. private _targetGeneration(sessionId: SessionId, persistenceBinding: PersistenceBinding): string {
  577. const db = this._requireDb()
  578. const live = db.prepare(
  579. 'SELECT generation FROM temp.live_sessions WHERE id = ?',
  580. ).get(sessionId) as { generation: number } | undefined
  581. if (live !== undefined) return `live:${live.generation}`
  582. if (persistenceBinding.service !== undefined) {
  583. const persisted = db.prepare(
  584. 'SELECT generation FROM persisted_sessions WHERE id = ?',
  585. ).get(sessionId) as { generation: number } | undefined
  586. if (persisted !== undefined) return `persisted:${this._persistenceEpoch}:${persisted.generation}`
  587. }
  588. throw new SessionQueryError(
  589. `session "${sessionId}" not found`,
  590. 'SESSION_QUERY_SESSION_NOT_FOUND',
  591. )
  592. }
  593. private _sessionHit(row: SearchRow): SessionSearchHit {
  594. return {
  595. header: rowHeader(row),
  596. live: row.live === 1,
  597. persisted: row.persisted === 1,
  598. bestMatch: this._eventHit(row),
  599. }
  600. }
  601. private _eventHit(row: SearchRow): SessionEventSearchHit {
  602. return {
  603. sessionId: row.session_id as SessionId,
  604. seq: row.seq,
  605. type: row.type as SessionEventSearchHit['type'],
  606. time: row.time,
  607. surface: row.surface as SessionEventSearchHit['surface'],
  608. snippet: makeSnippet(row.marked_text, this.config.snippetChars),
  609. }
  610. }
  611. private _requireDb(): DatabaseSync {
  612. /* v8 ignore next -- callers await `_ready`; this guards lifecycle misuse */
  613. if (this._db === undefined) throw indexClosed()
  614. return this._db
  615. }
  616. private _isClosed(): boolean {
  617. return this._closed
  618. }
  619. }
  620. function selectedDocumentsSql(): { sql: string } {
  621. return {
  622. sql: `WITH candidates AS (
  623. SELECT
  624. pd.session_id AS session_id,
  625. ps.version AS version,
  626. ps.created_at AS created_at,
  627. ps.cwd AS cwd,
  628. ps.parent_session AS parent_session,
  629. ps.seed_length AS seed_length,
  630. 0 AS live,
  631. 1 AS persisted,
  632. CAST(pd.seq AS INTEGER) AS seq,
  633. pd.type AS type,
  634. CAST(pd.time AS INTEGER) AS time,
  635. pd.surface AS surface,
  636. highlight(persisted_docs, 0, ?, ?) AS marked_text,
  637. CAST(pd.codepoint_length AS INTEGER) AS document_length
  638. FROM persisted_docs AS pd
  639. JOIN persisted_sessions AS ps ON ps.id = pd.session_id
  640. WHERE persisted_docs MATCH ?
  641. AND ? = 1
  642. AND NOT EXISTS (SELECT 1 FROM temp.live_sessions AS ls WHERE ls.id = pd.session_id)
  643. UNION ALL
  644. SELECT
  645. ld.session_id AS session_id,
  646. ls.version AS version,
  647. ls.created_at AS created_at,
  648. ls.cwd AS cwd,
  649. ls.parent_session AS parent_session,
  650. ls.seed_length AS seed_length,
  651. 1 AS live,
  652. CASE WHEN ? = 1 AND EXISTS (
  653. SELECT 1 FROM persisted_sessions AS ps WHERE ps.id = ld.session_id
  654. ) THEN 1 ELSE 0 END AS persisted,
  655. CAST(ld.seq AS INTEGER) AS seq,
  656. ld.type AS type,
  657. CAST(ld.time AS INTEGER) AS time,
  658. ld.surface AS surface,
  659. highlight(live_docs, 0, ?, ?) AS marked_text,
  660. CAST(ld.codepoint_length AS INTEGER) AS document_length
  661. FROM temp.live_docs AS ld
  662. JOIN temp.live_sessions AS ls ON ls.id = ld.session_id
  663. WHERE live_docs MATCH ?
  664. ), matched AS (
  665. SELECT *,
  666. (
  667. length(CAST(marked_text AS BLOB))
  668. - length(CAST(replace(marked_text, ?, '') AS BLOB))
  669. ) / ? AS match_count
  670. FROM candidates
  671. )`,
  672. }
  673. }
  674. function selectedDocumentsParams(query: string, persistenceVisible: boolean): Array<string | number> {
  675. const expression = quoteFtsData(query)
  676. const visible = persistenceVisible ? 1 : 0
  677. return [
  678. FTS_HIGHLIGHT_START,
  679. FTS_HIGHLIGHT_END,
  680. expression,
  681. visible,
  682. visible,
  683. FTS_HIGHLIGHT_START,
  684. FTS_HIGHLIGHT_END,
  685. expression,
  686. FTS_HIGHLIGHT_START,
  687. Buffer.byteLength(FTS_HIGHLIGHT_START, 'utf8'),
  688. ]
  689. }
  690. // SQLite builds may raise this ceiling; supported modern versions share 32,766
  691. // as the portable host-parameter limit.
  692. const SQLITE_PORTABLE_VARIABLE_LIMIT = 32_766
  693. function assertPortableBindingCount(bindings: readonly (string | number)[]): void {
  694. if (bindings.length > SQLITE_PORTABLE_VARIABLE_LIMIT) {
  695. throw new SessionQueryError(
  696. `session-search request requires ${bindings.length} SQLite bindings; reduce filters to stay within the portable ${SQLITE_PORTABLE_VARIABLE_LIMIT}-variable limit`,
  697. 'SESSION_QUERY_INVALID_FILTER',
  698. )
  699. }
  700. }
  701. function observeLive(session: Session): ObservedSession {
  702. return observeSession(session.header, session.events)
  703. }
  704. function observeSession(header: SessionHeader, events: readonly SessionEvent[]): ObservedSession {
  705. const detachedHeader = structuredClone(header)
  706. const detachedEvents = events.map(event => structuredClone(event))
  707. return {
  708. header: detachedHeader,
  709. documents: buildSessionEventSearchDocuments(detachedHeader.id, detachedEvents),
  710. fingerprint: createHash('sha256')
  711. .update(JSON.stringify({ header: detachedHeader, events: detachedEvents }))
  712. .digest('base64url'),
  713. }
  714. }
  715. function materializePersistenceSnapshots(
  716. snapshots: readonly SessionPersistenceSnapshot[],
  717. ): Map<SessionId, ObservedPersistedSession> {
  718. if (!isRuntimeArray(snapshots)) throw new Error('persistence snapshots must be an array')
  719. const result = new Map<SessionId, ObservedPersistedSession>()
  720. for (const snapshot of snapshots) {
  721. if (typeof snapshot.revision !== 'string') {
  722. throw new Error('persistence snapshot revision must be a string')
  723. }
  724. const header = structuredClone(snapshot.header)
  725. if (result.has(header.id)) {
  726. throw new Error(`persistence listed duplicate session "${header.id}"`)
  727. }
  728. result.set(header.id, { header, revision: snapshot.revision })
  729. }
  730. return result
  731. }
  732. function samePersistenceSnapshots(
  733. before: ReadonlyMap<SessionId, ObservedPersistedSession>,
  734. after: ReadonlyMap<SessionId, ObservedPersistedSession>,
  735. ): boolean {
  736. if (before.size !== after.size) return false
  737. for (const [id, first] of before) {
  738. const second = after.get(id)
  739. if (
  740. second === undefined
  741. || first.revision !== second.revision
  742. || !sameHeader(first.header, second.header)
  743. ) return false
  744. }
  745. return true
  746. }
  747. function sameHeader(a: SessionHeader, b: SessionHeader): boolean {
  748. return a.version === b.version
  749. && a.id === b.id
  750. && a.createdAt === b.createdAt
  751. && a.cwd === b.cwd
  752. && a.parentSession === b.parentSession
  753. && a.seedLength === b.seedLength
  754. }
  755. function rowHeader(row: SearchRow): SessionHeader {
  756. return {
  757. version: row.version,
  758. id: row.session_id as SessionId,
  759. createdAt: row.created_at,
  760. ...row.cwd === null ? {} : { cwd: row.cwd },
  761. ...row.parent_session === null ? {} : { parentSession: row.parent_session as SessionId },
  762. ...row.seed_length === null ? {} : { seedLength: row.seed_length },
  763. }
  764. }
  765. function page<Row, Item>(
  766. rows: readonly Row[],
  767. limit: number,
  768. convert: (row: Row) => Item,
  769. nextCursor: (offset: number) => SessionSearchCursorValue,
  770. offset: number,
  771. ): SessionSearchPage<Item> {
  772. const hasMore = rows.length > limit
  773. return {
  774. items: rows.slice(0, limit).map(convert),
  775. ...hasMore ? { nextCursor: nextCursor(offset + limit) } : {},
  776. }
  777. }
  778. function encodeCursor(payload: CursorPayload): SessionSearchCursorValue {
  779. return SessionSearchCursor(Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url'))
  780. }
  781. function decodeCursor(
  782. cursor: SessionSearchCursorValue,
  783. instance: string,
  784. scope: CursorPayload['scope'],
  785. fingerprint: string,
  786. generation: string,
  787. ): number {
  788. let decoded: Partial<CursorPayload>
  789. try {
  790. decoded = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<CursorPayload>
  791. } catch (error: unknown) {
  792. throw invalidCursor(error)
  793. }
  794. if (
  795. decoded.version !== 1
  796. || decoded.instance !== instance
  797. || decoded.scope !== scope
  798. || decoded.fingerprint !== fingerprint
  799. || !Number.isSafeInteger(decoded.offset)
  800. || decoded.offset === undefined
  801. || decoded.offset < 0
  802. ) {
  803. throw invalidCursor(new Error('cursor does not belong to this normalized request'))
  804. }
  805. if (decoded.generation !== generation) {
  806. throw new SessionQueryError(
  807. 'session-search cursor is stale because its relevant corpus changed',
  808. 'SESSION_QUERY_STALE_CURSOR',
  809. )
  810. }
  811. return decoded.offset
  812. }
  813. function invalidCursor(cause: unknown): SessionQueryError {
  814. return new SessionQueryError(
  815. 'session-search cursor is invalid',
  816. 'SESSION_QUERY_INVALID_CURSOR',
  817. { cause },
  818. )
  819. }
  820. function resolveConfig(config: Config): ResolvedConfig {
  821. const resolved: ResolvedConfig = {
  822. path: config.path,
  823. journalMode: config.journalMode ?? 'wal',
  824. defaultLimit: config.defaultLimit ?? SESSION_QUERY_SQLITE_DEFAULT_LIMIT,
  825. maxLimit: config.maxLimit ?? SESSION_QUERY_SQLITE_MAX_LIMIT,
  826. snippetChars: config.snippetChars ?? SESSION_QUERY_SQLITE_SNIPPET_CHARS,
  827. }
  828. if (typeof resolved.path !== 'string' || resolved.path.trim().length === 0) {
  829. throw invalidConfig('path must not be blank')
  830. }
  831. assertPageLimit('defaultLimit', resolved.defaultLimit)
  832. assertPageLimit('maxLimit', resolved.maxLimit)
  833. assertPositiveInteger('snippetChars', resolved.snippetChars)
  834. if (resolved.defaultLimit > resolved.maxLimit) {
  835. throw invalidConfig('defaultLimit must be less than or equal to maxLimit')
  836. }
  837. const journalModes: readonly string[] = ['wal', 'delete', 'truncate', 'persist']
  838. if (!journalModes.includes(resolved.journalMode)) throw invalidConfig('journalMode is not supported')
  839. return resolved
  840. }
  841. function assertPositiveInteger(name: string, value: number): void {
  842. if (!Number.isInteger(value) || value < 1) throw invalidConfig(`${name} must be a positive integer`)
  843. }
  844. function assertPageLimit(name: string, value: number): void {
  845. if (!Number.isSafeInteger(value) || value < 1 || value > SQLITE_MAX_PAGE_LIMIT) {
  846. throw invalidConfig(`${name} must be an integer between 1 and ${SQLITE_MAX_PAGE_LIMIT}`)
  847. }
  848. }
  849. function invalidConfig(detail: string): SessionQueryError {
  850. return new SessionQueryError(
  851. `session-search SQLite config: ${detail}`,
  852. 'SESSION_QUERY_INVALID_CONFIG',
  853. )
  854. }
  855. function indexClosed(): SessionQueryError {
  856. return new SessionQueryError('session-search SQLite index is closed', 'SESSION_QUERY_INDEX_FAILED')
  857. }
  858. function assertNotAborted(signal: AbortSignal | undefined): void {
  859. if (signal?.aborted) {
  860. throw new SessionQueryError('session-search aborted', 'SESSION_QUERY_ABORTED')
  861. }
  862. }
  863. function waitWithAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
  864. if (signal === undefined) return promise
  865. if (signal.aborted) return Promise.reject(new SessionQueryError('session-search aborted', 'SESSION_QUERY_ABORTED'))
  866. return new Promise<T>((resolve, reject) => {
  867. const onAbort = () => {
  868. reject(new SessionQueryError('session-search aborted', 'SESSION_QUERY_ABORTED'))
  869. }
  870. signal.addEventListener('abort', onAbort, { once: true })
  871. promise.then(
  872. (value) => {
  873. signal.removeEventListener('abort', onAbort)
  874. resolve(value)
  875. },
  876. (error: unknown) => {
  877. signal.removeEventListener('abort', onAbort)
  878. reject(asError(error))
  879. },
  880. )
  881. })
  882. }
  883. function isAbort(error: unknown): boolean {
  884. return error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED'
  885. }
  886. function asError(error: unknown): Error {
  887. return error instanceof Error
  888. ? error
  889. : new Error('session-search dependency rejected with a non-Error value', { cause: error })
  890. }
  891. function errorMessage(error: unknown): string {
  892. return error instanceof Error ? error.message : 'unknown error'
  893. }
  894. function isRuntimeArray(value: unknown): boolean {
  895. return Array.isArray(value)
  896. }
  897. export default SessionSearchSqlite