index.ts 39 KB

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