sqlite.spec.ts 83 KB

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