sqlite.spec.ts 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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 wildcardPath = await temporaryPath('sqlite-wildcard.db')
  1040. const wildcard = new DatabaseSync(wildcardPath)
  1041. wildcard.exec('PRAGMA journal_mode = WAL')
  1042. wildcard.exec('CREATE TABLE sqliteX(value TEXT)')
  1043. wildcard.exec("INSERT INTO sqliteX VALUES ('safe')")
  1044. wildcard.close()
  1045. const wildcardCtx = new Context()
  1046. await wildcardCtx.plugin(SessionStore)
  1047. await expect(wildcardCtx.plugin(SessionQuerySqlite, {
  1048. path: wildcardPath,
  1049. journalMode: 'delete',
  1050. })).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1051. expect(wildcardCtx.sessionQuery).toBeUndefined()
  1052. const stillWildcard = new DatabaseSync(wildcardPath)
  1053. expect(stillWildcard.prepare('SELECT value FROM sqliteX').get()).toEqual({ value: 'safe' })
  1054. expect(stillWildcard.prepare('PRAGMA application_id').get()).toEqual({ application_id: 0 })
  1055. expect(stillWildcard.prepare('PRAGMA user_version').get()).toEqual({ user_version: 0 })
  1056. expect(stillWildcard.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  1057. stillWildcard.close()
  1058. const otherAppPath = await temporaryPath('other-app.db')
  1059. const otherApp = new DatabaseSync(otherAppPath)
  1060. otherApp.exec('PRAGMA application_id = 123')
  1061. otherApp.close()
  1062. const otherAppCtx = new Context()
  1063. await otherAppCtx.plugin(SessionStore)
  1064. await expect(otherAppCtx.plugin(SessionQuerySqlite, { path: otherAppPath }))
  1065. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1066. expect(otherAppCtx.sessionQuery).toBeUndefined()
  1067. })
  1068. it('fails plugin initialization without an unhandled rejection or partial service', async () => {
  1069. const path = await temporaryPath('never-queried.db')
  1070. const foreign = new DatabaseSync(path)
  1071. foreign.exec('CREATE TABLE canonical(value TEXT)')
  1072. foreign.close()
  1073. const unhandled: unknown[] = []
  1074. const onUnhandled = (reason: unknown) => { unhandled.push(reason) }
  1075. process.on('unhandledRejection', onUnhandled)
  1076. try {
  1077. const ctx = new Context()
  1078. await ctx.plugin(SessionStore)
  1079. await expect(ctx.plugin(SessionQuerySqlite, { path }))
  1080. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1081. await new Promise<void>((resolve) => { setImmediate(resolve) })
  1082. expect(unhandled).toEqual([])
  1083. expect(ctx.sessionQuery).toBeUndefined()
  1084. } finally {
  1085. process.off('unhandledRejection', onUnhandled)
  1086. }
  1087. })
  1088. it('cancels both queued and in-flight source waits without committing them', async () => {
  1089. TestPersistence.reset()
  1090. const ctx = await liveContext()
  1091. await ctx.plugin(TestPersistence)
  1092. const boundaryController = new AbortController()
  1093. const boundary = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: boundaryController.signal })
  1094. queueMicrotask(() => { boundaryController.abort() })
  1095. await expect(boundary).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1096. const readyController = new AbortController()
  1097. readyController.abort()
  1098. const internals = ctx.sessionQuery as unknown as {
  1099. _ensureReady(signal: AbortSignal): Promise<void>
  1100. }
  1101. await expect(internals._ensureReady(readyController.signal))
  1102. .rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1103. let releaseBlocking!: () => void
  1104. TestPersistence.listGate = new Promise<void>((resolve) => { releaseBlocking = resolve })
  1105. let markBlockingStarted!: () => void
  1106. const blockingStarted = new Promise<void>((resolve) => { markBlockingStarted = resolve })
  1107. TestPersistence.listStarted = () => {
  1108. TestPersistence.listStarted = undefined
  1109. markBlockingStarted()
  1110. }
  1111. const blocking = ctx.sessionQuery.searchSessions({ query: 'needle' })
  1112. await blockingStarted
  1113. const queuedController = new AbortController()
  1114. const queued = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: queuedController.signal })
  1115. queuedController.abort()
  1116. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1117. releaseBlocking()
  1118. await expect(blocking).resolves.toEqual({ items: [] })
  1119. TestPersistence.set({
  1120. meta: header('uncommitted'),
  1121. events: messageEvents('durable needle'),
  1122. })
  1123. let releaseActive!: () => void
  1124. TestPersistence.listGate = new Promise<void>((resolve) => { releaseActive = resolve })
  1125. let markActiveStarted!: () => void
  1126. const activeStarted = new Promise<void>((resolve) => { markActiveStarted = resolve })
  1127. TestPersistence.listStarted = () => {
  1128. TestPersistence.listStarted = undefined
  1129. markActiveStarted()
  1130. }
  1131. const activeController = new AbortController()
  1132. const active = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: activeController.signal })
  1133. await activeStarted
  1134. activeController.abort()
  1135. await expect(active).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  1136. releaseActive()
  1137. const db = (ctx.sessionQuery as unknown as { _db: DatabaseSync })._db
  1138. expect(db.prepare('SELECT COUNT(*) AS count FROM persisted_sessions').get()).toEqual({ count: 0 })
  1139. await expect(ctx.sessionQuery.searchSessions({ query: 'needle' }))
  1140. .resolves.toMatchObject({ items: [{ header: { id: SessionId('uncommitted') } }] })
  1141. })
  1142. it('rejects queued and future work when close waits for an accepted operation', async () => {
  1143. TestPersistence.reset()
  1144. let release!: () => void
  1145. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  1146. let markStarted!: () => void
  1147. const started = new Promise<void>((resolve) => { markStarted = resolve })
  1148. TestPersistence.listStarted = () => {
  1149. TestPersistence.listStarted = undefined
  1150. markStarted()
  1151. }
  1152. const ctx = await liveContext()
  1153. await ctx.plugin(TestPersistence)
  1154. const search = ctx.sessionQuery as SessionQuerySqlite
  1155. const accepted = search.searchSessions({ query: 'needle' })
  1156. await started
  1157. const queued = search.searchSessions({ query: 'needle' })
  1158. const closing = search.close()
  1159. const repeatedClose = search.close()
  1160. expect(repeatedClose).toBe(closing)
  1161. release()
  1162. await expect(accepted).resolves.toEqual({ items: [] })
  1163. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1164. await Promise.all([closing, repeatedClose])
  1165. await expect(search.searchSessions({ query: 'needle' }))
  1166. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  1167. expect(search.close()).toBe(closing)
  1168. })
  1169. it('awaits optional-persistence child-fiber quiescence on disposal', async () => {
  1170. TestPersistence.reset()
  1171. const ctx = new Context()
  1172. await ctx.plugin(SessionStore)
  1173. const search = await ctx.plugin(SessionQuerySqlite, { path: ':memory:' })
  1174. const persistence = await ctx.plugin(TestPersistence)
  1175. const optional = (ctx.sessionQuery as unknown as {
  1176. _optionalPersistenceFiber: Fiber
  1177. })._optionalPersistenceFiber
  1178. let release!: () => void
  1179. const cleanup = new Promise<void>((resolve) => { release = resolve })
  1180. optional.ctx.effect(() => () => cleanup)
  1181. let settled = false
  1182. const disposing = search.dispose().then(() => { settled = true })
  1183. await Promise.resolve()
  1184. expect(settled).toBe(false)
  1185. release()
  1186. await disposing
  1187. await persistence.dispose()
  1188. })
  1189. it('combines the real SQLite persistence backend with the real search service keylessly', async () => {
  1190. const persistencePath = await temporaryPath('canonical.db')
  1191. const searchPath = await temporaryPath('derived.db')
  1192. const ctx = new Context()
  1193. await ctx.plugin(SessionStore)
  1194. const persistence = await ctx.plugin(SessionPersistenceSqlite, { path: persistencePath })
  1195. const search = await ctx.plugin(SessionQuerySqlite, { path: searchPath })
  1196. const meta = header('real', 10, { cwd: '/work' })
  1197. await ctx.sessionPersistence.create(meta)
  1198. await ctx.sessionPersistence.append(meta.id, messageEvents('real SQLite needle'))
  1199. await expect(ctx.sessionQuery.searchSessions({ query: 'SQLite needle' }))
  1200. .resolves.toMatchObject({ items: [{ header: meta, persisted: true, live: false }] })
  1201. await expect(ctx.sessionQuery.searchEvents({ sessionId: meta.id, query: 'SQLite needle' }))
  1202. .resolves.toMatchObject({ items: [{ sessionId: meta.id, seq: 0 }] })
  1203. await expect(ctx.sessionQuery.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  1204. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  1205. await search.dispose()
  1206. await expect(ctx.sessionPersistence.load(meta.id)).resolves.toMatchObject({ meta, events: [{ seq: 0 }] })
  1207. await persistence.dispose()
  1208. })
  1209. it('reconciles colliding local revisions when a derived index reopens against another SQLite store', async () => {
  1210. const persistencePathA = await temporaryPath('canonical-a.db')
  1211. const persistencePathB = await temporaryPath('canonical-b.db')
  1212. const searchPath = await temporaryPath('derived-collision.db')
  1213. const shared = header('same-id', 10)
  1214. const first = new Context()
  1215. await first.plugin(SessionStore)
  1216. const persistenceA = await first.plugin(SessionPersistenceSqlite, { path: persistencePathA })
  1217. await first.sessionPersistence.create(shared)
  1218. await first.sessionPersistence.append(shared.id, messageEvents('alpha source'))
  1219. const inspectA = vi.spyOn(first.sessionPersistence, 'inspect')
  1220. const searchA = await first.plugin(SessionQuerySqlite, { path: searchPath })
  1221. await expect(first.sessionQuery.searchSessions({ query: 'alpha' }))
  1222. .resolves.toMatchObject({ items: [{ header: shared }] })
  1223. expect(inspectA).toHaveBeenCalledTimes(1)
  1224. await searchA.dispose()
  1225. await persistenceA.dispose()
  1226. const reopened = new Context()
  1227. await reopened.plugin(SessionStore)
  1228. const persistenceAAgain = await reopened.plugin(SessionPersistenceSqlite, { path: persistencePathA })
  1229. const reopenedInspect = vi.spyOn(reopened.sessionPersistence, 'inspect')
  1230. const searchAAgain = await reopened.plugin(SessionQuerySqlite, { path: searchPath })
  1231. await expect(reopened.sessionQuery.searchSessions({ query: 'alpha' }))
  1232. .resolves.toMatchObject({ items: [{ header: shared }] })
  1233. expect(reopenedInspect).not.toHaveBeenCalled()
  1234. await searchAAgain.dispose()
  1235. await persistenceAAgain.dispose()
  1236. const second = new Context()
  1237. await second.plugin(SessionStore)
  1238. const persistenceB = await second.plugin(SessionPersistenceSqlite, { path: persistencePathB })
  1239. await second.sessionPersistence.create(shared)
  1240. await second.sessionPersistence.append(shared.id, messageEvents('bravo source'))
  1241. const inspectB = vi.spyOn(second.sessionPersistence, 'inspect')
  1242. const searchB = await second.plugin(SessionQuerySqlite, { path: searchPath })
  1243. await expect(second.sessionQuery.searchSessions({ query: 'bravo' }))
  1244. .resolves.toMatchObject({ items: [{ header: shared }] })
  1245. await expect(second.sessionQuery.searchSessions({ query: 'alpha' })).resolves.toEqual({ items: [] })
  1246. expect(inspectB).toHaveBeenCalledTimes(1)
  1247. await searchB.dispose()
  1248. await persistenceB.dispose()
  1249. })
  1250. })