sqlite.spec.ts 82 KB

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