sqlite.spec.ts 63 KB

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