sqlite.spec.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context, type Fiber } from 'cordis'
  3. import { DatabaseSync } from 'node:sqlite'
  4. import { mkdtemp, rm } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent, SessionHeader, SessionId as SessionIdType } from '@deepseek-ai/dsh-session'
  9. import SessionPersistence, { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence'
  10. import type { SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence'
  11. import SessionPersistenceSqlite from '@deepseek-ai/dsh-session-persistence-sqlite'
  12. import SessionSearchSqlite, {
  13. SESSION_QUERY_SQLITE_APPLICATION_ID,
  14. SESSION_QUERY_SQLITE_SCHEMA_VERSION,
  15. } from '@deepseek-ai/dsh-session-query-sqlite'
  16. import {
  17. SessionQueryError,
  18. SessionSearchCursor,
  19. type SessionAvailability,
  20. type SessionQueryErrorCode,
  21. type SessionSearchRequest,
  22. } from '@deepseek-ai/dsh-session-query'
  23. const temporaryDirectories: string[] = []
  24. afterEach(async () => {
  25. for (const directory of temporaryDirectories.splice(0)) {
  26. await rm(directory, { recursive: true, force: true })
  27. }
  28. })
  29. async function temporaryPath(name = 'search.db'): Promise<string> {
  30. const directory = await mkdtemp(join(tmpdir(), 'dsh-session-search-'))
  31. temporaryDirectories.push(directory)
  32. return join(directory, name)
  33. }
  34. function header(id: string, createdAt = 1, extra: Partial<SessionHeader> = {}): SessionHeader {
  35. return { version: SESSION_FORMAT_VERSION, id: SessionId(id), createdAt, ...extra }
  36. }
  37. function messageEvents(text: string, time = 1): SessionEvent[] {
  38. return [{
  39. type: 'user/message',
  40. seq: 0,
  41. time,
  42. data: { content: [{ type: 'text', text }], source: { kind: 'user' } },
  43. surfaceOp: 'append',
  44. }]
  45. }
  46. function expectCode(code: SessionQueryErrorCode): Error {
  47. return expect.objectContaining({ code }) as Error
  48. }
  49. class TestPersistence extends SessionPersistence {
  50. static entries = new Map<SessionIdType, { meta: SessionHeader; events: SessionEvent[] }>()
  51. static revisions = new Map<SessionIdType, number>()
  52. static nextRevision = 0
  53. static loads = new Map<SessionIdType, number>()
  54. static loadEffect: ((entry: { meta: SessionHeader; events: SessionEvent[] }) => void) | undefined
  55. static listGate: Promise<void> | undefined
  56. static listStarted: (() => void) | undefined
  57. static snapshotEffect: (() => void | Promise<void>) | undefined
  58. static snapshotOverride: (() => SessionPersistenceSnapshot[]) | undefined
  59. static failure: unknown
  60. static reset(entries: readonly { meta: SessionHeader; events: SessionEvent[] }[] = []): void {
  61. this.entries = new Map()
  62. this.revisions = new Map()
  63. this.loads = new Map()
  64. this.loadEffect = undefined
  65. for (const entry of entries) this.set(entry)
  66. this.listGate = undefined
  67. this.listStarted = undefined
  68. this.snapshotEffect = undefined
  69. this.snapshotOverride = undefined
  70. this.failure = undefined
  71. }
  72. static set(entry: { meta: SessionHeader; events: SessionEvent[] }): void {
  73. this.entries.set(entry.meta.id, structuredClone(entry))
  74. this.revisions.set(entry.meta.id, ++this.nextRevision)
  75. }
  76. create(meta: SessionHeader): Promise<void> {
  77. TestPersistence.set({ meta, events: [] })
  78. return Promise.resolve()
  79. }
  80. append(id: SessionIdType, events: readonly SessionEvent[]): Promise<void> {
  81. const entry = TestPersistence.entries.get(id)
  82. if (entry === undefined) return Promise.reject(new Error('missing test session'))
  83. entry.events.push(...structuredClone(events))
  84. TestPersistence.revisions.set(id, ++TestPersistence.nextRevision)
  85. return Promise.resolve()
  86. }
  87. async load(id: SessionIdType): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  88. TestPersistence.loads.set(id, (TestPersistence.loads.get(id) ?? 0) + 1)
  89. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  90. const entry = TestPersistence.entries.get(id)
  91. if (entry === undefined) throw new Error('missing test session')
  92. if (TestPersistence.loadEffect !== undefined) {
  93. const effect = TestPersistence.loadEffect
  94. TestPersistence.loadEffect = undefined
  95. effect(entry)
  96. TestPersistence.revisions.set(id, ++TestPersistence.nextRevision)
  97. }
  98. return structuredClone(entry)
  99. }
  100. async list(): Promise<SessionHeader[]> {
  101. TestPersistence.listStarted?.()
  102. await TestPersistence.listGate
  103. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  104. return [...TestPersistence.entries.values()].map(entry => structuredClone(entry.meta))
  105. }
  106. async listSnapshots(): Promise<SessionPersistenceSnapshot[]> {
  107. TestPersistence.listStarted?.()
  108. await TestPersistence.listGate
  109. if (TestPersistence.failure !== undefined) throw TestPersistence.failure
  110. const snapshots = TestPersistence.snapshotOverride?.()
  111. ?? [...TestPersistence.entries.values()].map(entry => ({
  112. header: structuredClone(entry.meta),
  113. revision: SessionPersistenceRevision(`test:${TestPersistence.revisions.get(entry.meta.id)}`),
  114. }))
  115. await TestPersistence.snapshotEffect?.()
  116. return snapshots
  117. }
  118. }
  119. async function liveContext(config: ConstructorParameters<typeof SessionSearchSqlite>[1] = { path: ':memory:' }): Promise<Context> {
  120. const ctx = new Context()
  121. await ctx.plugin(SessionStore)
  122. await ctx.plugin(SessionSearchSqlite, config)
  123. return ctx
  124. }
  125. describe('SQLite session search', () => {
  126. it('searches two-character Unicode61 tokens in live-only sessions', async () => {
  127. const ctx = await liveContext({ path: ':memory:', snippetChars: 20 })
  128. const session = ctx.sessions.create(SessionId('live'), { meta: { cwd: '/work', createdAt: 10, seedLength: 1 } })
  129. session.append(
  130. 'user/message',
  131. { content: [{ type: 'text', text: 'An AI helper' }], source: { kind: 'user' } },
  132. { surfaceOp: 'append' },
  133. )
  134. await expect(ctx.sessionSearch.searchEvents({ sessionId: session.id, query: 'AI' }))
  135. .resolves.toMatchObject({ items: [{ sessionId: session.id, seq: 0, snippet: 'An AI helper' }] })
  136. await expect(ctx.sessionSearch.searchSessions({ query: 'AI' }))
  137. .resolves.toMatchObject({ items: [{ header: { ...session.header, seedLength: 1 }, live: true, persisted: false }] })
  138. })
  139. it('searches all surfaces by default and applies metadata before ranking', async () => {
  140. const ctx = await liveContext({ path: ':memory:', defaultLimit: 10, maxLimit: 20 })
  141. const parent = SessionId('parent')
  142. const events: SessionEvent[] = [
  143. { type: 'user/message', seq: 0, time: 10, data: { content: [{ type: 'text', text: 'needle original' }], source: { kind: 'user' } }, surfaceOp: 'append' },
  144. { type: 'assistant/chunk', seq: 1, time: 11, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'needle raw' } } },
  145. { type: 'user/message', seq: 2, time: 12, data: { content: [{ type: 'text', text: 'needle summary' }], source: { kind: 'plugin', plugin: 'test' } }, surfaceOp: { op: 'replace', start: 0, end: 0 } },
  146. { type: 'turn/end', seq: 3, time: 13, data: { turn: 1, reason: { kind: 'error', step: 1, message: 'needle failure' } } },
  147. ]
  148. ctx.sessions.create(SessionId('a'), { seed: events, meta: { cwd: '/a', parentSession: parent, createdAt: 20 } })
  149. ctx.sessions.create(SessionId('b'), { seed: messageEvents('needle peer', 12), meta: { createdAt: 20 } })
  150. const all = await ctx.sessionSearch.searchEvents({ sessionId: SessionId('a'), query: 'needle' })
  151. expect(new Set(all.items.map(item => item.surface))).toEqual(new Set(['current', 'shadowed', 'log-only']))
  152. await expect(ctx.sessionSearch.searchEvents({
  153. sessionId: SessionId('a'),
  154. query: 'needle',
  155. filters: [
  156. { kind: 'seq', from: 2, to: 2 },
  157. { kind: 'time', from: 12, to: 12 },
  158. { kind: 'type', values: ['user/message'] },
  159. { kind: 'surface', values: ['current'] },
  160. ],
  161. })).resolves.toMatchObject({ items: [{ seq: 2, surface: 'current' }] })
  162. const grouped = await ctx.sessionSearch.searchSessions({
  163. query: 'needle',
  164. sessionFilters: [
  165. { kind: 'id', values: [SessionId('a')] },
  166. { kind: 'cwd', values: ['/a'] },
  167. { kind: 'created-at', from: 20, to: 20 },
  168. { kind: 'parent', values: [parent] },
  169. { kind: 'availability', values: ['live'] },
  170. ],
  171. eventFilters: [{ kind: 'surface', values: ['shadowed'] }],
  172. })
  173. expect(grouped.items).toHaveLength(1)
  174. expect(grouped.items[0]).toMatchObject({
  175. header: { id: SessionId('a'), cwd: '/a', parentSession: parent },
  176. live: true,
  177. persisted: false,
  178. bestMatch: { seq: 0, surface: 'shadowed' },
  179. })
  180. })
  181. it('uses literal phrase tokens, stable ties, and bounded Unicode snippets', async () => {
  182. const ctx = await liveContext({ path: ':memory:', defaultLimit: 10, maxLimit: 10, snippetChars: 5 })
  183. ctx.sessions.create(SessionId('a'), { seed: messageEvents('😀😀 alpha beta BRAID 😀😀', 10), meta: { createdAt: 1 } })
  184. ctx.sessions.create(SessionId('b'), { seed: messageEvents('alpha beta', 10), meta: { createdAt: 1 } })
  185. ctx.sessions.create(SessionId('c'), { seed: messageEvents('alpha middle beta', 10), meta: { createdAt: 1 } })
  186. ctx.sessions.create(SessionId('d'), { seed: messageEvents('alpha beta', 10), meta: { createdAt: 1 } })
  187. ctx.sessions.create(SessionId('operator'), { seed: messageEvents('needle OR absent', 10), meta: { createdAt: 1 } })
  188. ctx.sessions.create(SessionId('only'), { seed: messageEvents('needle only', 10), meta: { createdAt: 1 } })
  189. ctx.sessions.create(SessionId('quote'), { seed: messageEvents('say "needle" exactly', 10), meta: { createdAt: 1 } })
  190. const phrase = await ctx.sessionSearch.searchSessions({ query: 'alpha beta' })
  191. expect(phrase.items.map(item => item.header.id)).toEqual([SessionId('b'), SessionId('d'), SessionId('a')])
  192. expect(phrase.items.every(item => Array.from(item.bestMatch.snippet).length <= 5)).toBe(true)
  193. await expect(ctx.sessionSearch.searchSessions({ query: 'AI' })).resolves.toEqual({ items: [] })
  194. await expect(ctx.sessionSearch.searchSessions({ query: 'needle OR absent' }))
  195. .resolves.toMatchObject({ items: [{ header: { id: SessionId('operator') } }] })
  196. await expect(ctx.sessionSearch.searchSessions({ query: 'say "needle"' }))
  197. .resolves.toMatchObject({ items: [{ header: { id: SessionId('quote') } }] })
  198. await expect(ctx.sessionSearch.searchSessions({ query: '*' })).resolves.toEqual({ items: [] })
  199. })
  200. it('ranks live and persisted matches on one source-comparable contract', async () => {
  201. const persisted = header('z-persisted')
  202. TestPersistence.reset([
  203. { meta: persisted, events: messageEvents('needle needle', 10) },
  204. ...Array.from({ length: 12 }, (_, index) => ({
  205. meta: header(`filler-${index}`),
  206. events: messageEvents('needle', 10),
  207. })),
  208. ])
  209. const ctx = await liveContext()
  210. const persistence = await ctx.plugin(TestPersistence)
  211. ctx.sessions.create(SessionId('a-live'), {
  212. seed: messageEvents('needle needle', 10),
  213. meta: { createdAt: persisted.createdAt },
  214. })
  215. const result = await ctx.sessionSearch.searchSessions({
  216. query: 'needle',
  217. sessionFilters: [{ kind: 'id', values: [SessionId('a-live'), persisted.id] }],
  218. })
  219. expect(result.items.map(item => item.header.id)).toEqual([SessionId('a-live'), persisted.id])
  220. await persistence.dispose()
  221. })
  222. it('positions snippets from FTS5 matches across diacritics and punctuation', async () => {
  223. const ctx = await liveContext({ path: ':memory:', snippetChars: 14 })
  224. const session = ctx.sessions.create(SessionId('snippet'), {
  225. seed: messageEvents('long long long—café,\nnext value', 10),
  226. })
  227. const page = await ctx.sessionSearch.searchEvents({ sessionId: session.id, query: 'CAFE' })
  228. expect(page.items).toHaveLength(1)
  229. expect(page.items[0]!.snippet).toContain('café')
  230. expect(page.items[0]!.snippet).toContain('—')
  231. expect(page.items[0]!.snippet).not.toContain('\n')
  232. expect(Array.from(page.items[0]!.snippet).length).toBeLessThanOrEqual(14)
  233. })
  234. it('binds cursors to requests and only invalidates within-session pages for target changes', async () => {
  235. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 5 })
  236. const target = ctx.sessions.create(SessionId('target'), {
  237. seed: [
  238. ...messageEvents('needle one', 10),
  239. { ...messageEvents('needle two', 11)[0]!, seq: 1 },
  240. { ...messageEvents('needle three', 12)[0]!, seq: 2 },
  241. ],
  242. })
  243. ctx.sessions.create(SessionId('other'), { seed: messageEvents('needle other', 10) })
  244. const eventPage = await ctx.sessionSearch.searchEvents({ sessionId: target.id, query: 'needle', limit: 1 })
  245. const sessionPage = await ctx.sessionSearch.searchSessions({ query: 'needle', limit: 1 })
  246. expect(eventPage.nextCursor).toEqual(expect.any(String))
  247. expect(sessionPage.nextCursor).toEqual(expect.any(String))
  248. if (eventPage.nextCursor === undefined || sessionPage.nextCursor === undefined) throw new Error('expected cursors')
  249. const eventKeys = eventPage.items.map(item => `${item.sessionId}:${item.seq}`)
  250. let eventCursor: ReturnType<typeof SessionSearchCursor> | undefined = eventPage.nextCursor
  251. while (eventCursor !== undefined) {
  252. const next = await ctx.sessionSearch.searchEvents({
  253. sessionId: target.id,
  254. query: 'needle',
  255. limit: 1,
  256. cursor: eventCursor,
  257. })
  258. eventKeys.push(...next.items.map(item => `${item.sessionId}:${item.seq}`))
  259. eventCursor = next.nextCursor
  260. }
  261. expect(eventKeys).toHaveLength(3)
  262. expect(new Set(eventKeys).size).toBe(eventKeys.length)
  263. const sessionIds = sessionPage.items.map(item => item.header.id)
  264. let sessionCursor: ReturnType<typeof SessionSearchCursor> | undefined = sessionPage.nextCursor
  265. while (sessionCursor !== undefined) {
  266. const next = await ctx.sessionSearch.searchSessions({ query: 'needle', limit: 1, cursor: sessionCursor })
  267. sessionIds.push(...next.items.map(item => item.header.id))
  268. sessionCursor = next.nextCursor
  269. }
  270. expect(sessionIds).toHaveLength(2)
  271. expect(new Set(sessionIds).size).toBe(sessionIds.length)
  272. ctx.sessions.create(SessionId('unrelated'), { seed: messageEvents('needle unrelated', 20) })
  273. await expect(ctx.sessionSearch.searchEvents({
  274. sessionId: target.id,
  275. query: 'needle',
  276. limit: 1,
  277. cursor: eventPage.nextCursor,
  278. })).resolves.toMatchObject({ items: [{ sessionId: target.id }] })
  279. await expect(ctx.sessionSearch.searchSessions({ query: 'needle', limit: 1, cursor: sessionPage.nextCursor }))
  280. .rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  281. await expect(ctx.sessionSearch.searchEvents({
  282. sessionId: target.id,
  283. query: 'different',
  284. limit: 1,
  285. cursor: eventPage.nextCursor,
  286. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  287. target.append('user/message', { content: [{ type: 'text', text: 'needle four' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  288. await expect(ctx.sessionSearch.searchEvents({
  289. sessionId: target.id,
  290. query: 'needle',
  291. limit: 1,
  292. cursor: eventPage.nextCursor,
  293. })).rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  294. })
  295. it('rejects invalid requests, filters, cursors, and direct config', async () => {
  296. const ctx = await liveContext({ path: ':memory:', defaultLimit: 2, maxLimit: 3 })
  297. const session = ctx.sessions.create(SessionId('valid'), { seed: messageEvents('needle') })
  298. for (const request of [
  299. { sessionId: session.id, query: '' },
  300. { sessionId: session.id, query: 'needle', limit: 0 },
  301. { sessionId: session.id, query: 'needle', limit: 4 },
  302. { sessionId: session.id, query: 'needle', filters: [{ kind: 'seq', from: 2, to: 1 }] },
  303. { sessionId: session.id, query: 'needle', filters: [{ kind: 'surface', values: ['future'] }] },
  304. { sessionId: session.id, query: 'bad\0query' },
  305. ] as const) {
  306. await expect(ctx.sessionSearch.searchEvents(request as never)).rejects.toBeInstanceOf(Error)
  307. }
  308. await expect(ctx.sessionSearch.searchSessions({
  309. query: 'needle',
  310. sessionFilters: [{ kind: 'availability', values: ['remote' as never] }],
  311. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  312. await expect(ctx.sessionSearch.searchSessions({
  313. query: 'needle',
  314. sessionFilters: [{ kind: 'future' } as never],
  315. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  316. await expect(ctx.sessionSearch.searchSessions({
  317. query: 'needle',
  318. eventFilters: [{ kind: 'future' } as never],
  319. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  320. await expect(ctx.sessionSearch.searchEvents({
  321. sessionId: session.id,
  322. query: 'needle',
  323. filters: [{ kind: 'future' } as never],
  324. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  325. await expect(ctx.sessionSearch.searchEvents({
  326. sessionId: session.id,
  327. query: 'needle',
  328. cursor: SessionSearchCursor('not-json'),
  329. }))
  330. .rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  331. await expect(ctx.sessionSearch.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  332. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  333. for (const config of [
  334. { path: '' },
  335. { path: ':memory:', defaultLimit: 0 },
  336. { path: ':memory:', maxLimit: 0 },
  337. { path: ':memory:', snippetChars: 0 },
  338. { path: ':memory:', defaultLimit: 3, maxLimit: 2 },
  339. { path: ':memory:', journalMode: 'memory' },
  340. ]) {
  341. const direct = new Context()
  342. await direct.plugin(SessionStore)
  343. expect(() => new SessionSearchSqlite(direct, config as never))
  344. .toThrow(expectCode('SESSION_QUERY_INVALID_CONFIG'))
  345. }
  346. })
  347. })
  348. describe('SQLite reconciliation and source lifecycle', () => {
  349. it('owns queued request and filter values before waiting for the serializer', async () => {
  350. const durable = header('owned')
  351. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  352. const ctx = await liveContext()
  353. const persistence = await ctx.plugin(TestPersistence)
  354. let release!: () => void
  355. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  356. let markStarted!: () => void
  357. const started = new Promise<void>((resolve) => { markStarted = resolve })
  358. TestPersistence.listStarted = () => {
  359. TestPersistence.listStarted = undefined
  360. markStarted()
  361. }
  362. const blocking = ctx.sessionSearch.searchSessions({ query: 'needle' })
  363. await started
  364. const availability: SessionAvailability[] = ['persisted']
  365. const request: SessionSearchRequest = {
  366. query: 'needle',
  367. sessionFilters: [{ kind: 'availability', values: availability }],
  368. }
  369. const queued = ctx.sessionSearch.searchSessions(request)
  370. request.query = 'absent'
  371. availability[0] = 'live'
  372. release()
  373. await expect(blocking).resolves.toMatchObject({ items: [{ header: durable }] })
  374. await expect(queued).resolves.toMatchObject({ items: [{ header: durable }] })
  375. await persistence.dispose()
  376. })
  377. it('mounts persistence dynamically, shadows with TEMP live rows, reveals, and hides on unmount', async () => {
  378. const shared = header('shared', 10, { cwd: '/work' })
  379. const durable = header('durable', 5)
  380. TestPersistence.reset([
  381. { meta: shared, events: messageEvents('persisted needle') },
  382. { meta: durable, events: messageEvents('durable needle') },
  383. ])
  384. const ctx = await liveContext()
  385. await expect(ctx.sessionSearch.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  386. const persistenceFiber = await ctx.plugin(TestPersistence)
  387. await expect(ctx.sessionSearch.searchSessions({ query: 'durable' }))
  388. .resolves.toMatchObject({ items: [{ header: durable, live: false, persisted: true }] })
  389. const live = ctx.sessions.prepare(shared.id, { meta: { createdAt: 10, cwd: '/work' } })
  390. live.append('user/message', { content: [{ type: 'text', text: 'live needle' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  391. const detach = ctx.sessions.enter(live)
  392. ctx.sessions.announce(live)
  393. await expect(ctx.sessionSearch.searchSessions({ query: 'persisted' })).resolves.toEqual({ items: [] })
  394. await expect(ctx.sessionSearch.searchSessions({ query: 'live' }))
  395. .resolves.toMatchObject({ items: [{ header: shared, live: true, persisted: true }] })
  396. detach()
  397. await expect(ctx.sessionSearch.searchSessions({ query: 'persisted' }))
  398. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  399. await persistenceFiber.dispose()
  400. await expect(ctx.sessionSearch.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  401. await expect(ctx.sessionSearch.searchEvents({ sessionId: durable.id, query: 'needle' }))
  402. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  403. })
  404. it('discards a stale list rejection when persistence unmounts during observation', async () => {
  405. const durable = header('racing')
  406. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  407. const ctx = await liveContext()
  408. const persistenceFiber = await ctx.plugin(TestPersistence)
  409. let release!: () => void
  410. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  411. let markStarted!: () => void
  412. const started = new Promise<void>((resolve) => { markStarted = resolve })
  413. TestPersistence.listStarted = () => {
  414. TestPersistence.listStarted = undefined
  415. markStarted()
  416. }
  417. const search = ctx.sessionSearch.searchSessions({ query: 'needle' })
  418. await started
  419. await persistenceFiber.dispose()
  420. TestPersistence.failure = new Error('stale backend rejection')
  421. release()
  422. await expect(search).resolves.toEqual({ items: [] })
  423. })
  424. it('retries against a replacement after the prior binding rejects', async () => {
  425. const durable = header('replacement')
  426. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  427. const ctx = await liveContext()
  428. const prior = await ctx.plugin(TestPersistence)
  429. let rejectPrior!: (reason: unknown) => void
  430. TestPersistence.listGate = new Promise<void>((_resolve, reject) => { rejectPrior = reject })
  431. let markStarted!: () => void
  432. const started = new Promise<void>((resolve) => { markStarted = resolve })
  433. TestPersistence.listStarted = () => {
  434. TestPersistence.listStarted = undefined
  435. markStarted()
  436. }
  437. const search = ctx.sessionSearch.searchSessions({ query: 'needle' })
  438. await started
  439. await prior.dispose()
  440. TestPersistence.listGate = undefined
  441. const replacement = await ctx.plugin(TestPersistence)
  442. rejectPrior(new Error('stale prior binding'))
  443. await expect(search).resolves.toMatchObject({ items: [{ header: durable }] })
  444. await replacement.dispose()
  445. })
  446. it('reloads a replacement source even when its opaque revisions collide', async () => {
  447. const durable = header('colliding-replacement')
  448. TestPersistence.reset([{ meta: durable, events: messageEvents('old content') }])
  449. const revision = TestPersistence.revisions.get(durable.id)!
  450. const ctx = await liveContext()
  451. const prior = await ctx.plugin(TestPersistence)
  452. await expect(ctx.sessionSearch.searchSessions({ query: 'old' }))
  453. .resolves.toMatchObject({ items: [{ header: durable }] })
  454. await prior.dispose()
  455. TestPersistence.set({ meta: durable, events: messageEvents('new needle') })
  456. TestPersistence.revisions.set(durable.id, revision)
  457. const replacement = await ctx.plugin(TestPersistence)
  458. const internals = ctx.sessionSearch as unknown as {
  459. _lastPersistenceRevision: number
  460. _persistenceRevision: number
  461. }
  462. expect(internals._persistenceRevision).not.toBe(internals._lastPersistenceRevision)
  463. const page = await ctx.sessionSearch.searchSessions({ query: 'new needle' })
  464. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  465. expect(page).toMatchObject({ items: [{ header: durable }] })
  466. await expect(ctx.sessionSearch.searchSessions({ query: 'old' })).resolves.toEqual({ items: [] })
  467. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  468. await replacement.dispose()
  469. })
  470. it('retries when a successful observation belongs to a source unmounted during listing', async () => {
  471. const durable = header('successful-unmount')
  472. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  473. const ctx = await liveContext()
  474. const persistence = await ctx.plugin(TestPersistence)
  475. let lists = 0
  476. TestPersistence.snapshotEffect = async () => {
  477. lists += 1
  478. if (lists === 2) await persistence.dispose()
  479. }
  480. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' })).resolves.toEqual({ items: [] })
  481. expect(lists).toBe(2)
  482. })
  483. it('retries when the snapshot population changes during observation', async () => {
  484. const first = header('first')
  485. const added = header('added-during-list')
  486. TestPersistence.reset([{ meta: first, events: messageEvents('first needle') }])
  487. const ctx = await liveContext()
  488. await ctx.plugin(TestPersistence)
  489. TestPersistence.snapshotEffect = () => {
  490. TestPersistence.snapshotEffect = undefined
  491. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  492. }
  493. const page = await ctx.sessionSearch.searchSessions({ query: 'needle' })
  494. expect(page.items.map(item => item.header.id).sort()).toEqual([added.id, first.id].sort())
  495. expect(TestPersistence.loads.get(first.id)).toBe(2)
  496. expect(TestPersistence.loads.get(added.id)).toBe(1)
  497. })
  498. it('retries if the source revision changes while live sessions are observed', async () => {
  499. const durable = header('live-boundary-retry')
  500. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  501. const ctx = await liveContext()
  502. await ctx.plugin(TestPersistence)
  503. const internals = ctx.sessionSearch as unknown as { _persistenceRevision: number }
  504. const originalList = ctx.sessions.list.bind(ctx.sessions)
  505. let bumped = false
  506. const list = vi.spyOn(ctx.sessions, 'list').mockImplementation(() => {
  507. if (!bumped) {
  508. bumped = true
  509. internals._persistenceRevision += 1
  510. }
  511. return originalList()
  512. })
  513. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  514. .resolves.toMatchObject({ items: [{ header: durable }] })
  515. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  516. list.mockRestore()
  517. })
  518. it('rejects malformed snapshots and preserves typed persistence failures', async () => {
  519. const durable = header('invalid-snapshot')
  520. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  521. const ctx = await liveContext()
  522. await ctx.plugin(TestPersistence)
  523. TestPersistence.snapshotOverride = () => 'not-an-array' as never
  524. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  525. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  526. TestPersistence.snapshotOverride = () => [{ header: durable, revision: 1 as never }]
  527. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  528. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  529. TestPersistence.snapshotOverride = () => [
  530. { header: durable, revision: SessionPersistenceRevision('duplicate:1') },
  531. { header: durable, revision: SessionPersistenceRevision('duplicate:2') },
  532. ]
  533. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  534. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  535. TestPersistence.snapshotOverride = undefined
  536. const typed = new SessionQueryError('typed persistence failure', 'SESSION_QUERY_PERSISTENCE_FAILED')
  537. TestPersistence.failure = typed
  538. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' })).rejects.toBe(typed)
  539. })
  540. it('rejects immutable header conflicts between live and persisted sources', async () => {
  541. const shared = header('conflict', 10)
  542. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  543. const ctx = await liveContext()
  544. await ctx.plugin(TestPersistence)
  545. ctx.sessions.create(shared.id, { seed: messageEvents('live needle'), meta: { createdAt: 11 } })
  546. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  547. .rejects.toThrow(expectCode('SESSION_QUERY_SOURCE_CONFLICT'))
  548. })
  549. it('preserves unchanged persisted generations while reconciling new, changed, and deleted rows', async () => {
  550. const path = await temporaryPath()
  551. const unchanged = header('unchanged')
  552. const changed = header('changed')
  553. const deleted = header('deleted')
  554. TestPersistence.reset([
  555. { meta: unchanged, events: messageEvents('unchanged needle') },
  556. { meta: changed, events: messageEvents('old needle') },
  557. { meta: deleted, events: messageEvents('deleted needle') },
  558. ])
  559. const first = new Context()
  560. await first.plugin(SessionStore)
  561. const firstPersistence = await first.plugin(TestPersistence)
  562. const firstSearch = await first.plugin(SessionSearchSqlite, { path })
  563. await first.sessionSearch.searchSessions({ query: 'needle' })
  564. expect(Object.fromEntries(TestPersistence.loads)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  565. await first.sessionSearch.searchSessions({ query: 'needle' })
  566. expect(Object.fromEntries(TestPersistence.loads)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  567. await firstSearch.dispose()
  568. await firstPersistence.dispose()
  569. const beforeDb = new DatabaseSync(path)
  570. const beforeRows = beforeDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  571. beforeDb.close()
  572. const before = new Map(beforeRows.map(row => [row.id, row.generation]))
  573. const added = header('added')
  574. TestPersistence.entries.delete(deleted.id)
  575. TestPersistence.set({ meta: changed, events: messageEvents('changed needle') })
  576. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  577. const second = new Context()
  578. await second.plugin(SessionStore)
  579. const secondPersistence = await second.plugin(TestPersistence)
  580. const secondSearch = await second.plugin(SessionSearchSqlite, { path })
  581. const result = await second.sessionSearch.searchSessions({ query: 'needle' })
  582. expect(result.items.map(item => item.header.id).sort()).toEqual([added.id, changed.id, unchanged.id].sort())
  583. expect(Object.fromEntries(TestPersistence.loads)).toEqual({
  584. unchanged: 1,
  585. changed: 2,
  586. deleted: 1,
  587. added: 1,
  588. })
  589. await secondSearch.dispose()
  590. await secondPersistence.dispose()
  591. const afterDb = new DatabaseSync(path)
  592. const afterRows = afterDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  593. afterDb.close()
  594. const after = new Map(afterRows.map(row => [row.id, row.generation]))
  595. expect(after.get(unchanged.id)).toBe(before.get(unchanged.id))
  596. expect(after.get(changed.id)).toBeGreaterThan(before.get(changed.id)!)
  597. expect(after.has(deleted.id)).toBe(false)
  598. expect(after.has(added.id)).toBe(true)
  599. })
  600. it('drops connection-local live overlays on reopen and retains persistent bases', async () => {
  601. const path = await temporaryPath()
  602. const shared = header('shared', 10)
  603. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  604. const first = new Context()
  605. await first.plugin(SessionStore)
  606. const persistence = await first.plugin(TestPersistence)
  607. const live = first.sessions.create(shared.id, { seed: messageEvents('live needle'), meta: { createdAt: 10 } })
  608. const search = await first.plugin(SessionSearchSqlite, { path })
  609. await expect(first.sessionSearch.searchEvents({ sessionId: live.id, query: 'live' })).resolves.toMatchObject({ items: [{}] })
  610. await search.dispose()
  611. await persistence.dispose()
  612. const second = new Context()
  613. await second.plugin(SessionStore)
  614. const persistenceAgain = await second.plugin(TestPersistence)
  615. const searchAgain = await second.plugin(SessionSearchSqlite, { path })
  616. await expect(second.sessionSearch.searchSessions({ query: 'live' })).resolves.toEqual({ items: [] })
  617. await expect(second.sessionSearch.searchSessions({ query: 'persisted' }))
  618. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  619. expect(TestPersistence.loads.get(shared.id)).toBe(1)
  620. await searchAgain.dispose()
  621. await persistenceAgain.dispose()
  622. })
  623. it('refreshes the stored revision after a mutating load repair', async () => {
  624. const durable = header('repair')
  625. TestPersistence.reset([{ meta: durable, events: messageEvents('before repair') }])
  626. TestPersistence.loadEffect = (entry) => {
  627. entry.events = messageEvents('repaired needle')
  628. }
  629. const ctx = await liveContext()
  630. await ctx.plugin(TestPersistence)
  631. await expect(ctx.sessionSearch.searchSessions({ query: 'repaired' }))
  632. .resolves.toMatchObject({ items: [{ header: durable }] })
  633. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  634. await ctx.sessionSearch.searchSessions({ query: 'repaired' })
  635. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  636. })
  637. it('recovers on the next search after source and SQLite transaction failures', async () => {
  638. TestPersistence.reset([{ meta: header('durable'), events: messageEvents('durable needle') }])
  639. const ctx = await liveContext()
  640. await ctx.plugin(TestPersistence)
  641. TestPersistence.failure = 'offline'
  642. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  643. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  644. const signal = new AbortController().signal
  645. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal }))
  646. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  647. TestPersistence.failure = new Error('still offline')
  648. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal }))
  649. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  650. TestPersistence.failure = undefined
  651. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' })).resolves.toMatchObject({ items: [{}] })
  652. const live = ctx.sessions.create(SessionId('live'), { seed: messageEvents('base') })
  653. await ctx.sessionSearch.searchEvents({ sessionId: live.id, query: 'base' })
  654. const db = (ctx.sessionSearch as unknown as { _db: DatabaseSync })._db
  655. db.exec('PRAGMA query_only = ON')
  656. live.append('user/message', { content: [{ type: 'text', text: 'retry needle' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  657. await expect(ctx.sessionSearch.searchEvents({ sessionId: live.id, query: 'needle' }))
  658. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  659. db.exec('PRAGMA query_only = OFF')
  660. await expect(ctx.sessionSearch.searchEvents({ sessionId: live.id, query: 'needle' }))
  661. .resolves.toMatchObject({ items: [{ seq: 1 }] })
  662. })
  663. })
  664. describe('SQLite schema, cancellation, and real persistence integration', () => {
  665. it('resets a recognized incompatible derived schema but refuses a foreign database', async () => {
  666. const stalePath = await temporaryPath('stale.db')
  667. const stale = new DatabaseSync(stalePath)
  668. stale.exec(`PRAGMA application_id = ${SESSION_QUERY_SQLITE_APPLICATION_ID}`)
  669. stale.exec('PRAGMA user_version = 999')
  670. stale.exec('CREATE TABLE stale(value TEXT)')
  671. stale.close()
  672. const staleCtx = await liveContext({ path: stalePath })
  673. staleCtx.sessions.create(SessionId('live'), { seed: messageEvents('needle') })
  674. await staleCtx.sessionSearch.searchSessions({ query: 'needle' })
  675. await (staleCtx.sessionSearch as SessionSearchSqlite).close()
  676. const rebuilt = new DatabaseSync(stalePath)
  677. expect((rebuilt.prepare('PRAGMA user_version').get() as { user_version: number }).user_version)
  678. .toBe(SESSION_QUERY_SQLITE_SCHEMA_VERSION)
  679. expect(rebuilt.prepare("SELECT name FROM sqlite_master WHERE name = 'stale'").get()).toBeUndefined()
  680. rebuilt.close()
  681. const foreignPath = await temporaryPath('foreign.db')
  682. const foreign = new DatabaseSync(foreignPath)
  683. foreign.exec('PRAGMA journal_mode = WAL')
  684. foreign.exec('CREATE TABLE canonical(value TEXT)')
  685. foreign.exec("INSERT INTO canonical VALUES ('safe')")
  686. foreign.close()
  687. const foreignCtx = await liveContext({ path: foreignPath, journalMode: 'delete' })
  688. await expect(foreignCtx.sessionSearch.searchSessions({ query: 'needle' }))
  689. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  690. const stillForeign = new DatabaseSync(foreignPath)
  691. expect(stillForeign.prepare('SELECT value FROM canonical').get()).toEqual({ value: 'safe' })
  692. expect(stillForeign.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  693. stillForeign.close()
  694. await (foreignCtx.sessionSearch as SessionSearchSqlite).close()
  695. const otherAppPath = await temporaryPath('other-app.db')
  696. const otherApp = new DatabaseSync(otherAppPath)
  697. otherApp.exec('PRAGMA application_id = 123')
  698. otherApp.close()
  699. const otherAppCtx = await liveContext({ path: otherAppPath })
  700. await expect(otherAppCtx.sessionSearch.searchSessions({ query: 'needle' }))
  701. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  702. await (otherAppCtx.sessionSearch as SessionSearchSqlite).close()
  703. })
  704. it('observes asynchronous open rejection even when no query is made', async () => {
  705. const path = await temporaryPath('never-queried.db')
  706. const foreign = new DatabaseSync(path)
  707. foreign.exec('CREATE TABLE canonical(value TEXT)')
  708. foreign.close()
  709. const unhandled: unknown[] = []
  710. const onUnhandled = (reason: unknown) => { unhandled.push(reason) }
  711. process.on('unhandledRejection', onUnhandled)
  712. try {
  713. const ctx = await liveContext({ path })
  714. await new Promise<void>((resolve) => { setImmediate(resolve) })
  715. expect(unhandled).toEqual([])
  716. await (ctx.sessionSearch as SessionSearchSqlite).close()
  717. } finally {
  718. process.off('unhandledRejection', onUnhandled)
  719. }
  720. })
  721. it('cancels both queued and in-flight source waits without committing them', async () => {
  722. TestPersistence.reset()
  723. const ctx = await liveContext()
  724. await ctx.plugin(TestPersistence)
  725. const boundaryController = new AbortController()
  726. const boundary = ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal: boundaryController.signal })
  727. queueMicrotask(() => { boundaryController.abort() })
  728. await expect(boundary).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  729. const readyController = new AbortController()
  730. readyController.abort()
  731. const internals = ctx.sessionSearch as unknown as {
  732. _ensureReady(signal: AbortSignal): Promise<void>
  733. }
  734. await expect(internals._ensureReady(readyController.signal))
  735. .rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  736. let releaseBlocking!: () => void
  737. TestPersistence.listGate = new Promise<void>((resolve) => { releaseBlocking = resolve })
  738. let markBlockingStarted!: () => void
  739. const blockingStarted = new Promise<void>((resolve) => { markBlockingStarted = resolve })
  740. TestPersistence.listStarted = () => {
  741. TestPersistence.listStarted = undefined
  742. markBlockingStarted()
  743. }
  744. const blocking = ctx.sessionSearch.searchSessions({ query: 'needle' })
  745. await blockingStarted
  746. const queuedController = new AbortController()
  747. const queued = ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal: queuedController.signal })
  748. queuedController.abort()
  749. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  750. releaseBlocking()
  751. await expect(blocking).resolves.toEqual({ items: [] })
  752. TestPersistence.set({
  753. meta: header('uncommitted'),
  754. events: messageEvents('durable needle'),
  755. })
  756. let releaseActive!: () => void
  757. TestPersistence.listGate = new Promise<void>((resolve) => { releaseActive = resolve })
  758. let markActiveStarted!: () => void
  759. const activeStarted = new Promise<void>((resolve) => { markActiveStarted = resolve })
  760. TestPersistence.listStarted = () => {
  761. TestPersistence.listStarted = undefined
  762. markActiveStarted()
  763. }
  764. const activeController = new AbortController()
  765. const active = ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal: activeController.signal })
  766. await activeStarted
  767. activeController.abort()
  768. await expect(active).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  769. releaseActive()
  770. const db = (ctx.sessionSearch as unknown as { _db: DatabaseSync })._db
  771. expect(db.prepare('SELECT COUNT(*) AS count FROM persisted_sessions').get()).toEqual({ count: 0 })
  772. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  773. .resolves.toMatchObject({ items: [{ header: { id: SessionId('uncommitted') } }] })
  774. })
  775. it('rejects queued and future work when close waits for an accepted operation', async () => {
  776. TestPersistence.reset()
  777. let release!: () => void
  778. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  779. let markStarted!: () => void
  780. const started = new Promise<void>((resolve) => { markStarted = resolve })
  781. TestPersistence.listStarted = () => {
  782. TestPersistence.listStarted = undefined
  783. markStarted()
  784. }
  785. const ctx = await liveContext()
  786. await ctx.plugin(TestPersistence)
  787. const search = ctx.sessionSearch as SessionSearchSqlite
  788. const accepted = search.searchSessions({ query: 'needle' })
  789. await started
  790. const queued = search.searchSessions({ query: 'needle' })
  791. const closing = search.close()
  792. const repeatedClose = search.close()
  793. expect(repeatedClose).toBe(closing)
  794. release()
  795. await expect(accepted).resolves.toEqual({ items: [] })
  796. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  797. await Promise.all([closing, repeatedClose])
  798. await expect(search.searchSessions({ query: 'needle' }))
  799. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  800. expect(search.close()).toBe(closing)
  801. })
  802. it('awaits optional-persistence child-fiber quiescence on disposal', async () => {
  803. TestPersistence.reset()
  804. const ctx = new Context()
  805. await ctx.plugin(SessionStore)
  806. const search = await ctx.plugin(SessionSearchSqlite, { path: ':memory:' })
  807. const persistence = await ctx.plugin(TestPersistence)
  808. const optional = (ctx.sessionSearch as unknown as {
  809. _optionalPersistenceFiber: Fiber
  810. })._optionalPersistenceFiber
  811. let release!: () => void
  812. const cleanup = new Promise<void>((resolve) => { release = resolve })
  813. optional.ctx.effect(() => () => cleanup)
  814. let settled = false
  815. const disposing = search.dispose().then(() => { settled = true })
  816. await Promise.resolve()
  817. expect(settled).toBe(false)
  818. release()
  819. await disposing
  820. await persistence.dispose()
  821. })
  822. it('combines the real SQLite persistence backend with the real search service keylessly', async () => {
  823. const persistencePath = await temporaryPath('canonical.db')
  824. const searchPath = await temporaryPath('derived.db')
  825. const ctx = new Context()
  826. await ctx.plugin(SessionStore)
  827. const persistence = await ctx.plugin(SessionPersistenceSqlite, { path: persistencePath })
  828. const search = await ctx.plugin(SessionSearchSqlite, { path: searchPath })
  829. const meta = header('real', 10, { cwd: '/work' })
  830. await ctx.sessionPersistence.create(meta)
  831. await ctx.sessionPersistence.append(meta.id, messageEvents('real SQLite needle'))
  832. await expect(ctx.sessionSearch.searchSessions({ query: 'SQLite needle' }))
  833. .resolves.toMatchObject({ items: [{ header: meta, persisted: true, live: false }] })
  834. await expect(ctx.sessionSearch.searchEvents({ sessionId: meta.id, query: 'SQLite needle' }))
  835. .resolves.toMatchObject({ items: [{ sessionId: meta.id, seq: 0 }] })
  836. await expect(ctx.sessionSearch.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  837. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  838. await search.dispose()
  839. await expect(ctx.sessionPersistence.load(meta.id)).resolves.toMatchObject({ meta, events: [{ seq: 0 }] })
  840. await persistence.dispose()
  841. })
  842. })