1
0

sqlite.spec.ts 83 KB

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