sqlite.spec.ts 63 KB

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