sqlite.spec.ts 54 KB

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