api-proxy-projections.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /**
  2. * Projection carrier paths of the host ApiProxy: the history tail page's
  3. * projections block reads the registry's watermark snapshot (asOfSeq = last
  4. * event seq, one consistent cut); loadOlder pages never carry the block; a
  5. * composition without the registry serves histories without it; a disposed
  6. * registration's key leaves subsequent responses; and every unit change is
  7. * pushed to mux consumers as a session/projection frame minted here.
  8. */
  9. import { describe, expect, it, vi } from 'vitest'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import { z } from 'zod'
  12. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  13. import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
  14. import type { Agent } from '@deepseek-ai/dsh-agent'
  15. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  16. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  17. import type { Session } from '@deepseek-ai/dsh-session'
  18. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  19. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  20. import UserQuestionService from '@deepseek-ai/dsh-user-questions'
  21. import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
  22. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  23. import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
  24. declare module '@deepseek-ai/dsh-session-projection/types' {
  25. interface SessionProjectionStateMap {
  26. 'test/last-user': LastUserState
  27. 'test/internal-count': number
  28. }
  29. interface SessionProjectionMap {
  30. 'test/last-user': { text: string } | null
  31. }
  32. }
  33. let nextRpc = 1
  34. function request<P>(payload: P): RpcRequest<P> {
  35. return { rpcId: RpcId(`proj-${String(nextRpc++)}`), payload }
  36. }
  37. /** Whole-value unit folding the latest user/message text; null before the first. */
  38. type LastUserState = { text: string } | null
  39. const lastUserUnit = () => ({
  40. key: 'test/last-user',
  41. stateSchema: z.union([z.object({ text: z.string() }), z.null()]),
  42. init: () => null,
  43. apply: (state, event) => (event.type === 'user/message'
  44. ? { text: (event.data.content[0] as { text?: string }).text ?? '' }
  45. : state),
  46. wire: {
  47. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  48. view: state => state,
  49. },
  50. stateVersion: 1,
  51. }) satisfies ProjectionDefinition<'test/last-user', LastUserState>
  52. const internalCountUnit = () => ({
  53. key: 'test/internal-count',
  54. stateSchema: z.number().int().nonnegative(),
  55. init: () => 0,
  56. apply: (state: number) => state + 1,
  57. stateVersion: 1,
  58. }) satisfies ProjectionDefinition<'test/internal-count', number>
  59. async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> {
  60. const ctx = new Context()
  61. await ctx.plugin(SessionStore)
  62. await ctx.plugin(UserQuestionService)
  63. await ctx.plugin(AgentRegistry)
  64. if (withRegistry) await ctx.plugin(SessionProjectionRegistry)
  65. const session = ctx.sessions.create()
  66. // The gateway reads both the session and durable inbox baseline.
  67. ctx.agents.register({ id: session.id, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), status: 'idle', ctx } as Agent)
  68. return { ctx, session }
  69. }
  70. /** Append `count` user messages so the log has paginable message boundaries. */
  71. function seedMessages(session: Session, count: number): void {
  72. for (let i = 0; i < count; i++) {
  73. session.append('user/message', createUserMessage({
  74. content: [{ type: 'text', text: `m${i}` }],
  75. source: { kind: 'user' },
  76. }), { surfaceOp: 'append' })
  77. }
  78. }
  79. const api = (ctx: Context) => createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  80. describe('session.history projections block', () => {
  81. it('serves the unit value on the tail page with asOfSeq = last event seq', async () => {
  82. const { ctx, session } = await harness(true)
  83. ctx.sessionProjections.register(lastUserUnit())
  84. seedMessages(session, 3)
  85. const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
  86. expect(response.result.ok).toBe(true)
  87. if (!response.result.ok) throw new Error('unreachable')
  88. const { events, projections } = response.result.value
  89. expect(projections).toBeDefined()
  90. expect(projections?.asOfSeq).toBe(session.seq - 1)
  91. expect(projections?.values['test/last-user']).toEqual({ text: 'm2' })
  92. // asOfSeq IS the window tail: the last served event carries it.
  93. expect(events.at(-1)?.event.seq).toBe(projections?.asOfSeq)
  94. })
  95. it('publishes the attachments imageLimits as a constant unit while both seams are composed', async () => {
  96. const { ctx, session } = await harness(true)
  97. const limits = {
  98. maxImageBytes: 5 * 1024 * 1024,
  99. maxImagesPerMessage: 20,
  100. maxMessageImageBytes: 100 * 1024 * 1024,
  101. maxImagePixels: 40_000_000,
  102. maxImageDimension: 2000,
  103. mediaTypes: ['image/png'] as const,
  104. }
  105. await ctx.plugin(class extends AttachmentStore {
  106. readonly imageLimits = limits
  107. validateImage(): Promise<void> { return Promise.resolve() }
  108. saveImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  109. readImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  110. })
  111. const gateway = api(ctx)
  112. seedMessages(session, 2)
  113. const response = await gateway.sessions.history(request({ sessionId: session.id }))
  114. if (!response.result.ok) throw new Error('history failed')
  115. expect(response.result.value.projections?.values['imageLimits']).toEqual(limits)
  116. // Constant unit: appending events must never broadcast an imageLimits frame.
  117. await new Promise(resolve => setTimeout(resolve, 0))
  118. const abort = new AbortController()
  119. const stream = gateway.events.mux({ rpcId: RpcId('t-limits-mux'), payload: {} }, abort.signal)
  120. const frames: MuxFrame[] = []
  121. const drained = (async () => {
  122. for await (const envelope of stream) {
  123. frames.push(envelope.payload)
  124. if (frames.some(f => f.type === 'session/event')) abort.abort()
  125. }
  126. })().catch(() => {})
  127. seedMessages(session, 1)
  128. await drained
  129. expect(frames.some(f => f.type === 'session/projection' && f.key === 'imageLimits')).toBe(false)
  130. })
  131. it('leaves the imageLimits key absent while no attachment service is composed', async () => {
  132. const { ctx, session } = await harness(true)
  133. seedMessages(session, 1)
  134. const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
  135. if (!response.result.ok) throw new Error('history failed')
  136. expect(response.result.value.projections).toBeDefined()
  137. expect('imageLimits' in (response.result.value.projections?.values ?? {})).toBe(false)
  138. })
  139. it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
  140. const { ctx, session } = await harness(true)
  141. ctx.sessionProjections.register(lastUserUnit())
  142. seedMessages(session, 5)
  143. const older = await api(ctx).sessions.history(request({ sessionId: session.id, beforeSeq: 3, maxMessages: 2 }))
  144. expect(older.result.ok).toBe(true)
  145. if (!older.result.ok) throw new Error('unreachable')
  146. expect('projections' in older.result.value).toBe(false)
  147. })
  148. it('serves no block when the composition has no projection registry', async () => {
  149. const { ctx, session } = await harness(false)
  150. seedMessages(session, 2)
  151. const response = await api(ctx).sessions.history(request({ sessionId: session.id }))
  152. expect(response.result.ok).toBe(true)
  153. if (!response.result.ok) throw new Error('unreachable')
  154. expect('projections' in response.result.value).toBe(false)
  155. })
  156. it('never exposes a host-only unit through history, listing, or push frames', async () => {
  157. const { ctx, session } = await harness(true)
  158. ctx.sessionProjections.register(internalCountUnit())
  159. const proxy = api(ctx)
  160. await new Promise(resolve => setTimeout(resolve, 0))
  161. const abort = new AbortController()
  162. const frames: MuxFrame[] = []
  163. const drained = (async () => {
  164. for await (const envelope of proxy.events.mux({ rpcId: RpcId('t-host-only-mux'), payload: {} }, abort.signal)) {
  165. frames.push(envelope.payload)
  166. if (envelope.payload.type === 'session/event') abort.abort()
  167. }
  168. })().catch(() => {})
  169. seedMessages(session, 1)
  170. await drained
  171. const history = await proxy.sessions.history(request({ sessionId: session.id }))
  172. if (!history.result.ok) throw new Error('history failed')
  173. expect('test/internal-count' in (history.result.value.projections?.values ?? {})).toBe(false)
  174. const listing = await proxy.sessions.list(request({}))
  175. if (!listing.result.ok) throw new Error('listing failed')
  176. const row = listing.result.value.items.find(item => item.sessionId === session.id)
  177. expect('test/internal-count' in (row?.projections?.values ?? {})).toBe(false)
  178. expect(frames.some(frame => frame.type === 'session/projection' && frame.key === 'test/internal-count')).toBe(false)
  179. })
  180. it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
  181. const { ctx, session } = await harness(true)
  182. const dispose = ctx.sessionProjections.register(lastUserUnit())
  183. seedMessages(session, 1)
  184. const proxy = api(ctx)
  185. const before = await proxy.sessions.history(request({ sessionId: session.id }))
  186. if (!before.result.ok) throw new Error('unreachable')
  187. expect(before.result.value.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  188. dispose()
  189. const after = await proxy.sessions.history(request({ sessionId: session.id }))
  190. if (!after.result.ok) throw new Error('unreachable')
  191. // The registry stays mounted; only the disposed key leaves while the
  192. // gateway-owned Session-list unit remains.
  193. expect(after.result.value.projections?.asOfSeq).toBe(session.seq - 1)
  194. expect('test/last-user' in (after.result.value.projections?.values ?? {})).toBe(false)
  195. expect(after.result.value.projections?.values.sessionListMetadata).toEqual({
  196. blank: true,
  197. lastPromptAt: session.events.at(-1)?.time,
  198. })
  199. })
  200. it('removes the gateway-owned Session-list unit when the gateway fiber unloads', async () => {
  201. const { ctx, session } = await harness(true)
  202. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  203. const fiber = ctx.plugin(Object.assign((gatewayCtx: Context) => {
  204. createApiProxy(gatewayCtx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  205. }, { inject: ['sessions', 'agents', 'userQuestions', 'sessionProjections'] }))
  206. await fiber.await()
  207. await vi.waitFor(() => {
  208. expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata)
  209. .toEqual({ blank: true, lastPromptAt: null })
  210. })
  211. await fiber.dispose()
  212. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  213. })
  214. })
  215. describe('session.list projections column', () => {
  216. it('serves attached rows from the live registry cut, watermarked for client seeding', async () => {
  217. const { ctx, session } = await harness(true)
  218. ctx.sessionProjections.register(lastUserUnit())
  219. const gateway = api(ctx)
  220. await new Promise(resolve => setTimeout(resolve, 0))
  221. session.append('turn/start', { turn: 1 })
  222. seedMessages(session, 1)
  223. const response = await gateway.sessions.list(request({}))
  224. if (!response.result.ok) throw new Error('unreachable')
  225. const row = response.result.value.items.find(item => item.sessionId === session.id)
  226. expect(row?.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  227. expect(row?.projections?.values.sessionListMetadata).toEqual({
  228. blank: false,
  229. lastPromptAt: session.events.at(-1)?.time,
  230. })
  231. expect(row?.projections?.asOfSeq).toBe(session.seq - 1)
  232. })
  233. it('omits the column entirely when no registry is mounted', async () => {
  234. const { ctx, session } = await harness(false)
  235. seedMessages(session, 1)
  236. const response = await api(ctx).sessions.list(request({}))
  237. if (!response.result.ok) throw new Error('unreachable')
  238. const row = response.result.value.items.find(item => item.sessionId === session.id)
  239. expect(row).toBeDefined()
  240. expect(row !== undefined && 'projections' in row).toBe(false)
  241. })
  242. it('serves cold rows from the persisted projection cache with zero log loads', async () => {
  243. const { ctx } = await harness(true)
  244. const coldId = SessionId('session-cold-listing')
  245. const load = () => { throw new Error('list must not load event logs') }
  246. ctx.provide('sessionPersistence', {
  247. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  248. locate: () => undefined,
  249. load,
  250. inspect: load,
  251. readFrom: load,
  252. } as never)
  253. ctx.provide('sessionProjectionCache', {
  254. // The carrier hands the listed header through as the identity witness.
  255. cachedSnapshot: async (meta: { id: unknown; createdAt: number }) =>
  256. (meta.id === coldId && meta.createdAt === 5
  257. ? { asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } }
  258. : undefined),
  259. } as never)
  260. const response = await api(ctx).sessions.list(request({}))
  261. if (!response.result.ok) throw new Error('unreachable')
  262. const row = response.result.value.items.find(item => item.sessionId === coldId)
  263. expect(row?.running).toBe(false)
  264. expect(row?.projections).toEqual({ asOfSeq: 7, values: { 'test/last-user': { text: 'cached' } } })
  265. })
  266. it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => {
  267. const { ctx } = await harness(true)
  268. const coldId = SessionId('session-cold-uncached')
  269. ctx.provide('sessionPersistence', {
  270. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  271. locate: () => undefined,
  272. } as never)
  273. const response = await api(ctx).sessions.list(request({}))
  274. if (!response.result.ok) throw new Error('unreachable')
  275. const row = response.result.value.items.find(item => item.sessionId === coldId)
  276. expect(row).toBeDefined()
  277. expect(row !== undefined && 'projections' in row).toBe(false)
  278. })
  279. it('a throwing column read degrades that row, never the listing', async () => {
  280. const { ctx, session } = await harness(true)
  281. ctx.sessionProjections.register({
  282. ...lastUserUnit(),
  283. wire: {
  284. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  285. view: () => { throw new Error('unit exploded') },
  286. },
  287. })
  288. seedMessages(session, 1)
  289. const response = await api(ctx).sessions.list(request({}))
  290. if (!response.result.ok) throw new Error('unreachable')
  291. const row = response.result.value.items.find(item => item.sessionId === session.id)
  292. expect(row).toBeDefined()
  293. expect(row !== undefined && 'projections' in row).toBe(false)
  294. })
  295. })
  296. describe('session/projection push frame', () => {
  297. /** Drain frames until `count` session/projection frames arrived. */
  298. async function collect(iterable: AsyncIterable<RpcRequest<MuxFrame>>, count: number, abort: AbortController): Promise<MuxFrame[]> {
  299. const frames: MuxFrame[] = []
  300. for await (const envelope of iterable) {
  301. frames.push(envelope.payload)
  302. if (frames.filter(f => f.type === 'session/projection').length >= count) abort.abort()
  303. }
  304. return frames
  305. }
  306. it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
  307. const { ctx, session } = await harness(true)
  308. ctx.sessionProjections.register(lastUserUnit())
  309. const proxy = api(ctx)
  310. // The gateway's onChanged subscription lives in an inject child whose
  311. // fiber activates asynchronously; yield until it lands before appending.
  312. await new Promise(resolve => setTimeout(resolve, 0))
  313. const abort = new AbortController()
  314. const stream = proxy.events.mux({ rpcId: RpcId('t-proj-mux'), payload: {} }, abort.signal)
  315. const collected = collect(stream, 5, abort)
  316. const now = vi.spyOn(Date, 'now').mockReturnValue(100)
  317. seedMessages(session, 1)
  318. now.mockReturnValue(200)
  319. session.append('turn/start', { turn: 1 })
  320. now.mockReturnValue(300)
  321. seedMessages(session, 1)
  322. now.mockRestore()
  323. const frames = await collected
  324. const pushes = frames.filter(
  325. (f): f is Extract<MuxFrame, { type: 'session/projection' }> =>
  326. f.type === 'session/projection' && f.key === 'test/last-user',
  327. )
  328. expect(pushes).toEqual([
  329. { type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
  330. { type: 'session/projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
  331. ])
  332. expect(frames.filter(
  333. (f): f is Extract<MuxFrame, { type: 'session/projection' }> =>
  334. f.type === 'session/projection' && f.key === 'sessionListMetadata',
  335. )).toEqual([
  336. { type: 'session/projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: true, lastPromptAt: 100 }, seq: 0 },
  337. { type: 'session/projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 100 }, seq: 1 },
  338. { type: 'session/projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 300 }, seq: 2 },
  339. ])
  340. // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
  341. const tail = await proxy.sessions.history(request({ sessionId: session.id }))
  342. if (!tail.result.ok) throw new Error('unreachable')
  343. expect(tail.result.value.projections?.asOfSeq).toBe(pushes.at(-1)?.seq)
  344. })
  345. it('emits no projection frames when the composition has no registry', async () => {
  346. const { ctx, session } = await harness(false)
  347. const proxy = api(ctx)
  348. const abort = new AbortController()
  349. const stream = proxy.events.mux({ rpcId: RpcId('t-noproj-mux'), payload: {} }, abort.signal)
  350. const frames: MuxFrame[] = []
  351. const drained = (async () => {
  352. for await (const envelope of stream) {
  353. frames.push(envelope.payload)
  354. if (frames.filter(f => f.type === 'session/event').length >= 2) abort.abort()
  355. }
  356. })()
  357. seedMessages(session, 2)
  358. await drained
  359. expect(frames.some(f => f.type === 'session/projection')).toBe(false)
  360. })
  361. })