sqlite.spec.ts 83 KB

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