sqlite.spec.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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('invalidates session cursors after transient persistence topology changes', async () => {
  296. TestPersistence.reset()
  297. const ctx = await liveContext({ path: ':memory:', defaultLimit: 1, maxLimit: 5 })
  298. ctx.sessions.create(SessionId('first'), { seed: messageEvents('needle first') })
  299. ctx.sessions.create(SessionId('second'), { seed: messageEvents('needle second') })
  300. const page = await ctx.sessionSearch.searchSessions({ query: 'needle', limit: 1 })
  301. if (page.nextCursor === undefined) throw new Error('expected cursor')
  302. const persistence = await ctx.plugin(TestPersistence)
  303. await persistence.dispose()
  304. await expect(ctx.sessionSearch.searchSessions({
  305. query: 'needle',
  306. limit: 1,
  307. cursor: page.nextCursor,
  308. })).rejects.toThrow(expectCode('SESSION_QUERY_STALE_CURSOR'))
  309. })
  310. it('rejects invalid requests, filters, cursors, and direct config', async () => {
  311. const ctx = await liveContext({ path: ':memory:', defaultLimit: 2, maxLimit: 3 })
  312. const session = ctx.sessions.create(SessionId('valid'), { seed: messageEvents('needle') })
  313. for (const request of [
  314. { sessionId: session.id, query: '' },
  315. { sessionId: session.id, query: 'needle', limit: 0 },
  316. { sessionId: session.id, query: 'needle', limit: 4 },
  317. { sessionId: session.id, query: 'needle', filters: [{ kind: 'seq', from: 2, to: 1 }] },
  318. { sessionId: session.id, query: 'needle', filters: [{ kind: 'surface', values: ['future'] }] },
  319. { sessionId: session.id, query: 'bad\0query' },
  320. ] as const) {
  321. await expect(ctx.sessionSearch.searchEvents(request as never)).rejects.toBeInstanceOf(Error)
  322. }
  323. await expect(ctx.sessionSearch.searchSessions({
  324. query: 'needle',
  325. sessionFilters: [{ kind: 'availability', values: ['remote' as never] }],
  326. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  327. await expect(ctx.sessionSearch.searchSessions({
  328. query: 'needle',
  329. sessionFilters: [{ kind: 'future' } as never],
  330. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  331. await expect(ctx.sessionSearch.searchSessions({
  332. query: 'needle',
  333. eventFilters: [{ kind: 'future' } as never],
  334. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  335. await expect(ctx.sessionSearch.searchEvents({
  336. sessionId: session.id,
  337. query: 'needle',
  338. filters: [{ kind: 'future' } as never],
  339. })).rejects.toThrow(expectCode('SESSION_QUERY_INVALID_FILTER'))
  340. await expect(ctx.sessionSearch.searchEvents({
  341. sessionId: session.id,
  342. query: 'needle',
  343. cursor: SessionSearchCursor('not-json'),
  344. }))
  345. .rejects.toThrow(expectCode('SESSION_QUERY_INVALID_CURSOR'))
  346. await expect(ctx.sessionSearch.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  347. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  348. for (const config of [
  349. { path: '' },
  350. { path: ':memory:', defaultLimit: 0 },
  351. { path: ':memory:', maxLimit: 0 },
  352. { path: ':memory:', snippetChars: 0 },
  353. { path: ':memory:', defaultLimit: 3, maxLimit: 2 },
  354. { path: ':memory:', journalMode: 'memory' },
  355. ]) {
  356. const direct = new Context()
  357. await direct.plugin(SessionStore)
  358. expect(() => new SessionSearchSqlite(direct, config as never))
  359. .toThrow(expectCode('SESSION_QUERY_INVALID_CONFIG'))
  360. }
  361. })
  362. })
  363. describe('SQLite reconciliation and source lifecycle', () => {
  364. it('owns queued request and filter values before waiting for the serializer', async () => {
  365. const durable = header('owned')
  366. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  367. const ctx = await liveContext()
  368. const persistence = await ctx.plugin(TestPersistence)
  369. let release!: () => void
  370. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  371. let markStarted!: () => void
  372. const started = new Promise<void>((resolve) => { markStarted = resolve })
  373. TestPersistence.listStarted = () => {
  374. TestPersistence.listStarted = undefined
  375. markStarted()
  376. }
  377. const blocking = ctx.sessionSearch.searchSessions({ query: 'needle' })
  378. await started
  379. const availability: SessionAvailability[] = ['persisted']
  380. const request: SessionSearchRequest = {
  381. query: 'needle',
  382. sessionFilters: [{ kind: 'availability', values: availability }],
  383. }
  384. const queued = ctx.sessionSearch.searchSessions(request)
  385. request.query = 'absent'
  386. availability[0] = 'live'
  387. release()
  388. await expect(blocking).resolves.toMatchObject({ items: [{ header: durable }] })
  389. await expect(queued).resolves.toMatchObject({ items: [{ header: durable }] })
  390. await persistence.dispose()
  391. })
  392. it('mounts persistence dynamically, shadows with TEMP live rows, reveals, and hides on unmount', async () => {
  393. const shared = header('shared', 10, { cwd: '/work' })
  394. const durable = header('durable', 5)
  395. TestPersistence.reset([
  396. { meta: shared, events: messageEvents('persisted needle') },
  397. { meta: durable, events: messageEvents('durable needle') },
  398. ])
  399. const ctx = await liveContext()
  400. await expect(ctx.sessionSearch.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  401. const persistenceFiber = await ctx.plugin(TestPersistence)
  402. await expect(ctx.sessionSearch.searchSessions({ query: 'durable' }))
  403. .resolves.toMatchObject({ items: [{ header: durable, live: false, persisted: true }] })
  404. const live = ctx.sessions.prepare(shared.id, { meta: { createdAt: 10, cwd: '/work' } })
  405. live.append('user/message', { content: [{ type: 'text', text: 'live needle' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  406. const detach = ctx.sessions.enter(live)
  407. ctx.sessions.announce(live)
  408. await expect(ctx.sessionSearch.searchSessions({ query: 'persisted' })).resolves.toEqual({ items: [] })
  409. await expect(ctx.sessionSearch.searchSessions({ query: 'live' }))
  410. .resolves.toMatchObject({ items: [{ header: shared, live: true, persisted: true }] })
  411. detach()
  412. await expect(ctx.sessionSearch.searchSessions({ query: 'persisted' }))
  413. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  414. await persistenceFiber.dispose()
  415. await expect(ctx.sessionSearch.searchSessions({ query: 'durable' })).resolves.toEqual({ items: [] })
  416. await expect(ctx.sessionSearch.searchEvents({ sessionId: durable.id, query: 'needle' }))
  417. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  418. })
  419. it('discards a stale list rejection when persistence unmounts during observation', async () => {
  420. const durable = header('racing')
  421. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  422. const ctx = await liveContext()
  423. const persistenceFiber = await ctx.plugin(TestPersistence)
  424. let release!: () => void
  425. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  426. let markStarted!: () => void
  427. const started = new Promise<void>((resolve) => { markStarted = resolve })
  428. TestPersistence.listStarted = () => {
  429. TestPersistence.listStarted = undefined
  430. markStarted()
  431. }
  432. const search = ctx.sessionSearch.searchSessions({ query: 'needle' })
  433. await started
  434. await persistenceFiber.dispose()
  435. TestPersistence.failure = new Error('stale backend rejection')
  436. release()
  437. await expect(search).resolves.toEqual({ items: [] })
  438. })
  439. it('retries against a replacement after the prior binding rejects', async () => {
  440. const durable = header('replacement')
  441. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  442. const ctx = await liveContext()
  443. const prior = await ctx.plugin(TestPersistence)
  444. let rejectPrior!: (reason: unknown) => void
  445. TestPersistence.listGate = new Promise<void>((_resolve, reject) => { rejectPrior = reject })
  446. let markStarted!: () => void
  447. const started = new Promise<void>((resolve) => { markStarted = resolve })
  448. TestPersistence.listStarted = () => {
  449. TestPersistence.listStarted = undefined
  450. markStarted()
  451. }
  452. const search = ctx.sessionSearch.searchSessions({ query: 'needle' })
  453. await started
  454. await prior.dispose()
  455. TestPersistence.listGate = undefined
  456. const replacement = await ctx.plugin(TestPersistence)
  457. rejectPrior(new Error('stale prior binding'))
  458. await expect(search).resolves.toMatchObject({ items: [{ header: durable }] })
  459. await replacement.dispose()
  460. })
  461. it('reloads a replacement source even when its opaque revisions collide', async () => {
  462. const durable = header('colliding-replacement')
  463. TestPersistence.reset([{ meta: durable, events: messageEvents('old content') }])
  464. const revision = TestPersistence.revisions.get(durable.id)!
  465. const ctx = await liveContext()
  466. const prior = await ctx.plugin(TestPersistence)
  467. await expect(ctx.sessionSearch.searchSessions({ query: 'old' }))
  468. .resolves.toMatchObject({ items: [{ header: durable }] })
  469. await prior.dispose()
  470. TestPersistence.set({ meta: durable, events: messageEvents('new needle') })
  471. TestPersistence.revisions.set(durable.id, revision)
  472. const replacement = await ctx.plugin(TestPersistence)
  473. const page = await ctx.sessionSearch.searchSessions({ query: 'new needle' })
  474. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  475. expect(page).toMatchObject({ items: [{ header: durable }] })
  476. await expect(ctx.sessionSearch.searchSessions({ query: 'old' })).resolves.toEqual({ items: [] })
  477. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  478. await replacement.dispose()
  479. })
  480. it('retries when a successful observation belongs to a source unmounted during listing', async () => {
  481. const durable = header('successful-unmount')
  482. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  483. const ctx = await liveContext()
  484. const persistence = await ctx.plugin(TestPersistence)
  485. let lists = 0
  486. TestPersistence.snapshotEffect = async () => {
  487. lists += 1
  488. if (lists === 2) await persistence.dispose()
  489. }
  490. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' })).resolves.toEqual({ items: [] })
  491. expect(lists).toBe(2)
  492. })
  493. it('retries when the snapshot population changes during observation', async () => {
  494. const first = header('first')
  495. const added = header('added-during-list')
  496. TestPersistence.reset([{ meta: first, events: messageEvents('first needle') }])
  497. const ctx = await liveContext()
  498. await ctx.plugin(TestPersistence)
  499. TestPersistence.snapshotEffect = () => {
  500. TestPersistence.snapshotEffect = undefined
  501. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  502. }
  503. const page = await ctx.sessionSearch.searchSessions({ query: 'needle' })
  504. expect(page.items.map(item => item.header.id).sort()).toEqual([added.id, first.id].sort())
  505. expect(TestPersistence.loads.get(first.id)).toBe(2)
  506. expect(TestPersistence.loads.get(added.id)).toBe(1)
  507. })
  508. it('retries if the persistence binding changes while live sessions are observed', async () => {
  509. const durable = header('live-boundary-retry')
  510. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  511. const ctx = await liveContext()
  512. await ctx.plugin(TestPersistence)
  513. const internals = ctx.sessionSearch as unknown as {
  514. _persistenceBinding: { identity: symbol; service?: SessionPersistence }
  515. }
  516. const originalList = ctx.sessions.list.bind(ctx.sessions)
  517. let bumped = false
  518. const list = vi.spyOn(ctx.sessions, 'list').mockImplementation(() => {
  519. if (!bumped) {
  520. bumped = true
  521. internals._persistenceBinding = {
  522. ...internals._persistenceBinding,
  523. identity: Symbol(),
  524. }
  525. }
  526. return originalList()
  527. })
  528. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  529. .resolves.toMatchObject({ items: [{ header: durable }] })
  530. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  531. list.mockRestore()
  532. })
  533. it('rejects malformed snapshots and preserves typed persistence failures', async () => {
  534. const durable = header('invalid-snapshot')
  535. TestPersistence.reset([{ meta: durable, events: messageEvents('durable needle') }])
  536. const ctx = await liveContext()
  537. await ctx.plugin(TestPersistence)
  538. TestPersistence.snapshotOverride = () => 'not-an-array' as never
  539. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  540. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  541. TestPersistence.snapshotOverride = () => [{ header: durable, revision: 1 as never }]
  542. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  543. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  544. TestPersistence.snapshotOverride = () => [
  545. { header: durable, revision: SessionPersistenceRevision('duplicate:1') },
  546. { header: durable, revision: SessionPersistenceRevision('duplicate:2') },
  547. ]
  548. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  549. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  550. TestPersistence.snapshotOverride = undefined
  551. const typed = new SessionQueryError('typed persistence failure', 'SESSION_QUERY_PERSISTENCE_FAILED')
  552. TestPersistence.failure = typed
  553. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' })).rejects.toBe(typed)
  554. })
  555. it('rejects immutable header conflicts between live and persisted sources', async () => {
  556. const shared = header('conflict', 10)
  557. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  558. const ctx = await liveContext()
  559. await ctx.plugin(TestPersistence)
  560. ctx.sessions.create(shared.id, { seed: messageEvents('live needle'), meta: { createdAt: 11 } })
  561. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  562. .rejects.toThrow(expectCode('SESSION_QUERY_SOURCE_CONFLICT'))
  563. })
  564. it('preserves unchanged persisted generations while reconciling new, changed, and deleted rows', async () => {
  565. const path = await temporaryPath()
  566. const unchanged = header('unchanged')
  567. const changed = header('changed')
  568. const deleted = header('deleted')
  569. TestPersistence.reset([
  570. { meta: unchanged, events: messageEvents('unchanged needle') },
  571. { meta: changed, events: messageEvents('old needle') },
  572. { meta: deleted, events: messageEvents('deleted needle') },
  573. ])
  574. const first = new Context()
  575. await first.plugin(SessionStore)
  576. const firstPersistence = await first.plugin(TestPersistence)
  577. const firstSearch = await first.plugin(SessionSearchSqlite, { path })
  578. await first.sessionSearch.searchSessions({ query: 'needle' })
  579. expect(Object.fromEntries(TestPersistence.loads)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  580. await first.sessionSearch.searchSessions({ query: 'needle' })
  581. expect(Object.fromEntries(TestPersistence.loads)).toEqual({ unchanged: 1, changed: 1, deleted: 1 })
  582. await firstSearch.dispose()
  583. await firstPersistence.dispose()
  584. const beforeDb = new DatabaseSync(path)
  585. const beforeRows = beforeDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  586. beforeDb.close()
  587. const before = new Map(beforeRows.map(row => [row.id, row.generation]))
  588. const added = header('added')
  589. TestPersistence.entries.delete(deleted.id)
  590. TestPersistence.set({ meta: changed, events: messageEvents('changed needle') })
  591. TestPersistence.set({ meta: added, events: messageEvents('added needle') })
  592. const second = new Context()
  593. await second.plugin(SessionStore)
  594. const secondPersistence = await second.plugin(TestPersistence)
  595. const secondSearch = await second.plugin(SessionSearchSqlite, { path })
  596. const result = await second.sessionSearch.searchSessions({ query: 'needle' })
  597. expect(result.items.map(item => item.header.id).sort()).toEqual([added.id, changed.id, unchanged.id].sort())
  598. expect(Object.fromEntries(TestPersistence.loads)).toEqual({
  599. unchanged: 1,
  600. changed: 2,
  601. deleted: 1,
  602. added: 1,
  603. })
  604. await secondSearch.dispose()
  605. await secondPersistence.dispose()
  606. const afterDb = new DatabaseSync(path)
  607. const afterRows = afterDb.prepare('SELECT id, generation FROM persisted_sessions ORDER BY id').all() as Array<{ id: string; generation: number }>
  608. afterDb.close()
  609. const after = new Map(afterRows.map(row => [row.id, row.generation]))
  610. expect(after.get(unchanged.id)).toBe(before.get(unchanged.id))
  611. expect(after.get(changed.id)).toBeGreaterThan(before.get(changed.id)!)
  612. expect(after.has(deleted.id)).toBe(false)
  613. expect(after.has(added.id)).toBe(true)
  614. })
  615. it('drops connection-local live overlays on reopen and retains persistent bases', async () => {
  616. const path = await temporaryPath()
  617. const shared = header('shared', 10)
  618. TestPersistence.reset([{ meta: shared, events: messageEvents('persisted needle') }])
  619. const first = new Context()
  620. await first.plugin(SessionStore)
  621. const persistence = await first.plugin(TestPersistence)
  622. const live = first.sessions.create(shared.id, { seed: messageEvents('live needle'), meta: { createdAt: 10 } })
  623. const search = await first.plugin(SessionSearchSqlite, { path })
  624. await expect(first.sessionSearch.searchEvents({ sessionId: live.id, query: 'live' })).resolves.toMatchObject({ items: [{}] })
  625. await search.dispose()
  626. await persistence.dispose()
  627. const second = new Context()
  628. await second.plugin(SessionStore)
  629. const persistenceAgain = await second.plugin(TestPersistence)
  630. const searchAgain = await second.plugin(SessionSearchSqlite, { path })
  631. await expect(second.sessionSearch.searchSessions({ query: 'live' })).resolves.toEqual({ items: [] })
  632. await expect(second.sessionSearch.searchSessions({ query: 'persisted' }))
  633. .resolves.toMatchObject({ items: [{ header: shared, live: false, persisted: true }] })
  634. expect(TestPersistence.loads.get(shared.id)).toBe(1)
  635. await searchAgain.dispose()
  636. await persistenceAgain.dispose()
  637. })
  638. it('refreshes the stored revision after a mutating load repair', async () => {
  639. const durable = header('repair')
  640. TestPersistence.reset([{ meta: durable, events: messageEvents('before repair') }])
  641. TestPersistence.loadEffect = (entry) => {
  642. entry.events = messageEvents('repaired needle')
  643. }
  644. const ctx = await liveContext()
  645. await ctx.plugin(TestPersistence)
  646. await expect(ctx.sessionSearch.searchSessions({ query: 'repaired' }))
  647. .resolves.toMatchObject({ items: [{ header: durable }] })
  648. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  649. await ctx.sessionSearch.searchSessions({ query: 'repaired' })
  650. expect(TestPersistence.loads.get(durable.id)).toBe(2)
  651. })
  652. it('recovers on the next search after source and SQLite transaction failures', async () => {
  653. TestPersistence.reset([{ meta: header('durable'), events: messageEvents('durable needle') }])
  654. const ctx = await liveContext()
  655. await ctx.plugin(TestPersistence)
  656. TestPersistence.failure = 'offline'
  657. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  658. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  659. const signal = new AbortController().signal
  660. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal }))
  661. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  662. TestPersistence.failure = new Error('still offline')
  663. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal }))
  664. .rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED'))
  665. TestPersistence.failure = undefined
  666. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' })).resolves.toMatchObject({ items: [{}] })
  667. const live = ctx.sessions.create(SessionId('live'), { seed: messageEvents('base') })
  668. await ctx.sessionSearch.searchEvents({ sessionId: live.id, query: 'base' })
  669. const db = (ctx.sessionSearch as unknown as { _db: DatabaseSync })._db
  670. db.exec('PRAGMA query_only = ON')
  671. live.append('user/message', { content: [{ type: 'text', text: 'retry needle' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  672. await expect(ctx.sessionSearch.searchEvents({ sessionId: live.id, query: 'needle' }))
  673. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  674. db.exec('PRAGMA query_only = OFF')
  675. await expect(ctx.sessionSearch.searchEvents({ sessionId: live.id, query: 'needle' }))
  676. .resolves.toMatchObject({ items: [{ seq: 1 }] })
  677. })
  678. })
  679. describe('SQLite schema, cancellation, and real persistence integration', () => {
  680. it('resets a recognized incompatible derived schema but refuses a foreign database', async () => {
  681. const stalePath = await temporaryPath('stale.db')
  682. const stale = new DatabaseSync(stalePath)
  683. stale.exec(`PRAGMA application_id = ${SESSION_QUERY_SQLITE_APPLICATION_ID}`)
  684. stale.exec('PRAGMA user_version = 999')
  685. stale.exec('CREATE TABLE stale(value TEXT)')
  686. stale.close()
  687. const staleCtx = await liveContext({ path: stalePath })
  688. staleCtx.sessions.create(SessionId('live'), { seed: messageEvents('needle') })
  689. await staleCtx.sessionSearch.searchSessions({ query: 'needle' })
  690. await (staleCtx.sessionSearch as SessionSearchSqlite).close()
  691. const rebuilt = new DatabaseSync(stalePath)
  692. expect((rebuilt.prepare('PRAGMA user_version').get() as { user_version: number }).user_version)
  693. .toBe(SESSION_QUERY_SQLITE_SCHEMA_VERSION)
  694. expect(rebuilt.prepare("SELECT name FROM sqlite_master WHERE name = 'stale'").get()).toBeUndefined()
  695. rebuilt.close()
  696. const foreignPath = await temporaryPath('foreign.db')
  697. const foreign = new DatabaseSync(foreignPath)
  698. foreign.exec('PRAGMA journal_mode = WAL')
  699. foreign.exec('CREATE TABLE canonical(value TEXT)')
  700. foreign.exec("INSERT INTO canonical VALUES ('safe')")
  701. foreign.close()
  702. const foreignCtx = await liveContext({ path: foreignPath, journalMode: 'delete' })
  703. await expect(foreignCtx.sessionSearch.searchSessions({ query: 'needle' }))
  704. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  705. const stillForeign = new DatabaseSync(foreignPath)
  706. expect(stillForeign.prepare('SELECT value FROM canonical').get()).toEqual({ value: 'safe' })
  707. expect(stillForeign.prepare('PRAGMA journal_mode').get()).toEqual({ journal_mode: 'wal' })
  708. stillForeign.close()
  709. await (foreignCtx.sessionSearch as SessionSearchSqlite).close()
  710. const otherAppPath = await temporaryPath('other-app.db')
  711. const otherApp = new DatabaseSync(otherAppPath)
  712. otherApp.exec('PRAGMA application_id = 123')
  713. otherApp.close()
  714. const otherAppCtx = await liveContext({ path: otherAppPath })
  715. await expect(otherAppCtx.sessionSearch.searchSessions({ query: 'needle' }))
  716. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  717. await (otherAppCtx.sessionSearch as SessionSearchSqlite).close()
  718. })
  719. it('observes asynchronous open rejection even when no query is made', async () => {
  720. const path = await temporaryPath('never-queried.db')
  721. const foreign = new DatabaseSync(path)
  722. foreign.exec('CREATE TABLE canonical(value TEXT)')
  723. foreign.close()
  724. const unhandled: unknown[] = []
  725. const onUnhandled = (reason: unknown) => { unhandled.push(reason) }
  726. process.on('unhandledRejection', onUnhandled)
  727. try {
  728. const ctx = await liveContext({ path })
  729. await new Promise<void>((resolve) => { setImmediate(resolve) })
  730. expect(unhandled).toEqual([])
  731. await (ctx.sessionSearch as SessionSearchSqlite).close()
  732. } finally {
  733. process.off('unhandledRejection', onUnhandled)
  734. }
  735. })
  736. it('cancels both queued and in-flight source waits without committing them', async () => {
  737. TestPersistence.reset()
  738. const ctx = await liveContext()
  739. await ctx.plugin(TestPersistence)
  740. const boundaryController = new AbortController()
  741. const boundary = ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal: boundaryController.signal })
  742. queueMicrotask(() => { boundaryController.abort() })
  743. await expect(boundary).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  744. const readyController = new AbortController()
  745. readyController.abort()
  746. const internals = ctx.sessionSearch as unknown as {
  747. _ensureReady(signal: AbortSignal): Promise<void>
  748. }
  749. await expect(internals._ensureReady(readyController.signal))
  750. .rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  751. let releaseBlocking!: () => void
  752. TestPersistence.listGate = new Promise<void>((resolve) => { releaseBlocking = resolve })
  753. let markBlockingStarted!: () => void
  754. const blockingStarted = new Promise<void>((resolve) => { markBlockingStarted = resolve })
  755. TestPersistence.listStarted = () => {
  756. TestPersistence.listStarted = undefined
  757. markBlockingStarted()
  758. }
  759. const blocking = ctx.sessionSearch.searchSessions({ query: 'needle' })
  760. await blockingStarted
  761. const queuedController = new AbortController()
  762. const queued = ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal: queuedController.signal })
  763. queuedController.abort()
  764. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  765. releaseBlocking()
  766. await expect(blocking).resolves.toEqual({ items: [] })
  767. TestPersistence.set({
  768. meta: header('uncommitted'),
  769. events: messageEvents('durable needle'),
  770. })
  771. let releaseActive!: () => void
  772. TestPersistence.listGate = new Promise<void>((resolve) => { releaseActive = resolve })
  773. let markActiveStarted!: () => void
  774. const activeStarted = new Promise<void>((resolve) => { markActiveStarted = resolve })
  775. TestPersistence.listStarted = () => {
  776. TestPersistence.listStarted = undefined
  777. markActiveStarted()
  778. }
  779. const activeController = new AbortController()
  780. const active = ctx.sessionSearch.searchSessions({ query: 'needle' }, { signal: activeController.signal })
  781. await activeStarted
  782. activeController.abort()
  783. await expect(active).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED'))
  784. releaseActive()
  785. const db = (ctx.sessionSearch as unknown as { _db: DatabaseSync })._db
  786. expect(db.prepare('SELECT COUNT(*) AS count FROM persisted_sessions').get()).toEqual({ count: 0 })
  787. await expect(ctx.sessionSearch.searchSessions({ query: 'needle' }))
  788. .resolves.toMatchObject({ items: [{ header: { id: SessionId('uncommitted') } }] })
  789. })
  790. it('rejects queued and future work when close waits for an accepted operation', async () => {
  791. TestPersistence.reset()
  792. let release!: () => void
  793. TestPersistence.listGate = new Promise<void>((resolve) => { release = resolve })
  794. let markStarted!: () => void
  795. const started = new Promise<void>((resolve) => { markStarted = resolve })
  796. TestPersistence.listStarted = () => {
  797. TestPersistence.listStarted = undefined
  798. markStarted()
  799. }
  800. const ctx = await liveContext()
  801. await ctx.plugin(TestPersistence)
  802. const search = ctx.sessionSearch as SessionSearchSqlite
  803. const accepted = search.searchSessions({ query: 'needle' })
  804. await started
  805. const queued = search.searchSessions({ query: 'needle' })
  806. const closing = search.close()
  807. const repeatedClose = search.close()
  808. expect(repeatedClose).toBe(closing)
  809. release()
  810. await expect(accepted).resolves.toEqual({ items: [] })
  811. await expect(queued).rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  812. await Promise.all([closing, repeatedClose])
  813. await expect(search.searchSessions({ query: 'needle' }))
  814. .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED'))
  815. expect(search.close()).toBe(closing)
  816. })
  817. it('awaits optional-persistence child-fiber quiescence on disposal', async () => {
  818. TestPersistence.reset()
  819. const ctx = new Context()
  820. await ctx.plugin(SessionStore)
  821. const search = await ctx.plugin(SessionSearchSqlite, { path: ':memory:' })
  822. const persistence = await ctx.plugin(TestPersistence)
  823. const optional = (ctx.sessionSearch as unknown as {
  824. _optionalPersistenceFiber: Fiber
  825. })._optionalPersistenceFiber
  826. let release!: () => void
  827. const cleanup = new Promise<void>((resolve) => { release = resolve })
  828. optional.ctx.effect(() => () => cleanup)
  829. let settled = false
  830. const disposing = search.dispose().then(() => { settled = true })
  831. await Promise.resolve()
  832. expect(settled).toBe(false)
  833. release()
  834. await disposing
  835. await persistence.dispose()
  836. })
  837. it('combines the real SQLite persistence backend with the real search service keylessly', async () => {
  838. const persistencePath = await temporaryPath('canonical.db')
  839. const searchPath = await temporaryPath('derived.db')
  840. const ctx = new Context()
  841. await ctx.plugin(SessionStore)
  842. const persistence = await ctx.plugin(SessionPersistenceSqlite, { path: persistencePath })
  843. const search = await ctx.plugin(SessionSearchSqlite, { path: searchPath })
  844. const meta = header('real', 10, { cwd: '/work' })
  845. await ctx.sessionPersistence.create(meta)
  846. await ctx.sessionPersistence.append(meta.id, messageEvents('real SQLite needle'))
  847. await expect(ctx.sessionSearch.searchSessions({ query: 'SQLite needle' }))
  848. .resolves.toMatchObject({ items: [{ header: meta, persisted: true, live: false }] })
  849. await expect(ctx.sessionSearch.searchEvents({ sessionId: meta.id, query: 'SQLite needle' }))
  850. .resolves.toMatchObject({ items: [{ sessionId: meta.id, seq: 0 }] })
  851. await expect(ctx.sessionSearch.searchEvents({ sessionId: SessionId('absent'), query: 'needle' }))
  852. .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND'))
  853. await search.dispose()
  854. await expect(ctx.sessionPersistence.load(meta.id)).resolves.toMatchObject({ meta, events: [{ seq: 0 }] })
  855. await persistence.dispose()
  856. })
  857. it('reconciles colliding local revisions when a derived index reopens against another SQLite store', async () => {
  858. const persistencePathA = await temporaryPath('canonical-a.db')
  859. const persistencePathB = await temporaryPath('canonical-b.db')
  860. const searchPath = await temporaryPath('derived-collision.db')
  861. const shared = header('same-id', 10)
  862. const first = new Context()
  863. await first.plugin(SessionStore)
  864. const persistenceA = await first.plugin(SessionPersistenceSqlite, { path: persistencePathA })
  865. await first.sessionPersistence.create(shared)
  866. await first.sessionPersistence.append(shared.id, messageEvents('alpha source'))
  867. const loadA = vi.spyOn(first.sessionPersistence, 'load')
  868. const searchA = await first.plugin(SessionSearchSqlite, { path: searchPath })
  869. await expect(first.sessionSearch.searchSessions({ query: 'alpha' }))
  870. .resolves.toMatchObject({ items: [{ header: shared }] })
  871. expect(loadA).toHaveBeenCalledTimes(1)
  872. await searchA.dispose()
  873. await persistenceA.dispose()
  874. const reopened = new Context()
  875. await reopened.plugin(SessionStore)
  876. const persistenceAAgain = await reopened.plugin(SessionPersistenceSqlite, { path: persistencePathA })
  877. const reopenedLoad = vi.spyOn(reopened.sessionPersistence, 'load')
  878. const searchAAgain = await reopened.plugin(SessionSearchSqlite, { path: searchPath })
  879. await expect(reopened.sessionSearch.searchSessions({ query: 'alpha' }))
  880. .resolves.toMatchObject({ items: [{ header: shared }] })
  881. expect(reopenedLoad).not.toHaveBeenCalled()
  882. await searchAAgain.dispose()
  883. await persistenceAAgain.dispose()
  884. const second = new Context()
  885. await second.plugin(SessionStore)
  886. const persistenceB = await second.plugin(SessionPersistenceSqlite, { path: persistencePathB })
  887. await second.sessionPersistence.create(shared)
  888. await second.sessionPersistence.append(shared.id, messageEvents('bravo source'))
  889. const loadB = vi.spyOn(second.sessionPersistence, 'load')
  890. const searchB = await second.plugin(SessionSearchSqlite, { path: searchPath })
  891. await expect(second.sessionSearch.searchSessions({ query: 'bravo' }))
  892. .resolves.toMatchObject({ items: [{ header: shared }] })
  893. await expect(second.sessionSearch.searchSessions({ query: 'alpha' })).resolves.toEqual({ items: [] })
  894. expect(loadB).toHaveBeenCalledTimes(1)
  895. await searchB.dispose()
  896. await persistenceB.dispose()
  897. })
  898. })