sqlite.spec.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context, type Fiber } from 'cordis'
  3. import { DatabaseSync } from 'node:sqlite'
  4. import { chmod, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { dirname, join } from 'node:path'
  7. import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent, SessionHeader, SessionId as SessionIdType } from '@deepseek-ai/dsh-session'
  9. import SessionPersistence, { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence'
  10. import type { SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence'
  11. import SessionPersistenceSqlite from '@deepseek-ai/dsh-session-persistence-sqlite'
  12. import SessionQuerySqlite, {
  13. SESSION_QUERY_SQLITE_SCHEMA_VERSION,
  14. } from '@deepseek-ai/dsh-session-query-sqlite'
  15. import {
  16. SessionQueryError,
  17. SessionSearchCursor,
  18. type SessionAvailability,
  19. type SessionQueryErrorCode,
  20. type SessionSearchRequest,
  21. } from '@deepseek-ai/dsh-session-query'
  22. const temporaryDirectories: string[] = []
  23. afterEach(async () => {
  24. for (const directory of temporaryDirectories.splice(0)) {
  25. await rm(directory, { recursive: true, force: true })
  26. }
  27. })
  28. async function temporaryPath(name = 'search.db'): Promise<string> {
  29. const directory = await mkdtemp(join(tmpdir(), 'dsh-session-search-'))
  30. temporaryDirectories.push(directory)
  31. return join(directory, name)
  32. }
  33. function header(id: string, createdAt = 1, extra: Partial<SessionHeader> = {}): SessionHeader {
  34. return { version: SESSION_FORMAT_VERSION, id: SessionId(id), createdAt, ...extra }
  35. }
  36. function messageEvents(text: string, time = 1): SessionEvent[] {
  37. return [{
  38. type: 'user/message',
  39. seq: 0,
  40. time,
  41. data: { content: [{ type: 'text', text }], source: { kind: 'user' } },
  42. surfaceOp: 'append',
  43. }]
  44. }
  45. function expectCode(code: SessionQueryErrorCode): Error {
  46. return expect.objectContaining({ code }) as Error
  47. }
  48. function replaceCursorOffset(
  49. cursor: ReturnType<typeof SessionSearchCursor>,
  50. offset: number,
  51. ): ReturnType<typeof SessionSearchCursor> {
  52. const payload = JSON.parse(
  53. Buffer.from(cursor, 'base64url').toString('utf8'),
  54. ) as Record<string, unknown>
  55. return SessionSearchCursor(Buffer.from(JSON.stringify({ ...payload, offset }), 'utf8').toString('base64url'))
  56. }
  57. class TestPersistence extends SessionPersistence {
  58. static entries = new Map<SessionIdType, { meta: SessionHeader; events: SessionEvent[] }>()
  59. static revisions = new Map<SessionIdType, number>()
  60. static nextRevision = 0
  61. static loads = new Map<SessionIdType, number>()
  62. static inspections = new Map<SessionIdType, number>()
  63. static loadEffect: ((entry: { meta: SessionHeader; events: SessionEvent[] }) => void) | undefined
  64. static inspectEffect: ((entry: { meta: SessionHeader; events: SessionEvent[] }) => void | Promise<void>) | undefined
  65. static listGate: Promise<void> | undefined
  66. static listStarted: (() => void) | undefined
  67. static snapshotEffect: (() => void | Promise<void>) | undefined
  68. static snapshotOverride: (() => SessionPersistenceSnapshot[]) | undefined
  69. static failure: unknown
  70. locate(_meta: SessionHeader): undefined {
  71. return undefined
  72. }
  73. static reset(entries: readonly { meta: SessionHeader; events: SessionEvent[] }[] = []): void {
  74. this.entries = new Map()
  75. this.revisions = new Map()
  76. this.loads = new Map()
  77. this.inspections = new Map()
  78. this.loadEffect = undefined
  79. this.inspectEffect = undefined
  80. for (const entry of entries) this.set(entry)
  81. this.listGate = undefined
  82. this.listStarted = undefined
  83. this.snapshotEffect = undefined
  84. this.snapshotOverride = undefined
  85. this.failure = undefined
  86. }
  87. static set(entry: { meta: SessionHeader; events: SessionEvent[] }): void {
  88. this.entries.set(entry.meta.id, structuredClone(entry))
  89. this.revisions.set(entry.meta.id, ++this.nextRevision)
  90. }
  91. create(meta: SessionHeader): Promise<void> {
  92. TestPersistence.set({ meta, events: [] })
  93. return Promise.resolve()
  94. }
  95. append(id: SessionIdType, events: readonly SessionEvent[]): Promise<void> {
  96. const entry = TestPersistence.entries.get(id)
  97. if (entry === undefined) return Promise.reject(new Error('missing test session'))
  98. entry.events.push(...structuredClone(events))
  99. TestPersistence.revisions.set(id, ++TestPersistence.nextRevision)
  100. return Promise.resolve()
  101. }
  102. async load(id: SessionIdType): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  103. TestPersistence.loads.set(id, (TestPersistence.loads.get(id) ?? 0) + 1)
  104. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  105. const entry = TestPersistence.entries.get(id)
  106. if (entry === undefined) throw new Error('missing test session')
  107. if (TestPersistence.loadEffect !== undefined) {
  108. const effect = TestPersistence.loadEffect
  109. TestPersistence.loadEffect = undefined
  110. effect(entry)
  111. TestPersistence.revisions.set(id, ++TestPersistence.nextRevision)
  112. }
  113. return structuredClone(entry)
  114. }
  115. async inspect(id: SessionIdType): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  116. TestPersistence.inspections.set(id, (TestPersistence.inspections.get(id) ?? 0) + 1)
  117. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  118. const entry = TestPersistence.entries.get(id)
  119. if (entry === undefined) throw new Error('missing test session')
  120. await TestPersistence.inspectEffect?.(entry)
  121. TestPersistence.inspectEffect = undefined
  122. return structuredClone(entry)
  123. }
  124. async list(): Promise<SessionHeader[]> {
  125. TestPersistence.listStarted?.()
  126. await TestPersistence.listGate
  127. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  128. return [...TestPersistence.entries.values()].map(entry => structuredClone(entry.meta))
  129. }
  130. async listSnapshots(): Promise<SessionPersistenceSnapshot[]> {
  131. TestPersistence.listStarted?.()
  132. await TestPersistence.listGate
  133. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  134. const snapshots = TestPersistence.snapshotOverride?.()
  135. ?? [...TestPersistence.entries.values()].map(entry => ({
  136. header: structuredClone(entry.meta),
  137. revision: SessionPersistenceRevision(`test:${TestPersistence.revisions.get(entry.meta.id)}`),
  138. }))
  139. await TestPersistence.snapshotEffect?.()
  140. return snapshots
  141. }
  142. }
  143. async function liveContext(config: ConstructorParameters<typeof SessionQuerySqlite>[1] = { path: ':memory:' }): Promise<Context> {
  144. const ctx = new Context()
  145. await ctx.plugin(SessionStore)
  146. await ctx.plugin(SessionQuerySqlite, config)
  147. return ctx
  148. }
  149. describe('SQLite session search', () => {
  150. it('searches two-character Unicode61 tokens in live-only sessions', async () => {
  151. const ctx = await liveContext({ path: ':memory:', snippetChars: 20 })
  152. const session = ctx.sessions.create(SessionId('live'), {
  153. meta: { cwd: '/work', createdAt: 10, seedLength: 1, delegationDepth: 2 },
  154. })
  155. session.append(
  156. 'user/message',
  157. { content: [{ type: 'text', text: 'An AI helper' }], source: { kind: 'user' } },
  158. { surfaceOp: 'append' },
  159. )
  160. await expect(ctx.sessionQuery.searchEvents({ sessionId: session.id, query: 'AI' }))
  161. .resolves.toMatchObject({ items: [{ sessionId: session.id, seq: 0, snippet: 'An AI helper' }] })
  162. await expect(ctx.sessionQuery.searchSessions({ query: 'AI' }))
  163. .resolves.toMatchObject({ items: [{ header: { ...session.header, seedLength: 1 }, live: true, persisted: false }] })
  164. })
  165. it('searches all surfaces by default and applies metadata before ranking', async () => {
  166. const ctx = await liveContext({ path: ':memory:', defaultLimit: 10, maxLimit: 20 })
  167. const parent = SessionId('parent')
  168. const events: SessionEvent[] = [
  169. { type: 'user/message', seq: 0, time: 10, data: { content: [{ type: 'text', text: 'needle original' }], source: { kind: 'user' } }, surfaceOp: 'append' },
  170. { type: 'assistant/chunk', seq: 1, time: 11, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'needle raw' } } },
  171. { type: 'user/message', seq: 2, time: 12, data: { content: [{ type: 'text', text: 'needle summary' }], source: { kind: 'plugin', plugin: 'test' } }, surfaceOp: { op: 'replace', start: 0, end: 0 }, sourceEventSeqs: [0] },
  172. { type: 'turn/end', seq: 3, time: 13, data: { turn: 1, reason: { kind: 'error', step: 1, message: 'needle failure' } } },
  173. ]
  174. ctx.sessions.create(SessionId('a'), { seed: events, meta: { cwd: '/a', parentSession: parent, createdAt: 20 } })
  175. ctx.sessions.create(SessionId('b'), { seed: messageEvents('needle peer', 12), meta: { createdAt: 20 } })
  176. const all = await ctx.sessionQuery.searchEvents({ sessionId: SessionId('a'), query: 'needle' })
  177. expect(new Set(all.items.map(item => item.surface))).toEqual(new Set(['current', 'shadowed', 'log-only']))
  178. await expect(ctx.sessionQuery.searchEvents({
  179. sessionId: SessionId('a'),
  180. query: 'needle',
  181. filters: [
  182. { kind: 'seq', from: 2, to: 2 },
  183. { kind: 'time', from: 12, to: 12 },
  184. { kind: 'type', values: ['user/message'] },
  185. { kind: 'surface', values: ['current'] },
  186. ],
  187. })).resolves.toMatchObject({ items: [{ seq: 2, surface: 'current' }] })
  188. const grouped = await ctx.sessionQuery.searchSessions({
  189. query: 'needle',
  190. sessionFilters: [
  191. { kind: 'id', values: [SessionId('a')] },
  192. { kind: 'cwd', values: ['/a'] },
  193. { kind: 'created-at', from: 20, to: 20 },
  194. { kind: 'parent', values: [parent] },
  195. { kind: 'availability', values: ['live'] },
  196. ],
  197. eventFilters: [{ kind: 'surface', values: ['shadowed'] }],
  198. })
  199. expect(grouped.items).toHaveLength(1)
  200. expect(grouped.items[0]).toMatchObject({
  201. header: { id: SessionId('a'), cwd: '/a', parentSession: parent },
  202. live: true,
  203. persisted: false,
  204. bestMatch: { seq: 0, surface: 'shadowed' },
  205. })
  206. })
  207. it('searches at the supported FTS5 outer-predicate boundary in both scopes', async () => {
  208. const ctx = await liveContext()
  209. const session = ctx.sessions.create(SessionId('predicate-boundary'), {
  210. seed: messageEvents('needle'),
  211. meta: { cwd: '/work' },
  212. })
  213. const sessionFilters = Array.from(
  214. { length: 14 },
  215. () => ({ kind: 'cwd' as const, values: ['/work', null] }),
  216. )
  217. const eventFilters = Array.from(
  218. { length: 13 },
  219. () => ({ kind: 'type' as const, values: ['user/message' as const] }),
  220. )
  221. await expect(ctx.sessionQuery.searchSessions({ query: 'needle', sessionFilters }))
  222. .resolves.toMatchObject({ items: [{ header: { id: session.id } }] })
  223. await expect(ctx.sessionQuery.searchEvents({
  224. sessionId: session.id,
  225. query: 'needle',
  226. filters: eventFilters,
  227. })).resolves.toMatchObject({ items: [{ sessionId: session.id, seq: 0 }] })
  228. })
  229. it('rejects unsupported FTS5 outer-predicate counts with typed errors', async () => {
  230. const ctx = await liveContext()
  231. const session = ctx.sessions.create(SessionId('predicate-limit'), { seed: messageEvents('needle') })
  232. const sessionFilters = Array.from(
  233. { length: 1_100 },
  234. () => ({ kind: 'id' as const, values: [session.id] }),
  235. )
  236. const eventFilters = Array.from(
  237. { length: 1_100 },
  238. () => ({ kind: 'type' as const, values: ['user/message' as const] }),
  239. )
  240. await expect(ctx.sessionQuery.searchSessions({ query: 'needle', sessionFilters }))
  241. .rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  242. await expect(ctx.sessionQuery.searchEvents({
  243. sessionId: session.id,
  244. query: 'needle',
  245. filters: eventFilters,
  246. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  247. await expect(ctx.sessionQuery.searchSessions({
  248. query: 'needle',
  249. sessionFilters: sessionFilters.slice(0, 7),
  250. eventFilters: eventFilters.slice(0, 8),
  251. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  252. await expect(ctx.sessionQuery.searchEvents({
  253. sessionId: session.id,
  254. query: 'needle',
  255. filters: eventFilters.slice(0, 14),
  256. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  257. })
  258. it('uses literal phrase tokens, stable ties, and bounded Unicode snippets', async () => {
  259. const ctx = await liveContext({ path: ':memory:', defaultLimit: 10, maxLimit: 10, snippetChars: 5 })
  260. ctx.sessions.create(SessionId('a'), { seed: messageEvents('😀😀 alpha beta BRAID 😀😀', 10), meta: { createdAt: 1 } })
  261. ctx.sessions.create(SessionId('b'), { seed: messageEvents('alpha beta', 10), meta: { createdAt: 1 } })
  262. ctx.sessions.create(SessionId('c'), { seed: messageEvents('alpha middle beta', 10), meta: { createdAt: 1 } })
  263. ctx.sessions.create(SessionId('d'), { seed: messageEvents('alpha beta', 10), meta: { createdAt: 1 } })
  264. ctx.sessions.create(SessionId('operator'), { seed: messageEvents('needle OR absent', 10), meta: { createdAt: 1 } })
  265. ctx.sessions.create(SessionId('only'), { seed: messageEvents('needle only', 10), meta: { createdAt: 1 } })
  266. ctx.sessions.create(SessionId('quote'), { seed: messageEvents('say "needle" exactly', 10), meta: { createdAt: 1 } })
  267. const phrase = await ctx.sessionQuery.searchSessions({ query: 'alpha beta' })
  268. expect(phrase.items.map(item => item.header.id)).toEqual([SessionId('b'), SessionId('d'), SessionId('a')])
  269. expect(phrase.items.every(item => Array.from(item.bestMatch.snippet).length <= 5)).toBe(true)
  270. await expect(ctx.sessionQuery.searchSessions({ query: 'AI' })).resolves.toEqual({ items: [] })
  271. await expect(ctx.sessionQuery.searchSessions({ query: 'needle OR absent' }))
  272. .resolves.toMatchObject({ items: [{ header: { id: SessionId('operator') } }] })
  273. await expect(ctx.sessionQuery.searchSessions({ query: 'say "needle"' }))
  274. .resolves.toMatchObject({ items: [{ header: { id: SessionId('quote') } }] })
  275. await expect(ctx.sessionQuery.searchSessions({ query: '*' })).resolves.toEqual({ items: [] })
  276. })
  277. it('ranks live and persisted matches on one source-comparable contract', async () => {
  278. const persisted = header('z-persisted')
  279. TestPersistence.reset([
  280. { meta: persisted, events: messageEvents('needle needle', 10) },
  281. ...Array.from({ length: 12 }, (_, index) => ({
  282. meta: header(`filler-${index}`),
  283. events: messageEvents('needle', 10),
  284. })),
  285. ])
  286. const ctx = await liveContext()
  287. const persistence = await ctx.plugin(TestPersistence)
  288. ctx.sessions.create(SessionId('a-live'), {
  289. seed: messageEvents('needle needle', 10),
  290. meta: { createdAt: persisted.createdAt },
  291. })
  292. const result = await ctx.sessionQuery.searchSessions({
  293. query: 'needle',
  294. sessionFilters: [{ kind: 'id', values: [SessionId('a-live'), persisted.id] }],
  295. })
  296. expect(result.items.map(item => item.header.id)).toEqual([SessionId('a-live'), persisted.id])
  297. await persistence.dispose()
  298. })
  299. it('positions snippets from FTS5 matches across diacritics and punctuation', async () => {
  300. const ctx = await liveContext({ path: ':memory:', snippetChars: 14 })
  301. const session = ctx.sessions.create(SessionId('snippet'), {
  302. seed: messageEvents('long long long—café,\nnext value', 10),
  303. })
  304. const page = await ctx.sessionQuery.searchEvents({ sessionId: session.id, query: 'CAFE' })
  305. expect(page.items).toHaveLength(1)
  306. expect(page.items[0]!.snippet).toContain('café')
  307. expect(page.items[0]!.snippet).toContain('—')
  308. expect(page.items[0]!.snippet).not.toContain('\n')
  309. expect(Array.from(page.items[0]!.snippet).length).toBeLessThanOrEqual(14)
  310. })
  311. it('binds cursors to requests and only invalidates within-session pages for target changes', async () => {
  312. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 5 })
  313. const target = ctx.sessions.create(SessionId('target'), {
  314. seed: [
  315. ...messageEvents('needle one', 10),
  316. { ...messageEvents('needle two', 11)[0]!, seq: 1 },
  317. { ...messageEvents('needle three', 12)[0]!, seq: 2 },
  318. ],
  319. })
  320. ctx.sessions.create(SessionId('other'), { seed: messageEvents('needle other', 10) })
  321. const eventPage = await ctx.sessionQuery.searchEvents({ sessionId: target.id, query: 'needle', limit: 1 })
  322. const sessionPage = await ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1 })
  323. expect(eventPage.nextCursor).toEqual(expect.any(String))
  324. expect(sessionPage.nextCursor).toEqual(expect.any(String))
  325. if (eventPage.nextCursor === undefined || sessionPage.nextCursor === undefined) throw new Error('expected cursors')
  326. const unsafeOffsetCursor = replaceCursorOffset(eventPage.nextCursor, 1e100)
  327. await expect(ctx.sessionQuery.searchEvents({
  328. sessionId: target.id,
  329. query: 'needle',
  330. limit: 1,
  331. cursor: unsafeOffsetCursor,
  332. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  333. const eventKeys = eventPage.items.map(item => `${item.sessionId}:${item.seq}`)
  334. let eventCursor: ReturnType<typeof SessionSearchCursor> | undefined = eventPage.nextCursor
  335. while (eventCursor !== undefined) {
  336. const next = await ctx.sessionQuery.searchEvents({
  337. sessionId: target.id,
  338. query: 'needle',
  339. limit: 1,
  340. cursor: eventCursor,
  341. })
  342. eventKeys.push(...next.items.map(item => `${item.sessionId}:${item.seq}`))
  343. eventCursor = next.nextCursor
  344. }
  345. expect(eventKeys).toHaveLength(3)
  346. expect(new Set(eventKeys).size).toBe(eventKeys.length)
  347. const sessionIds = sessionPage.items.map(item => item.header.id)
  348. let sessionCursor: ReturnType<typeof SessionSearchCursor> | undefined = sessionPage.nextCursor
  349. while (sessionCursor !== undefined) {
  350. const next = await ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1, cursor: sessionCursor })
  351. sessionIds.push(...next.items.map(item => item.header.id))
  352. sessionCursor = next.nextCursor
  353. }
  354. expect(sessionIds).toHaveLength(2)
  355. expect(new Set(sessionIds).size).toBe(sessionIds.length)
  356. ctx.sessions.create(SessionId('unrelated'), { seed: messageEvents('needle unrelated', 20) })
  357. await expect(ctx.sessionQuery.searchEvents({
  358. sessionId: target.id,
  359. query: 'needle',
  360. limit: 1,
  361. cursor: eventPage.nextCursor,
  362. })).resolves.toMatchObject({ items: [{ sessionId: target.id }] })
  363. await expect(ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1, cursor: sessionPage.nextCursor }))
  364. .rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  365. await expect(ctx.sessionQuery.searchEvents({
  366. sessionId: target.id,
  367. query: 'different',
  368. limit: 1,
  369. cursor: eventPage.nextCursor,
  370. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  371. target.append('user/message', { content: [{ type: 'text', text: 'needle four' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  372. await expect(ctx.sessionQuery.searchEvents({
  373. sessionId: target.id,
  374. query: 'needle',
  375. limit: 1,
  376. cursor: eventPage.nextCursor,
  377. })).rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  378. })
  379. it('invalidates session cursors after transient persistence topology changes', async () => {
  380. TestPersistence.reset()
  381. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 5 })
  382. ctx.sessions.create(SessionId('first'), { seed: messageEvents('needle first') })
  383. ctx.sessions.create(SessionId('second'), { seed: messageEvents('needle second') })
  384. const page = await ctx.sessionQuery.searchSessions({ query: 'needle', limit: 1 })
  385. if (page.nextCursor === undefined) throw new Error('expected cursor')
  386. const persistence = await ctx.plugin(TestPersistence)
  387. await persistence.dispose()
  388. await expect(ctx.sessionQuery.searchSessions({
  389. query: 'needle',
  390. limit: 1,
  391. cursor: page.nextCursor,
  392. })).rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  393. })
  394. it('rejects invalid requests, filters, cursors, and direct config', async () => {
  395. const ctx = await liveContext({ path: ':memory:', defaultLimit: 2, maxLimit: 3 })
  396. const session = ctx.sessions.create(SessionId('valid'), { seed: messageEvents('needle') })
  397. for (const request of [
  398. { sessionId: session.id, query: '' },
  399. { sessionId: session.id, query: 'needle', limit: 0 },
  400. { sessionId: session.id, query: 'needle', limit: 4 },
  401. { sessionId: session.id, query: 'needle', filters: [{ kind: 'seq', from: 2, to: 1 }] },
  402. { sessionId: session.id, query: 'needle', filters: [{ kind: 'surface', values: ['future'] }] },
  403. { sessionId: session.id, query: 'bad\0query' },
  404. ] as const) {
  405. await expect(ctx.sessionQuery.searchEvents(request as never)).rejects.toBeInstanceOf(Error)
  406. }
  407. await expect(ctx.sessionQuery.searchSessions({
  408. query: 'needle',
  409. sessionFilters: [{ kind: 'availability', values: ['remote' as never] }],
  410. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  411. await expect(ctx.sessionQuery.searchSessions({
  412. query: 'needle',
  413. sessionFilters: [{ kind: 'future' } as never],
  414. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  415. await expect(ctx.sessionQuery.searchSessions({
  416. query: 'needle',
  417. eventFilters: [{ kind: 'future' } as never],
  418. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  419. await expect(ctx.sessionQuery.searchEvents({
  420. sessionId: session.id,
  421. query: 'needle',
  422. filters: [{ kind: 'future' } as never],
  423. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  424. await expect(ctx.sessionQuery.searchEvents({
  425. sessionId: session.id,
  426. query: 'needle',
  427. cursor: SessionSearchCursor('not-json'),
  428. }))
  429. .rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  430. await expect(ctx.sessionQuery.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  431. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  432. for (const config of [
  433. { path: '' },
  434. { path: ':memory:', defaultLimit: 0 },
  435. { path: ':memory:', maxLimit: 0 },
  436. { path: ':memory:', defaultLimit: 1e100 },
  437. { path: ':memory:', maxLimit: 1e100 },
  438. { path: ':memory:', snippetChars: 0 },
  439. { path: ':memory:', defaultLimit: 3, maxLimit: 2 },
  440. { path: ':memory:', journalMode: 'memory' },
  441. ]) {
  442. const direct = new Context()
  443. await direct.plugin(SessionStore)
  444. expect(() => new SessionQuerySqlite(direct, config as never))
  445. .toThrow(expectCode('SESSION_QUERY_INVALID_CONFIG'))
  446. }
  447. })
  448. it('rejects aggregate filter bindings above SQLite\'s portable variable limit', async () => {
  449. const ctx = await liveContext()
  450. const session = ctx.sessions.create(SessionId('binding-limit'), { seed: messageEvents('needle') })
  451. // Each clause is below the ceiling; combined with its sibling and fixed
  452. // query bindings, the complete statement is not portable.
  453. const halfPortableLimit = 16_383
  454. const ids = Array.from(
  455. { length: halfPortableLimit },
  456. (_, index) => SessionId(`binding-${index}`),
  457. )
  458. const types = Array.from({ length: halfPortableLimit }, () => 'user/message' as const)
  459. const surfaces = Array.from({ length: halfPortableLimit }, () => 'current' as const)
  460. await expect(ctx.sessionQuery.searchSessions({
  461. query: 'needle',
  462. sessionFilters: [{ kind: 'id', values: ids }],
  463. eventFilters: [{ kind: 'type', values: types }],
  464. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  465. await expect(ctx.sessionQuery.searchEvents({
  466. sessionId: session.id,
  467. query: 'needle',
  468. filters: [
  469. { kind: 'type', values: types },
  470. { kind: 'surface', values: surfaces },
  471. ],
  472. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  473. })
  474. it('rejects one 125,000-value filter list with a typed error', async () => {
  475. const ctx = await liveContext()
  476. const ids = Array.from(
  477. { length: 125_000 },
  478. (_, index) => SessionId(`oversized-binding-${index}`),
  479. )
  480. await expect(ctx.sessionQuery.searchSessions({
  481. query: 'needle',
  482. sessionFilters: [{ kind: 'id', values: ids }],
  483. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  484. })
  485. })
  486. describe('SQLite reconciliation and source lifecycle', () => {
  487. it('owns queued request and filter values before waiting for the serializer', async () => {
  488. const durable = header('owned')
  489. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  490. const ctx = await liveContext()
  491. const persistence = await ctx.plugin(TestPersistence)
  492. let release!: () => void
  493. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  494. let markStarted!: () => void
  495. const started = new Promise<void>((resolve) => { markStarted = resolve })
  496. TestPersistence.listStarted = () => {
  497. TestPersistence.listStarted = undefined
  498. markStarted()
  499. }
  500. const blocking = ctx.sessionQuery.searchSessions({ query: 'needle' })
  501. await started
  502. const availability: SessionAvailability[] = ['persisted']
  503. const request: SessionSearchRequest = {
  504. query: 'needle',
  505. sessionFilters: [{ kind: 'availability', values: availability }],
  506. }
  507. const queued = ctx.sessionQuery.searchSessions(request)
  508. request.query = 'absent'
  509. availability[0] = 'live'
  510. release()
  511. await expect(blocking).resolves.toMatchObject({ items: [{ header: durable }] })
  512. await expect(queued).resolves.toMatchObject({ items: [{ header: durable }] })
  513. await persistence.dispose()
  514. })
  515. it('mounts persistence dynamically, shadows with TEMP live rows, reveals, and hides on unmount', async () => {
  516. const shared = header('shared', 10, { cwd: '/work' })
  517. const durable = header('durable', 5)
  518. TestPersistence.reset([
  519. { meta: shared, events: messageEvents('persisted needle') },
  520. { meta: durable, events: messageEvents('durable needle') },
  521. ])
  522. const ctx = await liveContext()
  523. await expect(ctx.sessionQuery.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  524. const persistenceFiber = await ctx.plugin(TestPersistence)
  525. await expect(ctx.sessionQuery.searchSessions({ query: 'durable' }))
  526. .resolves.toMatchObject({ items: [{ header: durable, live: false, persisted: true }] })
  527. const live = ctx.sessions.prepare(shared.id, { meta: { createdAt: 10, cwd: '/work' } })
  528. live.append('user/message', { content: [{ type: 'text', text: 'live needle' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  529. const detach = ctx.sessions.enter(live)
  530. ctx.sessions.announce(live)
  531. await expect(ctx.sessionQuery.searchSessions({ query: 'persisted' })).resolves.toEqual({ items: [] })
  532. await expect(ctx.sessionQuery.searchSessions({ query: 'live' }))
  533. .resolves.toMatchObject({ items: [{ header: shared, live: true, persisted: true }] })
  534. detach()
  535. await expect(ctx.sessionQuery.searchSessions({ query: 'persisted' }))
  536. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  537. await persistenceFiber.dispose()
  538. await expect(ctx.sessionQuery.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  539. await expect(ctx.sessionQuery.searchEvents({ sessionId: durable.id, query: 'needle' }))
  540. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  541. })
  542. it('does not load a persisted log while the same session is live', async () => {
  543. const shared = header('checkpointed-live', 10)
  544. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  545. const ctx = await liveContext()
  546. const live = ctx.sessions.prepare(shared.id, {
  547. seed: messageEvents('live needle'),
  548. meta: { createdAt: shared.createdAt },
  549. })
  550. const detach = ctx.sessions.enter(live)
  551. ctx.sessions.announce(live)
  552. const persistence = await ctx.plugin(TestPersistence)
  553. await expect(ctx.sessionQuery.searchSessions({
  554. query: 'live',
  555. sessionFilters: [{ kind: 'availability', values: ['persisted'] }],
  556. })).resolves.toMatchObject({
  557. items: [{ header: shared, live: true, persisted: true }],
  558. })
  559. expect(TestPersistence.loads.get(shared.id)).toBeUndefined()
  560. expect(TestPersistence.inspections.get(shared.id)).toBeUndefined()
  561. detach()
  562. await expect(ctx.sessionQuery.searchSessions({ query: 'persisted' }))
  563. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  564. expect(TestPersistence.loads.get(shared.id)).toBeUndefined()
  565. expect(TestPersistence.inspections.get(shared.id)).toBe(1)
  566. await persistence.dispose()
  567. })
  568. it('retries when a live owner attaches during persistence observation', async () => {
  569. TestPersistence.reset()
  570. const ctx = await liveContext()
  571. await ctx.plugin(TestPersistence)
  572. TestPersistence.snapshotEffect = () => {
  573. TestPersistence.snapshotEffect = undefined
  574. ctx.sessions.create(SessionId('attached'), { seed: messageEvents('attached needle') })
  575. }
  576. await expect(ctx.sessionQuery.searchSessions({ query: 'attached' }))
  577. .resolves.toMatchObject({ items: [{ header: { id: SessionId('attached') } }] })
  578. })
  579. it('cannot crash-repair a log when live ownership begins during persisted inspection', async () => {
  580. const shared = header('attach-during-inspect', 10)
  581. const persistedEvents = messageEvents('persisted needle')
  582. TestPersistence.reset([{ meta: shared, events: persistedEvents }])
  583. const ctx = await liveContext()
  584. await ctx.plugin(TestPersistence)
  585. TestPersistence.loadEffect = (entry) => {
  586. entry.events = messageEvents('incorrect repair')
  587. }
  588. TestPersistence.inspectEffect = () => {
  589. ctx.sessions.create(shared.id, {
  590. seed: messageEvents('live needle'),
  591. meta: { createdAt: shared.createdAt },
  592. })
  593. }
  594. await expect(ctx.sessionQuery.searchSessions({ query: 'live' }))
  595. .resolves.toMatchObject({ items: [{ header: shared, live: true, persisted: true }] })
  596. expect(TestPersistence.loads.get(shared.id)).toBeUndefined()
  597. expect(TestPersistence.entries.get(shared.id)?.events).toEqual(persistedEvents)
  598. })
  599. it('retries when one live owner replaces another during persistence observation', async () => {
  600. TestPersistence.reset()
  601. const ctx = await liveContext()
  602. const first = ctx.sessions.prepare(SessionId('first'), { seed: messageEvents('first needle') })
  603. const detachFirst = ctx.sessions.enter(first)
  604. ctx.sessions.announce(first)
  605. await ctx.plugin(TestPersistence)
  606. TestPersistence.snapshotEffect = () => {
  607. TestPersistence.snapshotEffect = undefined
  608. detachFirst()
  609. ctx.sessions.create(SessionId('second'), { seed: messageEvents('second needle') })
  610. }
  611. await expect(ctx.sessionQuery.searchSessions({ query: 'second' }))
  612. .resolves.toMatchObject({ items: [{ header: { id: SessionId('second') } }] })
  613. })
  614. it('uses the reconciled persistence binding through the query boundary', async () => {
  615. const durable = header('post-reconcile-unmount')
  616. TestPersistence.reset([{ meta: durable, events: [
  617. ...messageEvents('durable needle', 1),
  618. { ...messageEvents('durable needle again', 2)[0]!, seq: 1 },
  619. ] }])
  620. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 2 })
  621. const persistence = await ctx.plugin(TestPersistence)
  622. const internals = ctx.sessionQuery as unknown as {
  623. _reconcile(signal: AbortSignal | undefined): Promise<{
  624. identity: symbol
  625. service?: SessionPersistence
  626. }>
  627. }
  628. const reconcile = internals._reconcile.bind(internals)
  629. const boundary = vi.spyOn(internals, '_reconcile').mockImplementation(async (signal) => {
  630. const binding = await reconcile(signal)
  631. await persistence.dispose()
  632. return binding
  633. })
  634. const page = await ctx.sessionQuery.searchEvents({
  635. sessionId: durable.id,
  636. query: 'needle',
  637. limit: 1,
  638. })
  639. expect(page.items).toMatchObject([{ sessionId: durable.id }])
  640. expect(page.nextCursor).toEqual(expect.any(String))
  641. boundary.mockRestore()
  642. await expect(ctx.sessionQuery.searchEvents({ sessionId: durable.id, query: 'needle' }))
  643. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  644. })
  645. it('discards a stale list rejection when persistence unmounts during observation', async () => {
  646. const durable = header('racing')
  647. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  648. const ctx = await liveContext()
  649. const persistenceFiber = await ctx.plugin(TestPersistence)
  650. let release!: () => void
  651. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  652. let markStarted!: () => void
  653. const started = new Promise<void>((resolve) => { markStarted = resolve })
  654. TestPersistence.listStarted = () => {
  655. TestPersistence.listStarted = undefined
  656. markStarted()
  657. }
  658. const search = ctx.sessionQuery.searchSessions({ query: 'needle' })
  659. await started
  660. await persistenceFiber.dispose()
  661. TestPersistence.failure = new Error('stale backend rejection')
  662. release()
  663. await expect(search).resolves.toEqual({ items: [] })
  664. })
  665. it('retries against a replacement after the prior binding rejects', async () => {
  666. const durable = header('replacement')
  667. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  668. const ctx = await liveContext()
  669. const prior = await ctx.plugin(TestPersistence)
  670. let rejectPrior!: (reason: unknown) => void
  671. TestPersistence.listGate = new Promise<void>((_resolve, reject) => { rejectPrior = reject })
  672. let markStarted!: () => void
  673. const started = new Promise<void>((resolve) => { markStarted = resolve })
  674. TestPersistence.listStarted = () => {
  675. TestPersistence.listStarted = undefined
  676. markStarted()
  677. }
  678. const search = ctx.sessionQuery.searchSessions({ query: 'needle' })
  679. await started
  680. await prior.dispose()
  681. TestPersistence.listGate = undefined
  682. const replacement = await ctx.plugin(TestPersistence)
  683. rejectPrior(new Error('stale prior binding'))
  684. await expect(search).resolves.toMatchObject({ items: [{ header: durable }] })
  685. await replacement.dispose()
  686. })
  687. it('reloads a replacement source even when its opaque revisions collide', async () => {
  688. const durable = header('colliding-replacement')
  689. TestPersistence.reset([{ meta: durable, events: messageEvents('old content') }])
  690. const revision = TestPersistence.revisions.get(durable.id)!
  691. const ctx = await liveContext()
  692. const prior = await ctx.plugin(TestPersistence)
  693. await expect(ctx.sessionQuery.searchSessions({ query: 'old' }))
  694. .resolves.toMatchObject({ items: [{ header: durable }] })
  695. await prior.dispose()
  696. TestPersistence.set({ meta: durable, events: messageEvents('new needle') })
  697. TestPersistence.revisions.set(durable.id, revision)
  698. const replacement = await ctx.plugin(TestPersistence)
  699. const page = await ctx.sessionQuery.searchSessions({ query: 'new needle' })
  700. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  701. expect(page).toMatchObject({ items: [{ header: durable }] })
  702. await expect(ctx.sessionQuery.searchSessions({ query: 'old' })).resolves.toEqual({ items: [] })
  703. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  704. await replacement.dispose()
  705. })
  706. it('retries when a successful observation belongs to a source unmounted during listing', async () => {
  707. const durable = header('successful-unmount')
  708. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  709. const ctx = await liveContext()
  710. const persistence = await ctx.plugin(TestPersistence)
  711. let lists = 0
  712. TestPersistence.snapshotEffect = async () => {
  713. lists += 1
  714. if (lists === 2) await persistence.dispose()
  715. }
  716. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' })).resolves.toEqual({ items: [] })
  717. expect(lists).toBe(2)
  718. })
  719. it('retries when the snapshot population changes during observation', async () => {
  720. const first = header('first')
  721. const added = header('added-during-list')
  722. TestPersistence.reset([{ meta: first, events: messageEvents('first needle') }])
  723. const ctx = await liveContext()
  724. await ctx.plugin(TestPersistence)
  725. TestPersistence.snapshotEffect = () => {
  726. TestPersistence.snapshotEffect = undefined
  727. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  728. }
  729. const page = await ctx.sessionQuery.searchSessions({ query: 'needle' })
  730. expect(page.items.map(item => item.header.id).sort()).toEqual([added.id, first.id].sort())
  731. expect(TestPersistence.inspections.get(first.id)).toBe(2)
  732. expect(TestPersistence.inspections.get(added.id)).toBe(1)
  733. })
  734. it('fails after one retry when persistence snapshots keep changing', async () => {
  735. const durable = header('continuous-mutation')
  736. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  737. const ctx = await liveContext()
  738. await ctx.plugin(TestPersistence)
  739. let lists = 0
  740. TestPersistence.snapshotEffect = () => {
  741. lists += 1
  742. TestPersistence.set({ meta: durable, events: messageEvents(`durable needle ${lists}`) })
  743. }
  744. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  745. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  746. expect(lists).toBe(4)
  747. })
  748. it('retries if the persistence binding changes while live sessions are observed', async () => {
  749. const durable = header('live-boundary-retry')
  750. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  751. const ctx = await liveContext()
  752. await ctx.plugin(TestPersistence)
  753. const internals = ctx.sessionQuery as unknown as {
  754. _persistenceBinding: { identity: symbol; service?: SessionPersistence }
  755. }
  756. const originalList = ctx.sessions.list.bind(ctx.sessions)
  757. let bumped = false
  758. const list = vi.spyOn(ctx.sessions, 'list').mockImplementation(() => {
  759. if (!bumped) {
  760. bumped = true
  761. internals._persistenceBinding = {
  762. ...internals._persistenceBinding,
  763. identity: Symbol(),
  764. }
  765. }
  766. return originalList()
  767. })
  768. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  769. .resolves.toMatchObject({ items: [{ header: durable }] })
  770. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  771. list.mockRestore()
  772. })
  773. it('rejects malformed snapshots and preserves typed persistence failures', async () => {
  774. const durable = header('invalid-snapshot')
  775. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  776. const ctx = await liveContext()
  777. await ctx.plugin(TestPersistence)
  778. TestPersistence.snapshotOverride = () => 'not-an-array' as never
  779. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  780. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  781. TestPersistence.snapshotOverride = () => [{ header: durable, revision: 1 as never }]
  782. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  783. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  784. TestPersistence.snapshotOverride = () => [
  785. { header: durable, revision: SessionPersistenceRevision('duplicate:1') },
  786. { header: durable, revision: SessionPersistenceRevision('duplicate:2') },
  787. ]
  788. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  789. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  790. TestPersistence.snapshotOverride = undefined
  791. const typed = new SessionQueryError('typed persistence failure', 'SESSION_QUERY_PERSISTENCE_FAILED')
  792. TestPersistence.failure = typed
  793. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' })).rejects.toBe(typed)
  794. })
  795. it('rejects immutable header conflicts between live and persisted sources', async () => {
  796. const shared = header('conflict', 10, { delegationDepth: 1 })
  797. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  798. const ctx = await liveContext()
  799. await ctx.plugin(TestPersistence)
  800. ctx.sessions.create(shared.id, {
  801. seed: messageEvents('live needle'),
  802. meta: { createdAt: 10, delegationDepth: 2 },
  803. })
  804. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  805. .rejects.toThrow(expectCode('SESSION_QUERY_SOURCE_CONFLICT'))
  806. })
  807. it('preserves unchanged persisted generations while reconciling new, changed, and deleted rows', async () => {
  808. const path = await temporaryPath()
  809. const unchanged = header('unchanged')
  810. const changed = header('changed')
  811. const deleted = header('deleted')
  812. TestPersistence.reset([
  813. { meta: unchanged, events: messageEvents('unchanged needle') },
  814. { meta: changed, events: messageEvents('old needle') },
  815. { meta: deleted, events: messageEvents('deleted needle') },
  816. ])
  817. const first = new Context()
  818. await first.plugin(SessionStore)
  819. const firstPersistence = await first.plugin(TestPersistence)
  820. const firstSearch = await first.plugin(SessionQuerySqlite, { path })
  821. await first.sessionQuery.searchSessions({ query: 'needle' })
  822. expect(Object.fromEntries(TestPersistence.inspections)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  823. await first.sessionQuery.searchSessions({ query: 'needle' })
  824. expect(Object.fromEntries(TestPersistence.inspections)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  825. await firstSearch.dispose()
  826. await firstPersistence.dispose()
  827. const beforeDb = new DatabaseSync(path)
  828. const beforeRows = beforeDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  829. beforeDb.close()
  830. const before = new Map(beforeRows.map(row => [row.id, row.generation]))
  831. const added = header('added')
  832. TestPersistence.entries.delete(deleted.id)
  833. TestPersistence.set({ meta: changed, events: messageEvents('changed needle') })
  834. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  835. const second = new Context()
  836. await second.plugin(SessionStore)
  837. const secondPersistence = await second.plugin(TestPersistence)
  838. const secondSearch = await second.plugin(SessionQuerySqlite, { path })
  839. const result = await second.sessionQuery.searchSessions({ query: 'needle' })
  840. expect(result.items.map(item => item.header.id).sort()).toEqual([added.id, changed.id, unchanged.id].sort())
  841. expect(Object.fromEntries(TestPersistence.inspections)).toEqual({
  842. unchanged: 1,
  843. changed: 2,
  844. deleted: 1,
  845. added: 1,
  846. })
  847. await secondSearch.dispose()
  848. await secondPersistence.dispose()
  849. const afterDb = new DatabaseSync(path)
  850. const afterRows = afterDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  851. afterDb.close()
  852. const after = new Map(afterRows.map(row => [row.id, row.generation]))
  853. expect(after.get(unchanged.id)).toBe(before.get(unchanged.id))
  854. expect(after.get(changed.id)).toBeGreaterThan(before.get(changed.id)!)
  855. expect(after.has(deleted.id)).toBe(false)
  856. expect(after.has(added.id)).toBe(true)
  857. })
  858. it('drops connection-local live overlays on reopen and retains persistent bases', async () => {
  859. const path = await temporaryPath()
  860. const shared = header('shared', 10)
  861. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  862. const first = new Context()
  863. await first.plugin(SessionStore)
  864. const persistence = await first.plugin(TestPersistence)
  865. const live = first.sessions.create(shared.id, { seed: messageEvents('live needle'), meta: { createdAt: 10 } })
  866. const search = await first.plugin(SessionQuerySqlite, { path })
  867. await expect(first.sessionQuery.searchEvents({ sessionId: live.id, query: 'live' })).resolves.toMatchObject({ items: [{}] })
  868. await search.dispose()
  869. await persistence.dispose()
  870. const second = new Context()
  871. await second.plugin(SessionStore)
  872. const persistenceAgain = await second.plugin(TestPersistence)
  873. const searchAgain = await second.plugin(SessionQuerySqlite, { path })
  874. await expect(second.sessionQuery.searchSessions({ query: 'live' })).resolves.toEqual({ items: [] })
  875. await expect(second.sessionQuery.searchSessions({ query: 'persisted' }))
  876. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  877. expect(TestPersistence.inspections.get(shared.id)).toBe(1)
  878. await searchAgain.dispose()
  879. await persistenceAgain.dispose()
  880. })
  881. it('refreshes after an external mutating load repair without loading from the query path', async () => {
  882. const durable = header('repair')
  883. TestPersistence.reset([{ meta: durable, events: messageEvents('before repair') }])
  884. const ctx = await liveContext()
  885. const persistence = await ctx.plugin(TestPersistence)
  886. await expect(ctx.sessionQuery.searchSessions({ query: 'before' }))
  887. .resolves.toMatchObject({ items: [{ header: durable }] })
  888. TestPersistence.loadEffect = (entry) => {
  889. entry.events = messageEvents('repaired needle')
  890. }
  891. await ctx.sessionPersistence.load(durable.id)
  892. await expect(ctx.sessionQuery.searchSessions({ query: 'repaired' }))
  893. .resolves.toMatchObject({ items: [{ header: durable }] })
  894. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  895. await ctx.sessionQuery.searchSessions({ query: 'repaired' })
  896. expect(TestPersistence.inspections.get(durable.id)).toBe(2)
  897. expect(TestPersistence.loads.get(durable.id)).toBe(1)
  898. await persistence.dispose()
  899. })
  900. it('recovers on the next search after source and SQLite transaction failures', async () => {
  901. TestPersistence.reset([{ meta: header('durable'), events: messageEvents('durable needle') }])
  902. const ctx = await liveContext()
  903. await ctx.plugin(TestPersistence)
  904. TestPersistence.failure = 'offline'
  905. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  906. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  907. const signal = new AbortController().signal
  908. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal }))
  909. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  910. TestPersistence.failure = new Error('still offline')
  911. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal }))
  912. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  913. TestPersistence.failure = undefined
  914. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' })).resolves.toMatchObject({ items: [{}] })
  915. const live = ctx.sessions.create(SessionId('live'), { seed: messageEvents('base') })
  916. await ctx.sessionQuery.searchEvents({ sessionId: live.id, query: 'base' })
  917. const db = (ctx.sessionQuery as unknown as { _db: DatabaseSync })._db
  918. db.exec('PRAGMA query_only = ON')
  919. live.append('user/message', { content: [{ type: 'text', text: 'retry needle' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  920. await expect(ctx.sessionQuery.searchEvents({ sessionId: live.id, query: 'needle' }))
  921. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  922. db.exec('PRAGMA query_only = OFF')
  923. await expect(ctx.sessionQuery.searchEvents({ sessionId: live.id, query: 'needle' }))
  924. .resolves.toMatchObject({ items: [{ seq: 1 }] })
  925. })
  926. })
  927. describe('SQLite schema, cancellation, and real persistence integration', () => {
  928. it('creates a new database and WAL sidecars owner-only without changing its parent mode', async () => {
  929. if (process.platform === 'win32') return
  930. const path = await temporaryPath()
  931. const directory = dirname(path)
  932. await chmod(directory, 0o755)
  933. const ctx = await liveContext({ path })
  934. await ctx.sessionQuery.searchSessions({ query: 'needle' })
  935. expect((await stat(directory)).mode & 0o777).toBe(0o755)
  936. expect((await stat(path)).mode & 0o777).toBe(0o600)
  937. expect((await stat(`${path}-wal`)).mode & 0o777).toBe(0o600)
  938. expect((await stat(`${path}-shm`)).mode & 0o777).toBe(0o600)
  939. await (ctx.sessionQuery as SessionQuerySqlite).close()
  940. })
  941. it('creates a persistent rollback journal owner-only', async () => {
  942. if (process.platform === 'win32') return
  943. const path = await temporaryPath()
  944. const ctx = await liveContext({ path, journalMode: 'persist' })
  945. await ctx.sessionQuery.searchSessions({ query: 'needle' })
  946. expect((await stat(path)).mode & 0o777).toBe(0o600)
  947. expect((await stat(`${path}-journal`)).mode & 0o777).toBe(0o600)
  948. await (ctx.sessionQuery as SessionQuerySqlite).close()
  949. })
  950. it('preserves the mode of an existing database file', async () => {
  951. if (process.platform === 'win32') return
  952. const path = await temporaryPath()
  953. await writeFile(path, '', { mode: 0o644 })
  954. await chmod(path, 0o644)
  955. const ctx = await liveContext({ path, journalMode: 'delete' })
  956. await ctx.sessionQuery.searchSessions({ query: 'needle' })
  957. expect((await stat(path)).mode & 0o777).toBe(0o644)
  958. await (ctx.sessionQuery as SessionQuerySqlite).close()
  959. })
  960. it('surfaces filesystem failures while pre-creating the database', async () => {
  961. const path = `${await temporaryPath()}\0`
  962. const ctx = new Context()
  963. await ctx.plugin(SessionStore)
  964. await expect(ctx.plugin(SessionQuerySqlite, { path })).rejects.toMatchObject({
  965. code: 'SESSION_QUERY_INDEX_FAILED',
  966. cause: { code: 'ERR_INVALID_ARG_VALUE' },
  967. })
  968. expect(ctx.sessionQuery).toBeUndefined()
  969. })
  970. it('resets a recognized incompatible schema but refuses unknown or foreign tables', async () => {
  971. const stalePath = await temporaryPath('stale.db')
  972. const staleOwner = await liveContext({ path: stalePath })
  973. await (staleOwner.sessionQuery as SessionQuerySqlite).close()
  974. const stale = new DatabaseSync(stalePath)
  975. stale.exec('PRAGMA user_version = 999')
  976. stale.close()
  977. const staleCtx = await liveContext({ path: stalePath })
  978. staleCtx.sessions.create(SessionId('live'), { seed: messageEvents('needle') })
  979. await staleCtx.sessionQuery.searchSessions({ query: 'needle' })
  980. await (staleCtx.sessionQuery as SessionQuerySqlite).close()
  981. const rebuilt = new DatabaseSync(stalePath)
  982. expect((rebuilt.prepare('PRAGMA user_version').get() as { user_version: number }).user_version)
  983. .toBe(SESSION_QUERY_SQLITE_SCHEMA_VERSION)
  984. rebuilt.close()
  985. const augmentedPath = await temporaryPath('augmented.db')
  986. const augmentedOwner = await liveContext({ path: augmentedPath })
  987. await (augmentedOwner.sessionQuery as SessionQuerySqlite).close()
  988. const augmented = new DatabaseSync(augmentedPath)
  989. augmented.exec('CREATE TABLE unrelated(value TEXT)')
  990. augmented.exec("INSERT INTO unrelated VALUES ('safe')")
  991. augmented.exec('PRAGMA user_version = 999')
  992. augmented.close()
  993. const augmentedCtx = new Context()
  994. await augmentedCtx.plugin(SessionStore)
  995. await expect(augmentedCtx.plugin(SessionQuerySqlite, { path: augmentedPath }))
  996. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  997. expect(augmentedCtx.sessionQuery).toBeUndefined()
  998. const stillAugmented = new DatabaseSync(augmentedPath)
  999. expect(stillAugmented.prepare('SELECT value FROM unrelated').get()).toEqual({ value: 'safe' })
  1000. expect(stillAugmented.prepare('PRAGMA user_version').get()).toEqual({ user_version: 999 })
  1001. stillAugmented.close()
  1002. const currentAugmentedPath = await temporaryPath('current-augmented.db')
  1003. const currentAugmentedOwner = await liveContext({ path: currentAugmentedPath })
  1004. await (currentAugmentedOwner.sessionQuery as SessionQuerySqlite).close()
  1005. const currentAugmented = new DatabaseSync(currentAugmentedPath)
  1006. currentAugmented.exec('CREATE TABLE unrelated(value TEXT)')
  1007. currentAugmented.exec("INSERT INTO unrelated VALUES ('safe')")
  1008. currentAugmented.close()
  1009. const currentAugmentedCtx = new Context()
  1010. await currentAugmentedCtx.plugin(SessionStore)
  1011. await expect(currentAugmentedCtx.plugin(SessionQuerySqlite, {
  1012. path: currentAugmentedPath,
  1013. journalMode: 'delete',
  1014. })).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1015. expect(currentAugmentedCtx.sessionQuery).toBeUndefined()
  1016. const stillCurrentAugmented = new DatabaseSync(currentAugmentedPath)
  1017. expect(stillCurrentAugmented.prepare('SELECT value FROM unrelated').get()).toEqual({ value: 'safe' })
  1018. expect(stillCurrentAugmented.prepare('PRAGMA user_version').get())
  1019. .toEqual({ user_version: SESSION_QUERY_SQLITE_SCHEMA_VERSION })
  1020. expect(stillCurrentAugmented.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  1021. stillCurrentAugmented.close()
  1022. const foreignPath = await temporaryPath('foreign.db')
  1023. const foreign = new DatabaseSync(foreignPath)
  1024. foreign.exec('PRAGMA journal_mode = WAL')
  1025. foreign.exec('CREATE TABLE canonical(value TEXT)')
  1026. foreign.exec("INSERT INTO canonical VALUES ('safe')")
  1027. foreign.close()
  1028. const foreignCtx = new Context()
  1029. await foreignCtx.plugin(SessionStore)
  1030. await expect(foreignCtx.plugin(SessionQuerySqlite, { path: foreignPath, journalMode: 'delete' }))
  1031. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1032. expect(foreignCtx.sessionQuery).toBeUndefined()
  1033. const stillForeign = new DatabaseSync(foreignPath)
  1034. expect(stillForeign.prepare('SELECT value FROM canonical').get()).toEqual({ value: 'safe' })
  1035. expect(stillForeign.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  1036. stillForeign.close()
  1037. const otherAppPath = await temporaryPath('other-app.db')
  1038. const otherApp = new DatabaseSync(otherAppPath)
  1039. otherApp.exec('PRAGMA application_id = 123')
  1040. otherApp.close()
  1041. const otherAppCtx = new Context()
  1042. await otherAppCtx.plugin(SessionStore)
  1043. await expect(otherAppCtx.plugin(SessionQuerySqlite, { path: otherAppPath }))
  1044. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1045. expect(otherAppCtx.sessionQuery).toBeUndefined()
  1046. })
  1047. it('fails plugin initialization without an unhandled rejection or partial service', async () => {
  1048. const path = await temporaryPath('never-queried.db')
  1049. const foreign = new DatabaseSync(path)
  1050. foreign.exec('CREATE TABLE canonical(value TEXT)')
  1051. foreign.close()
  1052. const unhandled: unknown[] = []
  1053. const onUnhandled = (reason: unknown) => { unhandled.push(reason) }
  1054. process.on('unhandledRejection', onUnhandled)
  1055. try {
  1056. const ctx = new Context()
  1057. await ctx.plugin(SessionStore)
  1058. await expect(ctx.plugin(SessionQuerySqlite, { path }))
  1059. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1060. await new Promise<void>((resolve) => { setImmediate(resolve) })
  1061. expect(unhandled).toEqual([])
  1062. expect(ctx.sessionQuery).toBeUndefined()
  1063. } finally {
  1064. process.off('unhandledRejection', onUnhandled)
  1065. }
  1066. })
  1067. it('cancels both queued and in-flight source waits without committing them', async () => {
  1068. TestPersistence.reset()
  1069. const ctx = await liveContext()
  1070. await ctx.plugin(TestPersistence)
  1071. const boundaryController = new AbortController()
  1072. const boundary = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: boundaryController.signal })
  1073. queueMicrotask(() => { boundaryController.abort() })
  1074. await expect(boundary).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1075. const readyController = new AbortController()
  1076. readyController.abort()
  1077. const internals = ctx.sessionQuery as unknown as {
  1078. _ensureReady(signal: AbortSignal): Promise<void>
  1079. }
  1080. await expect(internals._ensureReady(readyController.signal))
  1081. .rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1082. let releaseBlocking!: () => void
  1083. TestPersistence.listGate = new Promise<void>((resolve) => { releaseBlocking = resolve })
  1084. let markBlockingStarted!: () => void
  1085. const blockingStarted = new Promise<void>((resolve) => { markBlockingStarted = resolve })
  1086. TestPersistence.listStarted = () => {
  1087. TestPersistence.listStarted = undefined
  1088. markBlockingStarted()
  1089. }
  1090. const blocking = ctx.sessionQuery.searchSessions({ query: 'needle' })
  1091. await blockingStarted
  1092. const queuedController = new AbortController()
  1093. const queued = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: queuedController.signal })
  1094. queuedController.abort()
  1095. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1096. releaseBlocking()
  1097. await expect(blocking).resolves.toEqual({ items: [] })
  1098. TestPersistence.set({
  1099. meta: header('uncommitted'),
  1100. events: messageEvents('durable needle'),
  1101. })
  1102. let releaseActive!: () => void
  1103. TestPersistence.listGate = new Promise<void>((resolve) => { releaseActive = resolve })
  1104. let markActiveStarted!: () => void
  1105. const activeStarted = new Promise<void>((resolve) => { markActiveStarted = resolve })
  1106. TestPersistence.listStarted = () => {
  1107. TestPersistence.listStarted = undefined
  1108. markActiveStarted()
  1109. }
  1110. const activeController = new AbortController()
  1111. const active = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: activeController.signal })
  1112. await activeStarted
  1113. activeController.abort()
  1114. await expect(active).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1115. releaseActive()
  1116. const db = (ctx.sessionQuery as unknown as { _db: DatabaseSync })._db
  1117. expect(db.prepare('SELECT COUNT(*) AS count FROM persisted_sessions').get()).toEqual({ count: 0 })
  1118. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  1119. .resolves.toMatchObject({ items: [{ header: { id: SessionId('uncommitted') } }] })
  1120. })
  1121. it('rejects queued and future work when close waits for an accepted operation', async () => {
  1122. TestPersistence.reset()
  1123. let release!: () => void
  1124. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  1125. let markStarted!: () => void
  1126. const started = new Promise<void>((resolve) => { markStarted = resolve })
  1127. TestPersistence.listStarted = () => {
  1128. TestPersistence.listStarted = undefined
  1129. markStarted()
  1130. }
  1131. const ctx = await liveContext()
  1132. await ctx.plugin(TestPersistence)
  1133. const search = ctx.sessionQuery as SessionQuerySqlite
  1134. const accepted = search.searchSessions({ query: 'needle' })
  1135. await started
  1136. const queued = search.searchSessions({ query: 'needle' })
  1137. const closing = search.close()
  1138. const repeatedClose = search.close()
  1139. expect(repeatedClose).toBe(closing)
  1140. release()
  1141. await expect(accepted).resolves.toEqual({ items: [] })
  1142. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1143. await Promise.all([closing, repeatedClose])
  1144. await expect(search.searchSessions({ query: 'needle' }))
  1145. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1146. expect(search.close()).toBe(closing)
  1147. })
  1148. it('awaits optional-persistence child-fiber quiescence on disposal', async () => {
  1149. TestPersistence.reset()
  1150. const ctx = new Context()
  1151. await ctx.plugin(SessionStore)
  1152. const search = await ctx.plugin(SessionQuerySqlite, { path: ':memory:' })
  1153. const persistence = await ctx.plugin(TestPersistence)
  1154. const optional = (ctx.sessionQuery as unknown as {
  1155. _optionalPersistenceFiber: Fiber
  1156. })._optionalPersistenceFiber
  1157. let release!: () => void
  1158. const cleanup = new Promise<void>((resolve) => { release = resolve })
  1159. optional.ctx.effect(() => () => cleanup)
  1160. let settled = false
  1161. const disposing = search.dispose().then(() => { settled = true })
  1162. await Promise.resolve()
  1163. expect(settled).toBe(false)
  1164. release()
  1165. await disposing
  1166. await persistence.dispose()
  1167. })
  1168. it('combines the real SQLite persistence backend with the real search service keylessly', async () => {
  1169. const persistencePath = await temporaryPath('canonical.db')
  1170. const searchPath = await temporaryPath('derived.db')
  1171. const ctx = new Context()
  1172. await ctx.plugin(SessionStore)
  1173. const persistence = await ctx.plugin(SessionPersistenceSqlite, { path: persistencePath })
  1174. const search = await ctx.plugin(SessionQuerySqlite, { path: searchPath })
  1175. const meta = header('real', 10, { cwd: '/work' })
  1176. await ctx.sessionPersistence.create(meta)
  1177. await ctx.sessionPersistence.append(meta.id, messageEvents('real SQLite needle'))
  1178. await expect(ctx.sessionQuery.searchSessions({ query: 'SQLite needle' }))
  1179. .resolves.toMatchObject({ items: [{ header: meta, persisted: true, live: false }] })
  1180. await expect(ctx.sessionQuery.searchEvents({ sessionId: meta.id, query: 'SQLite needle' }))
  1181. .resolves.toMatchObject({ items: [{ sessionId: meta.id, seq: 0 }] })
  1182. await expect(ctx.sessionQuery.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  1183. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  1184. await search.dispose()
  1185. await expect(ctx.sessionPersistence.load(meta.id)).resolves.toMatchObject({ meta, events: [{ seq: 0 }] })
  1186. await persistence.dispose()
  1187. })
  1188. it('reconciles colliding local revisions when a derived index reopens against another SQLite store', async () => {
  1189. const persistencePathA = await temporaryPath('canonical-a.db')
  1190. const persistencePathB = await temporaryPath('canonical-b.db')
  1191. const searchPath = await temporaryPath('derived-collision.db')
  1192. const shared = header('same-id', 10)
  1193. const first = new Context()
  1194. await first.plugin(SessionStore)
  1195. const persistenceA = await first.plugin(SessionPersistenceSqlite, { path: persistencePathA })
  1196. await first.sessionPersistence.create(shared)
  1197. await first.sessionPersistence.append(shared.id, messageEvents('alpha source'))
  1198. const inspectA = vi.spyOn(first.sessionPersistence, 'inspect')
  1199. const searchA = await first.plugin(SessionQuerySqlite, { path: searchPath })
  1200. await expect(first.sessionQuery.searchSessions({ query: 'alpha' }))
  1201. .resolves.toMatchObject({ items: [{ header: shared }] })
  1202. expect(inspectA).toHaveBeenCalledTimes(1)
  1203. await searchA.dispose()
  1204. await persistenceA.dispose()
  1205. const reopened = new Context()
  1206. await reopened.plugin(SessionStore)
  1207. const persistenceAAgain = await reopened.plugin(SessionPersistenceSqlite, { path: persistencePathA })
  1208. const reopenedInspect = vi.spyOn(reopened.sessionPersistence, 'inspect')
  1209. const searchAAgain = await reopened.plugin(SessionQuerySqlite, { path: searchPath })
  1210. await expect(reopened.sessionQuery.searchSessions({ query: 'alpha' }))
  1211. .resolves.toMatchObject({ items: [{ header: shared }] })
  1212. expect(reopenedInspect).not.toHaveBeenCalled()
  1213. await searchAAgain.dispose()
  1214. await persistenceAAgain.dispose()
  1215. const second = new Context()
  1216. await second.plugin(SessionStore)
  1217. const persistenceB = await second.plugin(SessionPersistenceSqlite, { path: persistencePathB })
  1218. await second.sessionPersistence.create(shared)
  1219. await second.sessionPersistence.append(shared.id, messageEvents('bravo source'))
  1220. const inspectB = vi.spyOn(second.sessionPersistence, 'inspect')
  1221. const searchB = await second.plugin(SessionQuerySqlite, { path: searchPath })
  1222. await expect(second.sessionQuery.searchSessions({ query: 'bravo' }))
  1223. .resolves.toMatchObject({ items: [{ header: shared }] })
  1224. await expect(second.sessionQuery.searchSessions({ query: 'alpha' })).resolves.toEqual({ items: [] })
  1225. expect(inspectB).toHaveBeenCalledTimes(1)
  1226. await searchB.dispose()
  1227. await persistenceB.dispose()
  1228. })
  1229. })