sqlite.spec.ts 63 KB

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