index.ts 38 KB

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