sqlite.spec.ts 64 KB

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