1
0

sqlite.spec.ts 83 KB

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