sqlite.spec.ts 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  1. import { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { Context, type Fiber } from '@deepseek-ai/cordis'
  4. import { DatabaseSync } from 'node:sqlite'
  5. import { chmod, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
  6. import { tmpdir } from 'node:os'
  7. import { dirname, join } from 'node:path'
  8. import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
  9. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  10. import type { SessionEvent, SessionHeader, SessionId as SessionIdType } from '@deepseek-ai/dsh-session'
  11. import SessionPersistence, { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence'
  12. import type { SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence'
  13. import SqliteSessionPersistence from '@deepseek-ai/dsh-session-persistence-sqlite'
  14. import SqliteSessionQueryEngine, {
  15. SESSION_QUERY_SQLITE_SCHEMA_VERSION,
  16. } from '@deepseek-ai/dsh-session-query-sqlite'
  17. import {
  18. SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY,
  19. SessionQueryError,
  20. SessionSearchCursor,
  21. type SessionAvailability,
  22. type SessionQueryErrorCode,
  23. type SessionSearchRequest,
  24. } from '@deepseek-ai/dsh-session-query'
  25. const temporaryDirectories: string[] = []
  26. afterEach(async () => {
  27. for (const directory of temporaryDirectories.splice(0)) {
  28. await rm(directory, { recursive: true, force: true })
  29. }
  30. })
  31. async function temporaryPath(name = 'search.db'): Promise<string> {
  32. const directory = await mkdtemp(join(tmpdir(), 'dsh-session-search-'))
  33. temporaryDirectories.push(directory)
  34. return join(directory, name)
  35. }
  36. function header(id: string, createdAt = 1, extra: Partial<SessionHeader> = {}): SessionHeader {
  37. return { version: SESSION_FORMAT_VERSION, id: SessionId(id), createdAt, ...extra }
  38. }
  39. function messageEvents(text: string, time = 1): SessionEvent[] {
  40. return [{
  41. type: 'user/message',
  42. seq: 0,
  43. time,
  44. data: createUserMessage({
  45. content: [{ type: 'text', text }], source: { kind: 'user' },
  46. }),
  47. surfaceOp: 'append',
  48. }]
  49. }
  50. function expectCode(code: SessionQueryErrorCode): Error {
  51. return expect.objectContaining({ code }) as Error
  52. }
  53. function replaceCursorOffset(
  54. cursor: ReturnType<typeof SessionSearchCursor>,
  55. offset: number,
  56. ): ReturnType<typeof SessionSearchCursor> {
  57. const payload = JSON.parse(
  58. Buffer.from(cursor, 'base64url').toString('utf8'),
  59. ) as Record<string, unknown>
  60. return SessionSearchCursor(Buffer.from(JSON.stringify({ ...payload, offset }), 'utf8').toString('base64url'))
  61. }
  62. class TestPersistence extends SessionPersistence {
  63. override readonly supportsRawArtifacts = false
  64. static entries = new Map<SessionIdType, { meta: SessionHeader; events: SessionEvent[] }>()
  65. static revisions = new Map<SessionIdType, number>()
  66. static nextRevision = 0
  67. static loads = new Map<SessionIdType, number>()
  68. static inspections = new Map<SessionIdType, number>()
  69. static inspectSignals: Array<AbortSignal | undefined> = []
  70. static snapshotSignals: Array<AbortSignal | undefined> = []
  71. static loadEffect: ((entry: { meta: SessionHeader; events: SessionEvent[] }) => void) | undefined
  72. static inspectEffect: ((
  73. entry: { meta: SessionHeader; events: SessionEvent[] },
  74. signal?: AbortSignal,
  75. ) => void | Promise<void>) | undefined
  76. static listGate: Promise<void> | undefined
  77. static listStarted: (() => void) | undefined
  78. static snapshotEffect: ((signal?: AbortSignal) => void | Promise<void>) | undefined
  79. static snapshotOverride: (() => SessionPersistenceSnapshot[]) | undefined
  80. static failure: unknown
  81. locate(_meta: SessionHeader): undefined {
  82. return undefined
  83. }
  84. static reset(entries: readonly { meta: SessionHeader; events: SessionEvent[] }[] = []): void {
  85. this.entries = new Map()
  86. this.revisions = new Map()
  87. this.loads = new Map()
  88. this.inspections = new Map()
  89. this.inspectSignals = []
  90. this.snapshotSignals = []
  91. this.loadEffect = undefined
  92. this.inspectEffect = undefined
  93. for (const entry of entries) this.set(entry)
  94. this.listGate = undefined
  95. this.listStarted = undefined
  96. this.snapshotEffect = undefined
  97. this.snapshotOverride = undefined
  98. this.failure = undefined
  99. }
  100. static set(entry: { meta: SessionHeader; events: SessionEvent[] }): void {
  101. this.entries.set(entry.meta.id, structuredClone(entry))
  102. this.revisions.set(entry.meta.id, ++this.nextRevision)
  103. }
  104. create(meta: SessionHeader): Promise<void> {
  105. TestPersistence.set({ meta, events: [] })
  106. return Promise.resolve()
  107. }
  108. append(id: SessionIdType, events: readonly SessionEvent[]): Promise<void> {
  109. const entry = TestPersistence.entries.get(id)
  110. if (entry === undefined) return Promise.reject(new Error('missing test session'))
  111. entry.events.push(...structuredClone(events))
  112. TestPersistence.revisions.set(id, ++TestPersistence.nextRevision)
  113. return Promise.resolve()
  114. }
  115. async load(id: SessionIdType): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  116. TestPersistence.loads.set(id, (TestPersistence.loads.get(id) ?? 0) + 1)
  117. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  118. const entry = TestPersistence.entries.get(id)
  119. if (entry === undefined) throw new Error('missing test session')
  120. if (TestPersistence.loadEffect !== undefined) {
  121. const effect = TestPersistence.loadEffect
  122. TestPersistence.loadEffect = undefined
  123. effect(entry)
  124. TestPersistence.revisions.set(id, ++TestPersistence.nextRevision)
  125. }
  126. return structuredClone(entry)
  127. }
  128. async inspect(id: SessionIdType, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  129. TestPersistence.inspections.set(id, (TestPersistence.inspections.get(id) ?? 0) + 1)
  130. TestPersistence.inspectSignals.push(signal)
  131. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  132. const entry = TestPersistence.entries.get(id)
  133. if (entry === undefined) throw new Error('missing test session')
  134. await TestPersistence.inspectEffect?.(entry, signal)
  135. TestPersistence.inspectEffect = undefined
  136. return structuredClone(entry)
  137. }
  138. async readFrom(id: SessionIdType, fromSeq: number, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  139. const whole = await this.inspect(id, signal)
  140. return { meta: whole.meta, events: whole.events.filter(event => event.seq >= fromSeq) }
  141. }
  142. async list(): Promise<SessionHeader[]> {
  143. TestPersistence.listStarted?.()
  144. await TestPersistence.listGate
  145. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  146. return [...TestPersistence.entries.values()].map(entry => structuredClone(entry.meta))
  147. }
  148. async listSnapshots(signal?: AbortSignal): Promise<SessionPersistenceSnapshot[]> {
  149. TestPersistence.snapshotSignals.push(signal)
  150. TestPersistence.listStarted?.()
  151. await TestPersistence.listGate
  152. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  153. const snapshots = TestPersistence.snapshotOverride?.()
  154. ?? [...TestPersistence.entries.values()].map(entry => ({
  155. header: structuredClone(entry.meta),
  156. revision: SessionPersistenceRevision(`test:${TestPersistence.revisions.get(entry.meta.id)}`),
  157. }))
  158. await TestPersistence.snapshotEffect?.(signal)
  159. return snapshots
  160. }
  161. }
  162. async function liveContext(config: ConstructorParameters<typeof SqliteSessionQueryEngine>[1] = { path: ':memory:' }): Promise<Context> {
  163. const ctx = new Context()
  164. await ctx.plugin(SessionStore)
  165. await ctx.plugin(SessionProjectionRegistry)
  166. await ctx.plugin(SqliteSessionQueryEngine, config)
  167. return ctx
  168. }
  169. describe('SQLite session search', () => {
  170. it('defaults and validates opening policy and persisted inspection concurrency through its Cordis config', async () => {
  171. const defaultCtx = await liveContext()
  172. expect((defaultCtx.sessionQuery as SqliteSessionQueryEngine).config.openAt).toBe('startup')
  173. expect((defaultCtx.sessionQuery as SqliteSessionQueryEngine).config.persistedInspectConcurrency)
  174. .toBe(SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY)
  175. const configuredValue = 2
  176. const configured = new SqliteSessionQueryEngine.Config({
  177. path: ':memory:',
  178. openAt: 'first-search',
  179. persistedInspectConcurrency: configuredValue,
  180. })
  181. expect(configured.openAt).toBe('first-search')
  182. expect(configured.persistedInspectConcurrency).toBe(configuredValue)
  183. const configuredCtx = await liveContext(configured)
  184. expect((configuredCtx.sessionQuery as SqliteSessionQueryEngine).config.persistedInspectConcurrency)
  185. .toBe(configuredValue)
  186. for (const persistedInspectConcurrency of [0, Number.MAX_SAFE_INTEGER + 1]) {
  187. expect(() => new SqliteSessionQueryEngine.Config({
  188. path: ':memory:',
  189. persistedInspectConcurrency,
  190. })).toThrow()
  191. }
  192. expect(() => new SqliteSessionQueryEngine.Config({
  193. path: ':memory:',
  194. openAt: 'later' as never,
  195. })).toThrow()
  196. })
  197. it('mounts and disposes first-search mode without opening its database', async () => {
  198. const path = await temporaryPath('unopened.db')
  199. const ctx = new Context()
  200. await ctx.plugin(SessionStore)
  201. await ctx.plugin(SessionProjectionRegistry)
  202. const search = await ctx.plugin(SqliteSessionQueryEngine, {
  203. path,
  204. openAt: 'first-search',
  205. })
  206. await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
  207. await search.dispose()
  208. await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
  209. })
  210. it('refuses search in never mode while inherited reads and traces keep working', async () => {
  211. const path = await temporaryPath('never-mode.db')
  212. const ctx = new Context()
  213. await ctx.plugin(SessionStore)
  214. await ctx.plugin(SessionProjectionRegistry)
  215. const search = await ctx.plugin(SqliteSessionQueryEngine, { path, openAt: 'never' })
  216. const service = ctx.sessionQuery as SqliteSessionQueryEngine
  217. expect(service.config.openAt).toBe('never')
  218. const parent = SessionId('never-parent')
  219. const child = SessionId('never-child')
  220. ctx.sessions.create(parent, { seed: messageEvents('never opened needle'), meta: { createdAt: 10 } })
  221. ctx.sessions.create(child, { meta: { parentSession: parent, createdAt: 20 } })
  222. await expect(service.searchSessions({ query: 'needle' }))
  223. .rejects.toThrow(expectCode('SESSION_QUERY_SEARCH_DISABLED'))
  224. await expect(service.searchEvents({ sessionId: parent, query: 'needle' }))
  225. .rejects.toThrow(expectCode('SESSION_QUERY_SEARCH_DISABLED'))
  226. expect((await service.listSessions()).map(record => record.header.id).sort())
  227. .toEqual([child, parent])
  228. const lineage = await service.traceSession(parent)
  229. expect(lineage.complete).toBe(true)
  230. expect(lineage.descendants.map(node => node.session.header.id)).toEqual([child])
  231. // The disabled index never touches the filesystem, in mount, use, or disposal.
  232. await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
  233. await search.dispose()
  234. await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
  235. })
  236. it('opens once on the first search and reuses readiness for later searches', async () => {
  237. const ctx = new Context()
  238. await ctx.plugin(SessionStore)
  239. await ctx.plugin(SessionProjectionRegistry)
  240. await ctx.plugin(SqliteSessionQueryEngine, {
  241. path: ':memory:',
  242. openAt: 'first-search',
  243. })
  244. const service = ctx.sessionQuery as SqliteSessionQueryEngine
  245. const internals = service as unknown as { _open(): Promise<void> }
  246. const open = vi.spyOn(internals, '_open')
  247. await expect(service.searchSessions({ query: 'first' })).resolves.toEqual({ items: [] })
  248. await expect(service.searchSessions({ query: 'second' })).resolves.toEqual({ items: [] })
  249. expect(open).toHaveBeenCalledOnce()
  250. })
  251. it('shares one readiness promise across concurrent first searches', async () => {
  252. const ctx = new Context()
  253. await ctx.plugin(SessionStore)
  254. await ctx.plugin(SessionProjectionRegistry)
  255. await ctx.plugin(SqliteSessionQueryEngine, {
  256. path: ':memory:',
  257. openAt: 'first-search',
  258. })
  259. const service = ctx.sessionQuery as SqliteSessionQueryEngine
  260. const internals = service as unknown as { _open(): Promise<void> }
  261. const originalOpen = internals._open.bind(internals)
  262. const release = Promise.withResolvers<undefined>()
  263. const started = Promise.withResolvers<undefined>()
  264. const open = vi.spyOn(internals, '_open').mockImplementation(async () => {
  265. started.resolve(undefined)
  266. await release.promise
  267. await originalOpen()
  268. })
  269. const first = service.searchSessions({ query: 'first' })
  270. const second = service.searchSessions({ query: 'second' })
  271. await started.promise
  272. expect(open).toHaveBeenCalledOnce()
  273. release.resolve(undefined)
  274. await expect(Promise.all([first, second])).resolves.toEqual([
  275. { items: [] },
  276. { items: [] },
  277. ])
  278. expect(open).toHaveBeenCalledOnce()
  279. })
  280. it('searches two-character Unicode61 tokens in live-only sessions', async () => {
  281. const ctx = await liveContext({ path: ':memory:', snippetChars: 20 })
  282. const session = ctx.sessions.create(SessionId('live'), {
  283. // agentPreset rides along: the index rebuilds the header a caller reads,
  284. // and a session listed under the wrong composition is a lie about what it
  285. // ran. The full-header comparison below is what pins every column.
  286. meta: { cwd: '/work', createdAt: 10, seedLength: 1, delegationDepth: 2, agentPreset: 'minimal' },
  287. })
  288. session.append(
  289. 'user/message',
  290. createUserMessage({
  291. content: [{ type: 'text', text: 'An AI helper' }], source: { kind: 'user' },
  292. }),
  293. { surfaceOp: 'append' },
  294. )
  295. await expect(ctx.sessionQuery.searchEvents({ sessionId: session.id, query: 'AI' }))
  296. .resolves.toMatchObject({
  297. session: { ...session.header, seedLength: 1 },
  298. items: [{ sessionId: session.id, seq: 0, snippet: 'An AI helper' }],
  299. })
  300. await expect(ctx.sessionQuery.searchSessions({ query: 'AI' }))
  301. .resolves.toMatchObject({ items: [{ header: { ...session.header, seedLength: 1 }, live: true, persisted: false }] })
  302. })
  303. it('excludes assistant reasoning while indexing visible answer text', async () => {
  304. const ctx = await liveContext()
  305. const session = ctx.sessions.create(SessionId('reasoning'))
  306. session.append(
  307. 'assistant/message',
  308. {
  309. turn: 1,
  310. step: 1,
  311. message: createAssistantMessage({
  312. content: [
  313. { type: 'reasoning', text: 'private-chain-marker' },
  314. { type: 'text', text: 'visible-answer-marker' },
  315. ],
  316. source: { provider: 'mock', model: 'mock' },
  317. }),
  318. },
  319. { surfaceOp: 'append' },
  320. )
  321. await expect(ctx.sessionQuery.searchSessions({ query: 'private-chain-marker' }))
  322. .resolves.toEqual({ items: [] })
  323. await expect(ctx.sessionQuery.searchSessions({ query: 'visible-answer-marker' }))
  324. .resolves.toMatchObject({
  325. items: [{
  326. header: { id: session.id },
  327. bestMatch: { snippet: 'visible-answer-marker' },
  328. }],
  329. })
  330. })
  331. it('searches all surfaces by default and applies metadata before ranking', async () => {
  332. const ctx = await liveContext({ path: ':memory:', defaultLimit: 10, maxLimit: 20 })
  333. const parent = SessionId('parent')
  334. const events: SessionEvent[] = [
  335. { type: 'user/message', seq: 0, time: 10, data: createUserMessage({
  336. content: [{ type: 'text', text: 'needle original' }], source: { kind: 'user' },
  337. }), surfaceOp: 'append' },
  338. { type: 'assistant/chunk', seq: 1, time: 11, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'needle raw' } } },
  339. { type: 'user/message', seq: 2, time: 12, data: createUserMessage({
  340. content: [{ type: 'text', text: 'needle summary' }], source: { kind: 'plugin', plugin: 'test' },
  341. }), surfaceOp: { op: 'replace', start: 0, end: 0 }, sourceEventSeqs: [0] },
  342. { type: 'turn/end', seq: 3, time: 13, data: { turn: 1, reason: { kind: 'error', error: { message: 'needle failure', code: 'UNKNOWN' } } } },
  343. ]
  344. ctx.sessions.create(SessionId('a'), { seed: events, meta: { cwd: '/a', parentSession: parent, createdAt: 20 } })
  345. ctx.sessions.create(SessionId('b'), { seed: messageEvents('needle peer', 12), meta: { createdAt: 20 } })
  346. const all = await ctx.sessionQuery.searchEvents({ sessionId: SessionId('a'), query: 'needle' })
  347. expect(new Set(all.items.map(item => item.surface))).toEqual(new Set(['current', 'shadowed', 'log-only']))
  348. await expect(ctx.sessionQuery.searchEvents({
  349. sessionId: SessionId('a'),
  350. query: 'needle',
  351. filters: [
  352. { kind: 'seq', from: 2, to: 2 },
  353. { kind: 'time', from: 12, to: 12 },
  354. { kind: 'type', values: ['user/message'] },
  355. { kind: 'surface', values: ['current'] },
  356. ],
  357. })).resolves.toMatchObject({ items: [{ seq: 2, surface: 'current' }] })
  358. const grouped = await ctx.sessionQuery.searchSessions({
  359. query: 'needle',
  360. sessionFilters: [
  361. { kind: 'id', values: [SessionId('a')] },
  362. { kind: 'cwd', values: ['/a'] },
  363. { kind: 'created-at', from: 20, to: 20 },
  364. { kind: 'parent', values: [parent] },
  365. { kind: 'availability', values: ['live'] },
  366. ],
  367. eventFilters: [{ kind: 'surface', values: ['shadowed'] }],
  368. })
  369. expect(grouped.items).toHaveLength(1)
  370. expect(grouped.items[0]).toMatchObject({
  371. header: { id: SessionId('a'), cwd: '/a', parentSession: parent },
  372. live: true,
  373. persisted: false,
  374. bestMatch: { seq: 0, surface: 'shadowed' },
  375. })
  376. })
  377. it('searches at the supported FTS5 outer-predicate boundary in both scopes', async () => {
  378. const ctx = await liveContext()
  379. const session = ctx.sessions.create(SessionId('predicate-boundary'), {
  380. seed: messageEvents('needle'),
  381. meta: { cwd: '/work' },
  382. })
  383. const sessionFilters = Array.from(
  384. { length: 14 },
  385. () => ({ kind: 'cwd' as const, values: ['/work', null] }),
  386. )
  387. const eventFilters = Array.from(
  388. { length: 13 },
  389. () => ({ kind: 'type' as const, values: ['user/message' as const] }),
  390. )
  391. await expect(ctx.sessionQuery.searchSessions({ query: 'needle', sessionFilters }))
  392. .resolves.toMatchObject({ items: [{ header: { id: session.id } }] })
  393. await expect(ctx.sessionQuery.searchEvents({
  394. sessionId: session.id,
  395. query: 'needle',
  396. filters: eventFilters,
  397. })).resolves.toMatchObject({ items: [{ sessionId: session.id, seq: 0 }] })
  398. })
  399. it('rejects unsupported FTS5 outer-predicate counts with typed errors', async () => {
  400. const ctx = await liveContext()
  401. const session = ctx.sessions.create(SessionId('predicate-limit'), { seed: messageEvents('needle') })
  402. const sessionFilters = Array.from(
  403. { length: 1_100 },
  404. () => ({ kind: 'id' as const, values: [session.id] }),
  405. )
  406. const eventFilters = Array.from(
  407. { length: 1_100 },
  408. () => ({ kind: 'type' as const, values: ['user/message' as const] }),
  409. )
  410. await expect(ctx.sessionQuery.searchSessions({ query: 'needle', sessionFilters }))
  411. .rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  412. await expect(ctx.sessionQuery.searchEvents({
  413. sessionId: session.id,
  414. query: 'needle',
  415. filters: eventFilters,
  416. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  417. await expect(ctx.sessionQuery.searchSessions({
  418. query: 'needle',
  419. sessionFilters: sessionFilters.slice(0, 7),
  420. eventFilters: eventFilters.slice(0, 8),
  421. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  422. await expect(ctx.sessionQuery.searchEvents({
  423. sessionId: session.id,
  424. query: 'needle',
  425. filters: eventFilters.slice(0, 14),
  426. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  427. })
  428. it('uses literal phrase tokens, stable ties, and bounded Unicode snippets', async () => {
  429. const ctx = await liveContext({ path: ':memory:', defaultLimit: 10, maxLimit: 10, snippetChars: 5 })
  430. ctx.sessions.create(SessionId('a'), { seed: messageEvents('😀😀 alpha beta BRAID 😀😀', 10), meta: { createdAt: 1 } })
  431. ctx.sessions.create(SessionId('b'), { seed: messageEvents('alpha beta', 10), meta: { createdAt: 1 } })
  432. ctx.sessions.create(SessionId('c'), { seed: messageEvents('alpha middle beta', 10), meta: { createdAt: 1 } })
  433. ctx.sessions.create(SessionId('d'), { seed: messageEvents('alpha beta', 10), meta: { createdAt: 1 } })
  434. ctx.sessions.create(SessionId('operator'), { seed: messageEvents('needle OR absent', 10), meta: { createdAt: 1 } })
  435. ctx.sessions.create(SessionId('only'), { seed: messageEvents('needle only', 10), meta: { createdAt: 1 } })
  436. ctx.sessions.create(SessionId('quote'), { seed: messageEvents('say "needle" exactly', 10), meta: { createdAt: 1 } })
  437. const phrase = await ctx.sessionQuery.searchSessions({ query: 'alpha beta' })
  438. expect(phrase.items.map(item => item.header.id)).toEqual([SessionId('b'), SessionId('d'), SessionId('a')])
  439. expect(phrase.items.every(item => Array.from(item.bestMatch.snippet).length <= 5)).toBe(true)
  440. await expect(ctx.sessionQuery.searchSessions({ query: 'AI' })).resolves.toEqual({ items: [] })
  441. await expect(ctx.sessionQuery.searchSessions({ query: 'needle OR absent' }))
  442. .resolves.toMatchObject({ items: [{ header: { id: SessionId('operator') } }] })
  443. await expect(ctx.sessionQuery.searchSessions({ query: 'say "needle"' }))
  444. .resolves.toMatchObject({ items: [{ header: { id: SessionId('quote') } }] })
  445. await expect(ctx.sessionQuery.searchSessions({ query: '*' })).resolves.toEqual({ items: [] })
  446. })
  447. it('ranks live and persisted matches on one source-comparable contract', async () => {
  448. const persisted = header('z-persisted')
  449. TestPersistence.reset([
  450. { meta: persisted, events: messageEvents('needle needle', 10) },
  451. ...Array.from({ length: 12 }, (_, index) => ({
  452. meta: header(`filler-${index}`),
  453. events: messageEvents('needle', 10),
  454. })),
  455. ])
  456. const ctx = await liveContext()
  457. const persistence = await ctx.plugin(TestPersistence)
  458. ctx.sessions.create(SessionId('a-live'), {
  459. seed: messageEvents('needle needle', 10),
  460. meta: { createdAt: persisted.createdAt },
  461. })
  462. const result = await ctx.sessionQuery.searchSessions({
  463. query: 'needle',
  464. sessionFilters: [{ kind: 'id', values: [SessionId('a-live'), persisted.id] }],
  465. })
  466. expect(result.items.map(item => item.header.id)).toEqual([SessionId('a-live'), persisted.id])
  467. await persistence.dispose()
  468. })
  469. it('positions snippets from FTS5 matches across diacritics and punctuation', async () => {
  470. const ctx = await liveContext({ path: ':memory:', snippetChars: 14 })
  471. const session = ctx.sessions.create(SessionId('snippet'), {
  472. seed: messageEvents('long long long—café,\nnext value', 10),
  473. })
  474. const page = await ctx.sessionQuery.searchEvents({ sessionId: session.id, query: 'CAFE' })
  475. expect(page.items).toHaveLength(1)
  476. expect(page.items[0]!.snippet).toContain('café')
  477. expect(page.items[0]!.snippet).toContain('—')
  478. expect(page.items[0]!.snippet).not.toContain('\n')
  479. expect(Array.from(page.items[0]!.snippet).length).toBeLessThanOrEqual(14)
  480. })
  481. it('binds cursors to requests and only invalidates within-session pages for target changes', async () => {
  482. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 5 })
  483. const target = ctx.sessions.create(SessionId('target'), {
  484. seed: [
  485. ...messageEvents('needle one', 10),
  486. { ...messageEvents('needle two', 11)[0]!, seq: 1 },
  487. { ...messageEvents('needle three', 12)[0]!, seq: 2 },
  488. ],
  489. })
  490. ctx.sessions.create(SessionId('other'), { seed: messageEvents('needle other', 10) })
  491. const eventPage = await ctx.sessionQuery.searchEvents({ sessionId: target.id, query: 'needle', limit: 1 })
  492. const sessionPage = await ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1 })
  493. expect(eventPage.nextCursor).toEqual(expect.any(String))
  494. expect(sessionPage.nextCursor).toEqual(expect.any(String))
  495. if (eventPage.nextCursor === undefined || sessionPage.nextCursor === undefined) throw new Error('expected cursors')
  496. const unsafeOffsetCursor = replaceCursorOffset(eventPage.nextCursor, 1e100)
  497. await expect(ctx.sessionQuery.searchEvents({
  498. sessionId: target.id,
  499. query: 'needle',
  500. limit: 1,
  501. cursor: unsafeOffsetCursor,
  502. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  503. const eventKeys = eventPage.items.map(item => `${item.sessionId}:${item.seq}`)
  504. let eventCursor: ReturnType<typeof SessionSearchCursor> | undefined = eventPage.nextCursor
  505. while (eventCursor !== undefined) {
  506. const next = await ctx.sessionQuery.searchEvents({
  507. sessionId: target.id,
  508. query: 'needle',
  509. limit: 1,
  510. cursor: eventCursor,
  511. })
  512. eventKeys.push(...next.items.map(item => `${item.sessionId}:${item.seq}`))
  513. eventCursor = next.nextCursor
  514. }
  515. expect(eventKeys).toHaveLength(3)
  516. expect(new Set(eventKeys).size).toBe(eventKeys.length)
  517. const sessionIds = sessionPage.items.map(item => item.header.id)
  518. let sessionCursor: ReturnType<typeof SessionSearchCursor> | undefined = sessionPage.nextCursor
  519. while (sessionCursor !== undefined) {
  520. const next = await ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1, cursor: sessionCursor })
  521. sessionIds.push(...next.items.map(item => item.header.id))
  522. sessionCursor = next.nextCursor
  523. }
  524. expect(sessionIds).toHaveLength(2)
  525. expect(new Set(sessionIds).size).toBe(sessionIds.length)
  526. ctx.sessions.create(SessionId('unrelated'), { seed: messageEvents('needle unrelated', 20) })
  527. await expect(ctx.sessionQuery.searchEvents({
  528. sessionId: target.id,
  529. query: 'needle',
  530. limit: 1,
  531. cursor: eventPage.nextCursor,
  532. })).resolves.toMatchObject({ items: [{ sessionId: target.id }] })
  533. await expect(ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1, cursor: sessionPage.nextCursor }))
  534. .rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  535. await expect(ctx.sessionQuery.searchEvents({
  536. sessionId: target.id,
  537. query: 'different',
  538. limit: 1,
  539. cursor: eventPage.nextCursor,
  540. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  541. target.append('user/message', createUserMessage({
  542. content: [{ type: 'text', text: 'needle four' }], source: { kind: 'user' },
  543. }), { surfaceOp: 'append' })
  544. await expect(ctx.sessionQuery.searchEvents({
  545. sessionId: target.id,
  546. query: 'needle',
  547. limit: 1,
  548. cursor: eventPage.nextCursor,
  549. })).rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  550. })
  551. it('invalidates session cursors after transient persistence topology changes', async () => {
  552. TestPersistence.reset()
  553. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 5 })
  554. ctx.sessions.create(SessionId('first'), { seed: messageEvents('needle first') })
  555. ctx.sessions.create(SessionId('second'), { seed: messageEvents('needle second') })
  556. const page = await ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1 })
  557. if (page.nextCursor === undefined) throw new Error('expected cursor')
  558. const persistence = await ctx.plugin(TestPersistence)
  559. await persistence.dispose()
  560. await expect(ctx.sessionQuery.searchSessions({
  561. query: 'needle',
  562. limit: 1,
  563. cursor: page.nextCursor,
  564. })).rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  565. })
  566. it('rejects invalid requests, filters, cursors, and direct config', async () => {
  567. const ctx = await liveContext({ path: ':memory:', defaultLimit: 2, maxLimit: 3 })
  568. const session = ctx.sessions.create(SessionId('valid'), { seed: messageEvents('needle') })
  569. for (const request of [
  570. { sessionId: session.id, query: '' },
  571. { sessionId: session.id, query: 'needle', limit: 0 },
  572. { sessionId: session.id, query: 'needle', limit: 4 },
  573. { sessionId: session.id, query: 'needle', filters: [{ kind: 'seq', from: 2, to: 1 }] },
  574. { sessionId: session.id, query: 'needle', filters: [{ kind: 'surface', values: ['future'] }] },
  575. { sessionId: session.id, query: 'bad\0query' },
  576. ] as const) {
  577. await expect(ctx.sessionQuery.searchEvents(request as never)).rejects.toBeInstanceOf(Error)
  578. }
  579. await expect(ctx.sessionQuery.searchSessions({
  580. query: 'needle',
  581. sessionFilters: [{ kind: 'availability', values: ['remote' as never] }],
  582. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  583. await expect(ctx.sessionQuery.searchSessions({
  584. query: 'needle',
  585. sessionFilters: [{ kind: 'future' } as never],
  586. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  587. await expect(ctx.sessionQuery.searchSessions({
  588. query: 'needle',
  589. eventFilters: [{ kind: 'future' } as never],
  590. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  591. await expect(ctx.sessionQuery.searchEvents({
  592. sessionId: session.id,
  593. query: 'needle',
  594. filters: [{ kind: 'future' } as never],
  595. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  596. await expect(ctx.sessionQuery.searchEvents({
  597. sessionId: session.id,
  598. query: 'needle',
  599. cursor: SessionSearchCursor('not-json'),
  600. }))
  601. .rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  602. await expect(ctx.sessionQuery.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  603. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  604. for (const config of [
  605. { path: '' },
  606. { path: ':memory:', defaultLimit: 0 },
  607. { path: ':memory:', maxLimit: 0 },
  608. { path: ':memory:', defaultLimit: 1e100 },
  609. { path: ':memory:', maxLimit: 1e100 },
  610. { path: ':memory:', snippetChars: 0 },
  611. { path: ':memory:', readWindowMax: -1 },
  612. { path: ':memory:', persistedInspectConcurrency: 0 },
  613. { path: ':memory:', persistedInspectConcurrency: Number.MAX_SAFE_INTEGER + 1 },
  614. { path: ':memory:', defaultLimit: 3, maxLimit: 2 },
  615. { path: ':memory:', openAt: 'later' },
  616. { path: ':memory:', journalMode: 'memory' },
  617. ]) {
  618. const direct = new Context()
  619. await direct.plugin(SessionStore)
  620. expect(() => new SqliteSessionQueryEngine(direct, config as never))
  621. .toThrow(expectCode('SESSION_QUERY_INVALID_CONFIG'))
  622. expect(direct.sessionQuery).toBeUndefined()
  623. }
  624. })
  625. it('rejects aggregate filter bindings above SQLite\'s portable variable limit', async () => {
  626. const ctx = await liveContext()
  627. const session = ctx.sessions.create(SessionId('binding-limit'), { seed: messageEvents('needle') })
  628. // Each clause is below the ceiling; combined with its sibling and fixed
  629. // query bindings, the complete statement is not portable.
  630. const halfPortableLimit = 16_383
  631. const ids = Array.from(
  632. { length: halfPortableLimit },
  633. (_, index) => SessionId(`binding-${index}`),
  634. )
  635. const types = Array.from({ length: halfPortableLimit }, () => 'user/message' as const)
  636. const surfaces = Array.from({ length: halfPortableLimit }, () => 'current' as const)
  637. await expect(ctx.sessionQuery.searchSessions({
  638. query: 'needle',
  639. sessionFilters: [{ kind: 'id', values: ids }],
  640. eventFilters: [{ kind: 'type', values: types }],
  641. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  642. await expect(ctx.sessionQuery.searchEvents({
  643. sessionId: session.id,
  644. query: 'needle',
  645. filters: [
  646. { kind: 'type', values: types },
  647. { kind: 'surface', values: surfaces },
  648. ],
  649. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  650. })
  651. it('rejects one 125,000-value filter list with a typed error', async () => {
  652. const ctx = await liveContext()
  653. const ids = Array.from(
  654. { length: 125_000 },
  655. (_, index) => SessionId(`oversized-binding-${index}`),
  656. )
  657. await expect(ctx.sessionQuery.searchSessions({
  658. query: 'needle',
  659. sessionFilters: [{ kind: 'id', values: ids }],
  660. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  661. })
  662. })
  663. describe('SQLite reconciliation and source lifecycle', () => {
  664. it('owns queued request and filter values before waiting for the serializer', async () => {
  665. const durable = header('owned')
  666. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  667. const ctx = await liveContext()
  668. const persistence = await ctx.plugin(TestPersistence)
  669. let release!: () => void
  670. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  671. let markStarted!: () => void
  672. const started = new Promise<void>((resolve) => { markStarted = resolve })
  673. TestPersistence.listStarted = () => {
  674. TestPersistence.listStarted = undefined
  675. markStarted()
  676. }
  677. const blocking = ctx.sessionQuery.searchSessions({ query: 'needle' })
  678. await started
  679. const availability: SessionAvailability[] = ['persisted']
  680. const request: SessionSearchRequest = {
  681. query: 'needle',
  682. sessionFilters: [{ kind: 'availability', values: availability }],
  683. }
  684. const queued = ctx.sessionQuery.searchSessions(request)
  685. request.query = 'absent'
  686. availability[0] = 'live'
  687. release()
  688. await expect(blocking).resolves.toMatchObject({ items: [{ header: durable }] })
  689. await expect(queued).resolves.toMatchObject({ items: [{ header: durable }] })
  690. await persistence.dispose()
  691. })
  692. it('mounts persistence dynamically, shadows with TEMP live rows, reveals, and hides on unmount', async () => {
  693. const shared = header('shared', 10, { cwd: '/work' })
  694. const durable = header('durable', 5)
  695. TestPersistence.reset([
  696. { meta: shared, events: messageEvents('persisted needle') },
  697. { meta: durable, events: messageEvents('durable needle') },
  698. ])
  699. const ctx = await liveContext()
  700. await expect(ctx.sessionQuery.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  701. const persistenceFiber = await ctx.plugin(TestPersistence)
  702. await expect(ctx.sessionQuery.searchSessions({ query: 'durable' }))
  703. .resolves.toMatchObject({ items: [{ header: durable, live: false, persisted: true }] })
  704. const live = ctx.sessions.prepare(shared.id, { meta: { createdAt: 10, cwd: '/work' } })
  705. live.append('user/message', createUserMessage({
  706. content: [{ type: 'text', text: 'live needle' }], source: { kind: 'user' },
  707. }), { surfaceOp: 'append' })
  708. const detach = ctx.sessions.enter(live)
  709. ctx.sessions.announce(live)
  710. await expect(ctx.sessionQuery.searchSessions({ query: 'persisted' })).resolves.toEqual({ items: [] })
  711. await expect(ctx.sessionQuery.searchSessions({ query: 'live' }))
  712. .resolves.toMatchObject({ items: [{ header: shared, live: true, persisted: true }] })
  713. detach()
  714. await expect(ctx.sessionQuery.searchSessions({ query: 'persisted' }))
  715. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  716. await persistenceFiber.dispose()
  717. await expect(ctx.sessionQuery.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  718. await expect(ctx.sessionQuery.searchEvents({ sessionId: durable.id, query: 'needle' }))
  719. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  720. })
  721. it('does not load a persisted log while the same session is live', async () => {
  722. const shared = header('checkpointed-live', 10)
  723. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  724. const ctx = await liveContext()
  725. const live = ctx.sessions.prepare(shared.id, {
  726. seed: messageEvents('live needle'),
  727. meta: { createdAt: shared.createdAt },
  728. })
  729. const detach = ctx.sessions.enter(live)
  730. ctx.sessions.announce(live)
  731. const persistence = await ctx.plugin(TestPersistence)
  732. await expect(ctx.sessionQuery.searchSessions({
  733. query: 'live',
  734. sessionFilters: [{ kind: 'availability', values: ['persisted'] }],
  735. })).resolves.toMatchObject({
  736. items: [{ header: shared, live: true, persisted: true }],
  737. })
  738. expect(TestPersistence.loads.get(shared.id)).toBeUndefined()
  739. expect(TestPersistence.inspections.get(shared.id)).toBeUndefined()
  740. detach()
  741. await expect(ctx.sessionQuery.searchSessions({ query: 'persisted' }))
  742. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  743. expect(TestPersistence.loads.get(shared.id)).toBeUndefined()
  744. expect(TestPersistence.inspections.get(shared.id)).toBe(1)
  745. await persistence.dispose()
  746. })
  747. it('retries when a live owner attaches during persistence observation', async () => {
  748. TestPersistence.reset()
  749. const ctx = await liveContext()
  750. await ctx.plugin(TestPersistence)
  751. TestPersistence.snapshotEffect = () => {
  752. TestPersistence.snapshotEffect = undefined
  753. ctx.sessions.create(SessionId('attached'), { seed: messageEvents('attached needle') })
  754. }
  755. await expect(ctx.sessionQuery.searchSessions({ query: 'attached' }))
  756. .resolves.toMatchObject({ items: [{ header: { id: SessionId('attached') } }] })
  757. })
  758. it('cannot crash-repair a log when live ownership begins during persisted inspection', async () => {
  759. const shared = header('attach-during-inspect', 10)
  760. const persistedEvents = messageEvents('persisted needle')
  761. TestPersistence.reset([{ meta: shared, events: persistedEvents }])
  762. const ctx = await liveContext()
  763. await ctx.plugin(TestPersistence)
  764. TestPersistence.loadEffect = (entry) => {
  765. entry.events = messageEvents('incorrect repair')
  766. }
  767. TestPersistence.inspectEffect = () => {
  768. ctx.sessions.create(shared.id, {
  769. seed: messageEvents('live needle'),
  770. meta: { createdAt: shared.createdAt },
  771. })
  772. }
  773. await expect(ctx.sessionQuery.searchSessions({ query: 'live' }))
  774. .resolves.toMatchObject({ items: [{ header: shared, live: true, persisted: true }] })
  775. expect(TestPersistence.loads.get(shared.id)).toBeUndefined()
  776. expect(TestPersistence.entries.get(shared.id)?.events).toEqual(persistedEvents)
  777. })
  778. it('retries when one live owner replaces another during persistence observation', async () => {
  779. TestPersistence.reset()
  780. const ctx = await liveContext()
  781. const first = ctx.sessions.prepare(SessionId('first'), { seed: messageEvents('first needle') })
  782. const detachFirst = ctx.sessions.enter(first)
  783. ctx.sessions.announce(first)
  784. await ctx.plugin(TestPersistence)
  785. TestPersistence.snapshotEffect = () => {
  786. TestPersistence.snapshotEffect = undefined
  787. detachFirst()
  788. ctx.sessions.create(SessionId('second'), { seed: messageEvents('second needle') })
  789. }
  790. await expect(ctx.sessionQuery.searchSessions({ query: 'second' }))
  791. .resolves.toMatchObject({ items: [{ header: { id: SessionId('second') } }] })
  792. })
  793. it('uses the reconciled persistence binding through the query boundary', async () => {
  794. const durable = header('post-reconcile-unmount')
  795. TestPersistence.reset([{ meta: durable, events: [
  796. ...messageEvents('durable needle', 1),
  797. { ...messageEvents('durable needle again', 2)[0]!, seq: 1 },
  798. ] }])
  799. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 2 })
  800. const persistence = await ctx.plugin(TestPersistence)
  801. const internals = ctx.sessionQuery as unknown as {
  802. _reconcile(signal: AbortSignal | undefined): Promise<{
  803. identity: symbol
  804. service?: SessionPersistence
  805. }>
  806. }
  807. const reconcile = internals._reconcile.bind(internals)
  808. const boundary = vi.spyOn(internals, '_reconcile').mockImplementation(async (signal) => {
  809. const binding = await reconcile(signal)
  810. await persistence.dispose()
  811. return binding
  812. })
  813. const page = await ctx.sessionQuery.searchEvents({
  814. sessionId: durable.id,
  815. query: 'needle',
  816. limit: 1,
  817. })
  818. expect(page.items).toMatchObject([{ sessionId: durable.id }])
  819. expect(page.nextCursor).toEqual(expect.any(String))
  820. boundary.mockRestore()
  821. await expect(ctx.sessionQuery.searchEvents({ sessionId: durable.id, query: 'needle' }))
  822. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  823. })
  824. it('discards a stale list rejection when persistence unmounts during observation', async () => {
  825. const durable = header('racing')
  826. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  827. const ctx = await liveContext()
  828. const persistenceFiber = await ctx.plugin(TestPersistence)
  829. let release!: () => void
  830. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  831. let markStarted!: () => void
  832. const started = new Promise<void>((resolve) => { markStarted = resolve })
  833. TestPersistence.listStarted = () => {
  834. TestPersistence.listStarted = undefined
  835. markStarted()
  836. }
  837. const search = ctx.sessionQuery.searchSessions({ query: 'needle' })
  838. await started
  839. await persistenceFiber.dispose()
  840. TestPersistence.failure = new Error('stale backend rejection')
  841. release()
  842. await expect(search).resolves.toEqual({ items: [] })
  843. })
  844. it('retries against a replacement after the prior binding rejects', async () => {
  845. const durable = header('replacement')
  846. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  847. const ctx = await liveContext()
  848. const prior = await ctx.plugin(TestPersistence)
  849. let rejectPrior!: (reason: unknown) => void
  850. TestPersistence.listGate = new Promise<void>((_resolve, reject) => { rejectPrior = reject })
  851. let markStarted!: () => void
  852. const started = new Promise<void>((resolve) => { markStarted = resolve })
  853. TestPersistence.listStarted = () => {
  854. TestPersistence.listStarted = undefined
  855. markStarted()
  856. }
  857. const search = ctx.sessionQuery.searchSessions({ query: 'needle' })
  858. await started
  859. await prior.dispose()
  860. TestPersistence.listGate = undefined
  861. const replacement = await ctx.plugin(TestPersistence)
  862. rejectPrior(new Error('stale prior binding'))
  863. await expect(search).resolves.toMatchObject({ items: [{ header: durable }] })
  864. await replacement.dispose()
  865. })
  866. it('reloads a replacement source even when its opaque revisions collide', async () => {
  867. const durable = header('colliding-replacement')
  868. TestPersistence.reset([{ meta: durable, events: messageEvents('old content') }])
  869. const revision = TestPersistence.revisions.get(durable.id)!
  870. const ctx = await liveContext()
  871. const prior = await ctx.plugin(TestPersistence)
  872. await expect(ctx.sessionQuery.searchSessions({ query: 'old' }))
  873. .resolves.toMatchObject({ items: [{ header: durable }] })
  874. await prior.dispose()
  875. TestPersistence.set({ meta: durable, events: messageEvents('new needle') })
  876. TestPersistence.revisions.set(durable.id, revision)
  877. const replacement = await ctx.plugin(TestPersistence)
  878. const page = await ctx.sessionQuery.searchSessions({ query: 'new needle' })
  879. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  880. expect(page).toMatchObject({ items: [{ header: durable }] })
  881. await expect(ctx.sessionQuery.searchSessions({ query: 'old' })).resolves.toEqual({ items: [] })
  882. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  883. await replacement.dispose()
  884. })
  885. it('retries when a successful observation belongs to a source unmounted during listing', async () => {
  886. const durable = header('successful-unmount')
  887. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  888. const ctx = await liveContext()
  889. const persistence = await ctx.plugin(TestPersistence)
  890. let lists = 0
  891. TestPersistence.snapshotEffect = async () => {
  892. lists += 1
  893. if (lists === 2) await persistence.dispose()
  894. }
  895. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' })).resolves.toEqual({ items: [] })
  896. expect(lists).toBe(2)
  897. })
  898. it('retries when the snapshot population changes during observation', async () => {
  899. const first = header('first')
  900. const added = header('added-during-list')
  901. TestPersistence.reset([{ meta: first, events: messageEvents('first needle') }])
  902. const ctx = await liveContext()
  903. await ctx.plugin(TestPersistence)
  904. TestPersistence.snapshotEffect = () => {
  905. TestPersistence.snapshotEffect = undefined
  906. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  907. }
  908. const page = await ctx.sessionQuery.searchSessions({ query: 'needle' })
  909. expect(page.items.map(item => item.header.id).sort()).toEqual([added.id, first.id].sort())
  910. expect(TestPersistence.inspections.get(first.id)).toBe(2)
  911. expect(TestPersistence.inspections.get(added.id)).toBe(1)
  912. })
  913. it('fails after one retry when persistence snapshots keep changing', async () => {
  914. const durable = header('continuous-mutation')
  915. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  916. const ctx = await liveContext()
  917. await ctx.plugin(TestPersistence)
  918. let lists = 0
  919. TestPersistence.snapshotEffect = () => {
  920. lists += 1
  921. TestPersistence.set({ meta: durable, events: messageEvents(`durable needle ${lists}`) })
  922. }
  923. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  924. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  925. expect(lists).toBe(4)
  926. })
  927. it('retries if the persistence binding changes while live sessions are observed', async () => {
  928. const durable = header('live-boundary-retry')
  929. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  930. const ctx = await liveContext()
  931. await ctx.plugin(TestPersistence)
  932. const internals = ctx.sessionQuery as unknown as {
  933. _persistenceBinding: { identity: symbol; service?: SessionPersistence }
  934. }
  935. const originalList = ctx.sessions.list.bind(ctx.sessions)
  936. let bumped = false
  937. const list = vi.spyOn(ctx.sessions, 'list').mockImplementation(() => {
  938. if (!bumped) {
  939. bumped = true
  940. internals._persistenceBinding = {
  941. ...internals._persistenceBinding,
  942. identity: Symbol(),
  943. }
  944. }
  945. return originalList()
  946. })
  947. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  948. .resolves.toMatchObject({ items: [{ header: durable }] })
  949. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  950. list.mockRestore()
  951. })
  952. it('rejects malformed snapshots and preserves typed persistence failures', async () => {
  953. const durable = header('invalid-snapshot')
  954. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  955. const ctx = await liveContext()
  956. await ctx.plugin(TestPersistence)
  957. TestPersistence.snapshotOverride = () => 'not-an-array' as never
  958. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  959. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  960. TestPersistence.snapshotOverride = () => [{ header: durable, revision: 1 as never }]
  961. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  962. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  963. TestPersistence.snapshotOverride = () => [
  964. { header: durable, revision: SessionPersistenceRevision('duplicate:1') },
  965. { header: durable, revision: SessionPersistenceRevision('duplicate:2') },
  966. ]
  967. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  968. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  969. TestPersistence.snapshotOverride = undefined
  970. const typed = new SessionQueryError('typed persistence failure', 'SESSION_QUERY_PERSISTENCE_FAILED')
  971. TestPersistence.failure = typed
  972. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' })).rejects.toBe(typed)
  973. })
  974. it('rejects immutable header conflicts between live and persisted sources', async () => {
  975. const shared = header('conflict', 10, { delegationDepth: 1 })
  976. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  977. const ctx = await liveContext()
  978. await ctx.plugin(TestPersistence)
  979. ctx.sessions.create(shared.id, {
  980. seed: messageEvents('live needle'),
  981. meta: { createdAt: 10, delegationDepth: 2 },
  982. })
  983. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  984. .rejects.toThrow(expectCode('SESSION_QUERY_SOURCE_CONFLICT'))
  985. })
  986. it('preserves unchanged persisted generations while reconciling new, changed, and deleted rows', { timeout: 20_000 }, async () => {
  987. const path = await temporaryPath()
  988. const unchanged = header('unchanged')
  989. const changed = header('changed')
  990. const deleted = header('deleted')
  991. TestPersistence.reset([
  992. { meta: unchanged, events: messageEvents('unchanged needle') },
  993. { meta: changed, events: messageEvents('old needle') },
  994. { meta: deleted, events: messageEvents('deleted needle') },
  995. ])
  996. const first = new Context()
  997. await first.plugin(SessionStore)
  998. await first.plugin(SessionProjectionRegistry)
  999. const firstPersistence = await first.plugin(TestPersistence)
  1000. const firstSearch = await first.plugin(SqliteSessionQueryEngine, { path })
  1001. await first.sessionQuery.searchSessions({ query: 'needle' })
  1002. expect(Object.fromEntries(TestPersistence.inspections)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  1003. await first.sessionQuery.searchSessions({ query: 'needle' })
  1004. expect(Object.fromEntries(TestPersistence.inspections)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  1005. await firstSearch.dispose()
  1006. await firstPersistence.dispose()
  1007. const beforeDb = new DatabaseSync(path)
  1008. const beforeRows = beforeDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  1009. beforeDb.close()
  1010. const before = new Map(beforeRows.map(row => [row.id, row.generation]))
  1011. const added = header('added')
  1012. TestPersistence.entries.delete(deleted.id)
  1013. TestPersistence.set({ meta: changed, events: messageEvents('changed needle') })
  1014. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  1015. const second = new Context()
  1016. await second.plugin(SessionStore)
  1017. await second.plugin(SessionProjectionRegistry)
  1018. const secondPersistence = await second.plugin(TestPersistence)
  1019. const secondSearch = await second.plugin(SqliteSessionQueryEngine, { path })
  1020. const result = await second.sessionQuery.searchSessions({ query: 'needle' })
  1021. expect(result.items.map(item => item.header.id).sort()).toEqual([added.id, changed.id, unchanged.id].sort())
  1022. expect(Object.fromEntries(TestPersistence.inspections)).toEqual({
  1023. unchanged: 1,
  1024. changed: 2,
  1025. deleted: 1,
  1026. added: 1,
  1027. })
  1028. await secondSearch.dispose()
  1029. await secondPersistence.dispose()
  1030. const afterDb = new DatabaseSync(path)
  1031. const afterRows = afterDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  1032. afterDb.close()
  1033. const after = new Map(afterRows.map(row => [row.id, row.generation]))
  1034. expect(after.get(unchanged.id)).toBe(before.get(unchanged.id))
  1035. expect(after.get(changed.id)).toBeGreaterThan(before.get(changed.id)!)
  1036. expect(after.has(deleted.id)).toBe(false)
  1037. expect(after.has(added.id)).toBe(true)
  1038. })
  1039. it('drops connection-local live overlays on reopen and retains persistent bases', async () => {
  1040. const path = await temporaryPath()
  1041. const shared = header('shared', 10)
  1042. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  1043. const first = new Context()
  1044. await first.plugin(SessionStore)
  1045. await first.plugin(SessionProjectionRegistry)
  1046. const persistence = await first.plugin(TestPersistence)
  1047. const live = first.sessions.create(shared.id, { seed: messageEvents('live needle'), meta: { createdAt: 10 } })
  1048. const search = await first.plugin(SqliteSessionQueryEngine, { path })
  1049. await expect(first.sessionQuery.searchEvents({ sessionId: live.id, query: 'live' })).resolves.toMatchObject({ items: [{}] })
  1050. await search.dispose()
  1051. await persistence.dispose()
  1052. const second = new Context()
  1053. await second.plugin(SessionStore)
  1054. await second.plugin(SessionProjectionRegistry)
  1055. const persistenceAgain = await second.plugin(TestPersistence)
  1056. const searchAgain = await second.plugin(SqliteSessionQueryEngine, { path })
  1057. await expect(second.sessionQuery.searchSessions({ query: 'live' })).resolves.toEqual({ items: [] })
  1058. await expect(second.sessionQuery.searchSessions({ query: 'persisted' }))
  1059. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  1060. expect(TestPersistence.inspections.get(shared.id)).toBe(1)
  1061. await searchAgain.dispose()
  1062. await persistenceAgain.dispose()
  1063. })
  1064. it('refreshes after an external mutating load repair without loading from the query path', async () => {
  1065. const durable = header('repair')
  1066. TestPersistence.reset([{ meta: durable, events: messageEvents('before repair') }])
  1067. const ctx = await liveContext()
  1068. const persistence = await ctx.plugin(TestPersistence)
  1069. await expect(ctx.sessionQuery.searchSessions({ query: 'before' }))
  1070. .resolves.toMatchObject({ items: [{ header: durable }] })
  1071. TestPersistence.loadEffect = (entry) => {
  1072. entry.events = messageEvents('repaired needle')
  1073. }
  1074. await ctx.sessionPersistence.load(durable.id)
  1075. await expect(ctx.sessionQuery.searchSessions({ query: 'repaired' }))
  1076. .resolves.toMatchObject({ items: [{ header: durable }] })
  1077. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  1078. await ctx.sessionQuery.searchSessions({ query: 'repaired' })
  1079. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  1080. expect(TestPersistence.loads.get(durable.id)).toBe(1)
  1081. await persistence.dispose()
  1082. })
  1083. it('recovers on the next search after source and SQLite transaction failures', async () => {
  1084. TestPersistence.reset([{ meta: header('durable'), events: messageEvents('durable needle') }])
  1085. const ctx = await liveContext()
  1086. await ctx.plugin(TestPersistence)
  1087. TestPersistence.failure = 'offline'
  1088. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  1089. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  1090. const signal = new AbortController().signal
  1091. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal }))
  1092. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  1093. TestPersistence.failure = new Error('still offline')
  1094. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal }))
  1095. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  1096. TestPersistence.failure = undefined
  1097. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' })).resolves.toMatchObject({ items: [{}] })
  1098. const live = ctx.sessions.create(SessionId('live'), { seed: messageEvents('base') })
  1099. await ctx.sessionQuery.searchEvents({ sessionId: live.id, query: 'base' })
  1100. const db = (ctx.sessionQuery as unknown as { _db: DatabaseSync })._db
  1101. db.exec('PRAGMA query_only = ON')
  1102. live.append('user/message', createUserMessage({
  1103. content: [{ type: 'text', text: 'retry needle' }], source: { kind: 'user' },
  1104. }), { surfaceOp: 'append' })
  1105. await expect(ctx.sessionQuery.searchEvents({ sessionId: live.id, query: 'needle' }))
  1106. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1107. db.exec('PRAGMA query_only = OFF')
  1108. // seq 2: one-event seed, end-seed, then the live message.
  1109. await expect(ctx.sessionQuery.searchEvents({ sessionId: live.id, query: 'needle' }))
  1110. .resolves.toMatchObject({ items: [{ seq: 2 }] })
  1111. })
  1112. })
  1113. describe('SQLite schema, cancellation, and real persistence integration', () => {
  1114. it('creates a new database and WAL sidecars owner-only without changing its parent mode', async () => {
  1115. if (process.platform === 'win32') return
  1116. const path = await temporaryPath()
  1117. const directory = dirname(path)
  1118. await chmod(directory, 0o755)
  1119. const ctx = await liveContext({ path })
  1120. await ctx.sessionQuery.searchSessions({ query: 'needle' })
  1121. expect((await stat(directory)).mode & 0o777).toBe(0o755)
  1122. expect((await stat(path)).mode & 0o777).toBe(0o600)
  1123. expect((await stat(`${path}-wal`)).mode & 0o777).toBe(0o600)
  1124. expect((await stat(`${path}-shm`)).mode & 0o777).toBe(0o600)
  1125. await (ctx.sessionQuery as SqliteSessionQueryEngine).close()
  1126. })
  1127. it('creates a persistent rollback journal owner-only', async () => {
  1128. if (process.platform === 'win32') return
  1129. const path = await temporaryPath()
  1130. const ctx = await liveContext({ path, journalMode: 'persist' })
  1131. await ctx.sessionQuery.searchSessions({ query: 'needle' })
  1132. expect((await stat(path)).mode & 0o777).toBe(0o600)
  1133. expect((await stat(`${path}-journal`)).mode & 0o777).toBe(0o600)
  1134. await (ctx.sessionQuery as SqliteSessionQueryEngine).close()
  1135. })
  1136. it('preserves the mode of an existing database file', async () => {
  1137. if (process.platform === 'win32') return
  1138. const path = await temporaryPath()
  1139. await writeFile(path, '', { mode: 0o644 })
  1140. await chmod(path, 0o644)
  1141. const ctx = await liveContext({ path, journalMode: 'delete' })
  1142. await ctx.sessionQuery.searchSessions({ query: 'needle' })
  1143. expect((await stat(path)).mode & 0o777).toBe(0o644)
  1144. await (ctx.sessionQuery as SqliteSessionQueryEngine).close()
  1145. })
  1146. it('surfaces filesystem failures while pre-creating the database', async () => {
  1147. const path = `${await temporaryPath()}\0`
  1148. const ctx = new Context()
  1149. await ctx.plugin(SessionStore)
  1150. await ctx.plugin(SessionProjectionRegistry)
  1151. await expect(ctx.plugin(SqliteSessionQueryEngine, { path })).rejects.toMatchObject({
  1152. code: 'SESSION_QUERY_INDEX_FAILED',
  1153. cause: { code: 'ERR_INVALID_ARG_VALUE' },
  1154. })
  1155. expect(ctx.sessionQuery).toBeUndefined()
  1156. })
  1157. it('resets a recognized incompatible schema but refuses unknown or foreign tables', { timeout: 20_000 }, async () => {
  1158. const stalePath = await temporaryPath('stale.db')
  1159. const staleOwner = await liveContext({ path: stalePath })
  1160. await (staleOwner.sessionQuery as SqliteSessionQueryEngine).close()
  1161. const stale = new DatabaseSync(stalePath)
  1162. stale.exec(`PRAGMA user_version = ${SESSION_QUERY_SQLITE_SCHEMA_VERSION - 1}`)
  1163. stale.close()
  1164. const staleCtx = await liveContext({ path: stalePath })
  1165. staleCtx.sessions.create(SessionId('live'), { seed: messageEvents('needle') })
  1166. await staleCtx.sessionQuery.searchSessions({ query: 'needle' })
  1167. await (staleCtx.sessionQuery as SqliteSessionQueryEngine).close()
  1168. const rebuilt = new DatabaseSync(stalePath)
  1169. expect((rebuilt.prepare('PRAGMA user_version').get() as { user_version: number }).user_version)
  1170. .toBe(SESSION_QUERY_SQLITE_SCHEMA_VERSION)
  1171. rebuilt.close()
  1172. const augmentedPath = await temporaryPath('augmented.db')
  1173. const augmentedOwner = await liveContext({ path: augmentedPath })
  1174. await (augmentedOwner.sessionQuery as SqliteSessionQueryEngine).close()
  1175. const augmented = new DatabaseSync(augmentedPath)
  1176. augmented.exec('CREATE TABLE unrelated(value TEXT)')
  1177. augmented.exec("INSERT INTO unrelated VALUES ('safe')")
  1178. augmented.exec('PRAGMA user_version = 999')
  1179. augmented.close()
  1180. const augmentedCtx = new Context()
  1181. await augmentedCtx.plugin(SessionStore)
  1182. await augmentedCtx.plugin(SessionProjectionRegistry)
  1183. await expect(augmentedCtx.plugin(SqliteSessionQueryEngine, { path: augmentedPath }))
  1184. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1185. expect(augmentedCtx.sessionQuery).toBeUndefined()
  1186. const stillAugmented = new DatabaseSync(augmentedPath)
  1187. expect(stillAugmented.prepare('SELECT value FROM unrelated').get()).toEqual({ value: 'safe' })
  1188. expect(stillAugmented.prepare('PRAGMA user_version').get()).toEqual({ user_version: 999 })
  1189. stillAugmented.close()
  1190. const currentAugmentedPath = await temporaryPath('current-augmented.db')
  1191. const currentAugmentedOwner = await liveContext({ path: currentAugmentedPath })
  1192. await (currentAugmentedOwner.sessionQuery as SqliteSessionQueryEngine).close()
  1193. const currentAugmented = new DatabaseSync(currentAugmentedPath)
  1194. currentAugmented.exec('CREATE TABLE unrelated(value TEXT)')
  1195. currentAugmented.exec("INSERT INTO unrelated VALUES ('safe')")
  1196. currentAugmented.close()
  1197. const currentAugmentedCtx = new Context()
  1198. await currentAugmentedCtx.plugin(SessionStore)
  1199. await currentAugmentedCtx.plugin(SessionProjectionRegistry)
  1200. await expect(currentAugmentedCtx.plugin(SqliteSessionQueryEngine, {
  1201. path: currentAugmentedPath,
  1202. journalMode: 'delete',
  1203. })).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1204. expect(currentAugmentedCtx.sessionQuery).toBeUndefined()
  1205. const stillCurrentAugmented = new DatabaseSync(currentAugmentedPath)
  1206. expect(stillCurrentAugmented.prepare('SELECT value FROM unrelated').get()).toEqual({ value: 'safe' })
  1207. expect(stillCurrentAugmented.prepare('PRAGMA user_version').get())
  1208. .toEqual({ user_version: SESSION_QUERY_SQLITE_SCHEMA_VERSION })
  1209. expect(stillCurrentAugmented.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  1210. stillCurrentAugmented.close()
  1211. const foreignPath = await temporaryPath('foreign.db')
  1212. const foreign = new DatabaseSync(foreignPath)
  1213. foreign.exec('PRAGMA journal_mode = WAL')
  1214. foreign.exec('CREATE TABLE canonical(value TEXT)')
  1215. foreign.exec("INSERT INTO canonical VALUES ('safe')")
  1216. foreign.close()
  1217. const foreignCtx = new Context()
  1218. await foreignCtx.plugin(SessionStore)
  1219. await foreignCtx.plugin(SessionProjectionRegistry)
  1220. await expect(foreignCtx.plugin(SqliteSessionQueryEngine, { path: foreignPath, journalMode: 'delete' }))
  1221. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1222. expect(foreignCtx.sessionQuery).toBeUndefined()
  1223. const stillForeign = new DatabaseSync(foreignPath)
  1224. expect(stillForeign.prepare('SELECT value FROM canonical').get()).toEqual({ value: 'safe' })
  1225. expect(stillForeign.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  1226. stillForeign.close()
  1227. const wildcardPath = await temporaryPath('sqlite-wildcard.db')
  1228. const wildcard = new DatabaseSync(wildcardPath)
  1229. wildcard.exec('PRAGMA journal_mode = WAL')
  1230. wildcard.exec('CREATE TABLE sqliteX(value TEXT)')
  1231. wildcard.exec("INSERT INTO sqliteX VALUES ('safe')")
  1232. wildcard.close()
  1233. const wildcardCtx = new Context()
  1234. await wildcardCtx.plugin(SessionStore)
  1235. await wildcardCtx.plugin(SessionProjectionRegistry)
  1236. await expect(wildcardCtx.plugin(SqliteSessionQueryEngine, {
  1237. path: wildcardPath,
  1238. journalMode: 'delete',
  1239. })).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1240. expect(wildcardCtx.sessionQuery).toBeUndefined()
  1241. const stillWildcard = new DatabaseSync(wildcardPath)
  1242. expect(stillWildcard.prepare('SELECT value FROM sqliteX').get()).toEqual({ value: 'safe' })
  1243. expect(stillWildcard.prepare('PRAGMA application_id').get()).toEqual({ application_id: 0 })
  1244. expect(stillWildcard.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 })
  1245. expect(stillWildcard.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  1246. stillWildcard.close()
  1247. const otherAppPath = await temporaryPath('other-app.db')
  1248. const otherApp = new DatabaseSync(otherAppPath)
  1249. otherApp.exec('PRAGMA application_id = 123')
  1250. otherApp.close()
  1251. const otherAppCtx = new Context()
  1252. await otherAppCtx.plugin(SessionStore)
  1253. await otherAppCtx.plugin(SessionProjectionRegistry)
  1254. await expect(otherAppCtx.plugin(SqliteSessionQueryEngine, { path: otherAppPath }))
  1255. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1256. expect(otherAppCtx.sessionQuery).toBeUndefined()
  1257. })
  1258. it('fails plugin initialization without an unhandled rejection or partial service', async () => {
  1259. const path = await temporaryPath('never-queried.db')
  1260. const foreign = new DatabaseSync(path)
  1261. foreign.exec('CREATE TABLE canonical(value TEXT)')
  1262. foreign.close()
  1263. const unhandled: unknown[] = []
  1264. const onUnhandled = (reason: unknown) => { unhandled.push(reason) }
  1265. process.on('unhandledRejection', onUnhandled)
  1266. try {
  1267. const ctx = new Context()
  1268. await ctx.plugin(SessionStore)
  1269. await ctx.plugin(SessionProjectionRegistry)
  1270. await expect(ctx.plugin(SqliteSessionQueryEngine, { path }))
  1271. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1272. await new Promise<void>((resolve) => { setImmediate(resolve) })
  1273. expect(unhandled).toEqual([])
  1274. expect(ctx.sessionQuery).toBeUndefined()
  1275. } finally {
  1276. process.off('unhandledRejection', onUnhandled)
  1277. }
  1278. })
  1279. it('defers an invalid database failure only in first-search mode', async () => {
  1280. const path = await temporaryPath('lazy-invalid.db')
  1281. const foreign = new DatabaseSync(path)
  1282. foreign.exec('CREATE TABLE canonical(value TEXT)')
  1283. foreign.close()
  1284. const lazyCtx = new Context()
  1285. await lazyCtx.plugin(SessionStore)
  1286. await lazyCtx.plugin(SessionProjectionRegistry)
  1287. const lazy = await lazyCtx.plugin(SqliteSessionQueryEngine, {
  1288. path,
  1289. openAt: 'first-search',
  1290. })
  1291. expect(lazyCtx.sessionQuery).toBeInstanceOf(SqliteSessionQueryEngine)
  1292. await expect(lazyCtx.sessionQuery.searchSessions({ query: 'needle' }))
  1293. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1294. await lazy.dispose()
  1295. const eagerCtx = new Context()
  1296. await eagerCtx.plugin(SessionStore)
  1297. await eagerCtx.plugin(SessionProjectionRegistry)
  1298. await expect(eagerCtx.plugin(SqliteSessionQueryEngine, { path }))
  1299. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1300. expect(eagerCtx.sessionQuery).toBeUndefined()
  1301. })
  1302. it.each(['sessions', 'events'] as const)(
  1303. 'forwards one exact reconciliation signal through both snapshot lists and persisted inspection for %s search',
  1304. async (scope) => {
  1305. const durable = header(`signal-${scope}`)
  1306. TestPersistence.reset([{ meta: durable, events: messageEvents('signal needle') }])
  1307. const ctx = await liveContext()
  1308. await ctx.plugin(TestPersistence)
  1309. const controller = new AbortController()
  1310. const result = scope === 'sessions'
  1311. ? await ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal })
  1312. : await ctx.sessionQuery.searchEvents(
  1313. { sessionId: durable.id, query: 'needle' },
  1314. { signal: controller.signal },
  1315. )
  1316. expect(result.items).toHaveLength(1)
  1317. expect(TestPersistence.snapshotSignals).toEqual([controller.signal, controller.signal])
  1318. expect(TestPersistence.inspectSignals).toEqual([controller.signal])
  1319. },
  1320. )
  1321. it.each(['sessions', 'events'] as const)(
  1322. 'starts no persistence observation for a pre-aborted %s search',
  1323. async (scope) => {
  1324. const durable = header(`pre-aborted-${scope}`)
  1325. TestPersistence.reset([{ meta: durable, events: messageEvents('needle') }])
  1326. const ctx = await liveContext()
  1327. await ctx.plugin(TestPersistence)
  1328. const controller = new AbortController()
  1329. controller.abort(new Error(`pre-aborted ${scope}`))
  1330. const pending = scope === 'sessions'
  1331. ? ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal })
  1332. : ctx.sessionQuery.searchEvents(
  1333. { sessionId: durable.id, query: 'needle' },
  1334. { signal: controller.signal },
  1335. )
  1336. await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1337. expect(TestPersistence.snapshotSignals).toEqual([])
  1338. expect(TestPersistence.inspectSignals).toEqual([])
  1339. },
  1340. )
  1341. it('awaits cooperative snapshot-list cancellation cleanup without starting another observation step', async () => {
  1342. const durable = header('cooperative-list-abort')
  1343. TestPersistence.reset([{ meta: durable, events: messageEvents('needle') }])
  1344. const ctx = await liveContext()
  1345. await ctx.plugin(TestPersistence)
  1346. const started = Promise.withResolvers<AbortSignal>()
  1347. const abortObserved = Promise.withResolvers<undefined>()
  1348. const cleanup = Promise.withResolvers<undefined>()
  1349. TestPersistence.snapshotEffect = async (signal) => {
  1350. TestPersistence.snapshotEffect = undefined
  1351. if (signal === undefined) throw new Error('expected reconciliation signal')
  1352. started.resolve(signal)
  1353. await new Promise<void>((resolve) => {
  1354. signal.addEventListener('abort', () => { resolve() }, { once: true })
  1355. })
  1356. abortObserved.resolve(undefined)
  1357. await cleanup.promise
  1358. signal.throwIfAborted()
  1359. }
  1360. const controller = new AbortController()
  1361. const pending = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal })
  1362. expect(await started.promise).toBe(controller.signal)
  1363. let settled = false
  1364. void pending.then(
  1365. () => { settled = true },
  1366. () => { settled = true },
  1367. )
  1368. controller.abort(new Error('cooperative list cancellation'))
  1369. await abortObserved.promise
  1370. expect(settled).toBe(false)
  1371. expect(TestPersistence.snapshotSignals).toEqual([controller.signal])
  1372. expect(TestPersistence.inspectSignals).toEqual([])
  1373. cleanup.resolve(undefined)
  1374. await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1375. })
  1376. it('keeps a second search serialized while an abort-ignoring snapshot list finishes', async () => {
  1377. const durable = header('serialized-list-abort')
  1378. TestPersistence.reset([{ meta: durable, events: messageEvents('needle') }])
  1379. const ctx = await liveContext()
  1380. await ctx.plugin(TestPersistence)
  1381. const cleanup = Promise.withResolvers<undefined>()
  1382. const started = Promise.withResolvers<undefined>()
  1383. TestPersistence.listGate = cleanup.promise
  1384. TestPersistence.listStarted = () => {
  1385. TestPersistence.listStarted = undefined
  1386. started.resolve(undefined)
  1387. }
  1388. const controller = new AbortController()
  1389. const first = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal })
  1390. await started.promise
  1391. let firstSettled = false
  1392. let secondSettled = false
  1393. void first.then(
  1394. () => { firstSettled = true },
  1395. () => { firstSettled = true },
  1396. )
  1397. controller.abort(new Error('ignored list cancellation'))
  1398. const second = ctx.sessionQuery.searchEvents({ sessionId: durable.id, query: 'needle' })
  1399. void second.then(
  1400. () => { secondSettled = true },
  1401. () => { secondSettled = true },
  1402. )
  1403. await Promise.resolve()
  1404. expect(firstSettled).toBe(false)
  1405. expect(secondSettled).toBe(false)
  1406. expect(TestPersistence.snapshotSignals).toEqual([controller.signal])
  1407. expect(TestPersistence.inspectSignals).toEqual([])
  1408. cleanup.resolve(undefined)
  1409. await expect(first).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1410. await expect(second).resolves.toMatchObject({ items: [{ sessionId: durable.id }] })
  1411. })
  1412. it('awaits an abort-ignoring inspection and starts neither another inspection nor the after-list', async () => {
  1413. const first = header('ignored-inspect-first')
  1414. const second = header('ignored-inspect-second')
  1415. TestPersistence.reset([
  1416. { meta: first, events: messageEvents('first needle') },
  1417. { meta: second, events: messageEvents('second needle') },
  1418. ])
  1419. const ctx = await liveContext()
  1420. await ctx.plugin(TestPersistence)
  1421. const started = Promise.withResolvers<AbortSignal>()
  1422. const cleanup = Promise.withResolvers<undefined>()
  1423. TestPersistence.inspectEffect = async (_entry, signal) => {
  1424. TestPersistence.inspectEffect = undefined
  1425. if (signal === undefined) throw new Error('expected reconciliation signal')
  1426. started.resolve(signal)
  1427. await cleanup.promise
  1428. }
  1429. const controller = new AbortController()
  1430. const pending = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal })
  1431. expect(await started.promise).toBe(controller.signal)
  1432. let settled = false
  1433. void pending.then(
  1434. () => { settled = true },
  1435. () => { settled = true },
  1436. )
  1437. controller.abort(new Error('ignored inspect cancellation'))
  1438. await Promise.resolve()
  1439. expect(settled).toBe(false)
  1440. expect(TestPersistence.snapshotSignals).toEqual([controller.signal])
  1441. expect(TestPersistence.inspections.get(first.id)).toBe(1)
  1442. expect(TestPersistence.inspections.get(second.id)).toBeUndefined()
  1443. cleanup.resolve(undefined)
  1444. await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1445. expect(TestPersistence.snapshotSignals).toEqual([controller.signal])
  1446. expect(TestPersistence.inspections.get(second.id)).toBeUndefined()
  1447. })
  1448. it('cancels both queued and in-flight source waits without committing them', async () => {
  1449. TestPersistence.reset()
  1450. const ctx = await liveContext()
  1451. await ctx.plugin(TestPersistence)
  1452. const boundaryController = new AbortController()
  1453. const boundary = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: boundaryController.signal })
  1454. queueMicrotask(() => { boundaryController.abort() })
  1455. await expect(boundary).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1456. const readyController = new AbortController()
  1457. readyController.abort()
  1458. const internals = ctx.sessionQuery as unknown as {
  1459. _ensureReady(signal: AbortSignal): Promise<void>
  1460. }
  1461. await expect(internals._ensureReady(readyController.signal))
  1462. .rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1463. let releaseBlocking!: () => void
  1464. TestPersistence.listGate = new Promise<void>((resolve) => { releaseBlocking = resolve })
  1465. let markBlockingStarted!: () => void
  1466. const blockingStarted = new Promise<void>((resolve) => { markBlockingStarted = resolve })
  1467. TestPersistence.listStarted = () => {
  1468. TestPersistence.listStarted = undefined
  1469. markBlockingStarted()
  1470. }
  1471. const blocking = ctx.sessionQuery.searchSessions({ query: 'needle' })
  1472. await blockingStarted
  1473. const queuedController = new AbortController()
  1474. const queued = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: queuedController.signal })
  1475. queuedController.abort()
  1476. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1477. releaseBlocking()
  1478. await expect(blocking).resolves.toEqual({ items: [] })
  1479. TestPersistence.set({
  1480. meta: header('uncommitted'),
  1481. events: messageEvents('durable needle'),
  1482. })
  1483. let releaseActive!: () => void
  1484. TestPersistence.listGate = new Promise<void>((resolve) => { releaseActive = resolve })
  1485. let markActiveStarted!: () => void
  1486. const activeStarted = new Promise<void>((resolve) => { markActiveStarted = resolve })
  1487. TestPersistence.listStarted = () => {
  1488. TestPersistence.listStarted = undefined
  1489. markActiveStarted()
  1490. }
  1491. const activeController = new AbortController()
  1492. const active = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: activeController.signal })
  1493. await activeStarted
  1494. activeController.abort()
  1495. let activeSettled = false
  1496. void active.then(
  1497. () => { activeSettled = true },
  1498. () => { activeSettled = true },
  1499. )
  1500. await Promise.resolve()
  1501. expect(activeSettled).toBe(false)
  1502. releaseActive()
  1503. await expect(active).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1504. const db = (ctx.sessionQuery as unknown as { _db: DatabaseSync })._db
  1505. expect(db.prepare('SELECT COUNT(*) AS count FROM persisted_sessions').get()).toEqual({ count: 0 })
  1506. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  1507. .resolves.toMatchObject({ items: [{ header: { id: SessionId('uncommitted') } }] })
  1508. })
  1509. it.each([
  1510. [new Error('ready error'), 'ready error'],
  1511. ['non-error ready failure', 'session-search dependency rejected with a non-Error value'],
  1512. ])('normalizes a rejected readiness wait before mapping it to an index error', async (failure, detail) => {
  1513. TestPersistence.reset()
  1514. const ctx = await liveContext()
  1515. const internals = ctx.sessionQuery as unknown as {
  1516. _ready: Promise<void>
  1517. _ensureReady(signal: AbortSignal): Promise<void>
  1518. }
  1519. internals._ready = Promise.resolve().then(() => {
  1520. throw failure
  1521. })
  1522. await expect(internals._ensureReady(new AbortController().signal))
  1523. .rejects.toThrow(`session-search SQLite index failed to open: ${detail}`)
  1524. })
  1525. it('checks cancellation after readiness before reconciliation accesses SQLite', async () => {
  1526. TestPersistence.reset()
  1527. const ctx = await liveContext()
  1528. const internals = ctx.sessionQuery as unknown as {
  1529. _db: DatabaseSync
  1530. _ready: Promise<void>
  1531. _ensureReady(signal: AbortSignal | undefined): Promise<void>
  1532. }
  1533. const readiness = Promise.withResolvers<undefined>()
  1534. internals._ready = readiness.promise
  1535. const readyWaitStarted = Promise.withResolvers<undefined>()
  1536. const ensureReady = internals._ensureReady.bind(internals)
  1537. vi.spyOn(internals, '_ensureReady').mockImplementation(async (signal) => {
  1538. const pending = ensureReady(signal)
  1539. readyWaitStarted.resolve(undefined)
  1540. return pending
  1541. })
  1542. const prepare = vi.spyOn(internals._db, 'prepare')
  1543. const reason = new Error('cancelled after readiness')
  1544. const controller = new AbortController()
  1545. const pending = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal })
  1546. await readyWaitStarted.promise
  1547. const queueBoundaryAbort = readiness.promise.then(() => {
  1548. queueMicrotask(() => { controller.abort(reason) })
  1549. })
  1550. readiness.resolve(undefined)
  1551. await queueBoundaryAbort
  1552. await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1553. expect(prepare).not.toHaveBeenCalled()
  1554. })
  1555. it('rejects queued and future work when close waits for an accepted operation', async () => {
  1556. TestPersistence.reset()
  1557. let release!: () => void
  1558. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  1559. let markStarted!: () => void
  1560. const started = new Promise<void>((resolve) => { markStarted = resolve })
  1561. TestPersistence.listStarted = () => {
  1562. TestPersistence.listStarted = undefined
  1563. markStarted()
  1564. }
  1565. const ctx = await liveContext()
  1566. await ctx.plugin(TestPersistence)
  1567. const search = ctx.sessionQuery as SqliteSessionQueryEngine
  1568. const accepted = search.searchSessions({ query: 'needle' })
  1569. await started
  1570. const queued = search.searchSessions({ query: 'needle' })
  1571. const closing = search.close()
  1572. const repeatedClose = search.close()
  1573. expect(repeatedClose).toBe(closing)
  1574. release()
  1575. await expect(accepted).resolves.toEqual({ items: [] })
  1576. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1577. await Promise.all([closing, repeatedClose])
  1578. await expect(search.searchSessions({ query: 'needle' }))
  1579. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1580. expect(search.close()).toBe(closing)
  1581. })
  1582. it('awaits optional-persistence child-fiber quiescence on disposal', async () => {
  1583. TestPersistence.reset()
  1584. const ctx = new Context()
  1585. await ctx.plugin(SessionStore)
  1586. await ctx.plugin(SessionProjectionRegistry)
  1587. const search = await ctx.plugin(SqliteSessionQueryEngine, { path: ':memory:' })
  1588. const persistence = await ctx.plugin(TestPersistence)
  1589. const optional = (ctx.sessionQuery as unknown as {
  1590. _optionalPersistenceFiber: Fiber
  1591. })._optionalPersistenceFiber
  1592. let release!: () => void
  1593. const cleanup = new Promise<void>((resolve) => { release = resolve })
  1594. optional.ctx.effect(() => () => cleanup)
  1595. let settled = false
  1596. const disposing = search.dispose().then(() => { settled = true })
  1597. await Promise.resolve()
  1598. expect(settled).toBe(false)
  1599. release()
  1600. await disposing
  1601. await persistence.dispose()
  1602. })
  1603. it('combines the real SQLite persistence backend with the real search service keylessly', async () => {
  1604. const persistencePath = await temporaryPath('canonical.db')
  1605. const searchPath = await temporaryPath('derived.db')
  1606. const ctx = new Context()
  1607. await ctx.plugin(SessionStore)
  1608. await ctx.plugin(SessionProjectionRegistry)
  1609. const persistence = await ctx.plugin(SqliteSessionPersistence, { path: persistencePath })
  1610. const search = await ctx.plugin(SqliteSessionQueryEngine, { path: searchPath })
  1611. const meta = header('real', 10, { cwd: '/work' })
  1612. await ctx.sessionPersistence.create(meta)
  1613. await ctx.sessionPersistence.append(meta.id, messageEvents('real SQLite needle'))
  1614. await expect(ctx.sessionQuery.searchSessions({ query: 'SQLite needle' }))
  1615. .resolves.toMatchObject({ items: [{ header: meta, persisted: true, live: false }] })
  1616. await expect(ctx.sessionQuery.searchEvents({ sessionId: meta.id, query: 'SQLite needle' }))
  1617. .resolves.toMatchObject({ session: meta, items: [{ sessionId: meta.id, seq: 0 }] })
  1618. await expect(ctx.sessionQuery.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  1619. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  1620. await search.dispose()
  1621. await expect(ctx.sessionPersistence.load(meta.id)).resolves.toMatchObject({ meta, events: [{ seq: 0 }] })
  1622. await persistence.dispose()
  1623. })
  1624. it('reconciles colliding local revisions when a derived index reopens against another SQLite store', async () => {
  1625. const persistencePathA = await temporaryPath('canonical-a.db')
  1626. const persistencePathB = await temporaryPath('canonical-b.db')
  1627. const searchPath = await temporaryPath('derived-collision.db')
  1628. const shared = header('same-id', 10)
  1629. const first = new Context()
  1630. await first.plugin(SessionStore)
  1631. await first.plugin(SessionProjectionRegistry)
  1632. const persistenceA = await first.plugin(SqliteSessionPersistence, { path: persistencePathA })
  1633. await first.sessionPersistence.create(shared)
  1634. await first.sessionPersistence.append(shared.id, messageEvents('alpha source'))
  1635. const inspectA = vi.spyOn(first.sessionPersistence, 'inspect')
  1636. const searchA = await first.plugin(SqliteSessionQueryEngine, { path: searchPath })
  1637. await expect(first.sessionQuery.searchSessions({ query: 'alpha' }))
  1638. .resolves.toMatchObject({ items: [{ header: shared }] })
  1639. expect(inspectA).toHaveBeenCalledTimes(1)
  1640. await searchA.dispose()
  1641. await persistenceA.dispose()
  1642. const reopened = new Context()
  1643. await reopened.plugin(SessionStore)
  1644. await reopened.plugin(SessionProjectionRegistry)
  1645. const persistenceAAgain = await reopened.plugin(SqliteSessionPersistence, { path: persistencePathA })
  1646. const reopenedInspect = vi.spyOn(reopened.sessionPersistence, 'inspect')
  1647. const searchAAgain = await reopened.plugin(SqliteSessionQueryEngine, { path: searchPath })
  1648. await expect(reopened.sessionQuery.searchSessions({ query: 'alpha' }))
  1649. .resolves.toMatchObject({ items: [{ header: shared }] })
  1650. expect(reopenedInspect).not.toHaveBeenCalled()
  1651. await searchAAgain.dispose()
  1652. await persistenceAAgain.dispose()
  1653. const second = new Context()
  1654. await second.plugin(SessionStore)
  1655. await second.plugin(SessionProjectionRegistry)
  1656. const persistenceB = await second.plugin(SqliteSessionPersistence, { path: persistencePathB })
  1657. await second.sessionPersistence.create(shared)
  1658. await second.sessionPersistence.append(shared.id, messageEvents('bravo source'))
  1659. const inspectB = vi.spyOn(second.sessionPersistence, 'inspect')
  1660. const searchB = await second.plugin(SqliteSessionQueryEngine, { path: searchPath })
  1661. await expect(second.sessionQuery.searchSessions({ query: 'bravo' }))
  1662. .resolves.toMatchObject({ items: [{ header: shared }] })
  1663. await expect(second.sessionQuery.searchSessions({ query: 'alpha' })).resolves.toEqual({ items: [] })
  1664. expect(inspectB).toHaveBeenCalledTimes(1)
  1665. await searchB.dispose()
  1666. await persistenceB.dispose()
  1667. })
  1668. })