sqlite.spec.ts 74 KB

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