sqlite.spec.ts 80 KB

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