telemetry.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /**
  2. * Coordinator semantics against a bare fake backend — the RFC's named unit
  3. * tier for the seam: adoption (fresh, seeded, re-adoption via the handoff
  4. * cursor), the fixed chunk projection, deep-copy isolation, turn-latency and
  5. * dispose-ordering pins, failure containment, and the `agent/error` relay.
  6. */
  7. import { describe, expect, it, vi } from 'vitest'
  8. import { Context } from 'cordis'
  9. import SessionStore, { SessionId, type Session, type SessionEvent } from '@deepseek-ai/dsh-session'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import { TelemetryCoordinator, type TelemetryBackend, type TelemetryRecord } from '../src/index.ts'
  12. declare module '@deepseek-ai/dsh-session' {
  13. interface SessionEventMap {
  14. /**
  15. * Test-only merged event proving unknown types flow through unchanged.
  16. * @mode emit
  17. * @param payload - opaque test payload
  18. */
  19. 'telemetry-test/opaque': { payload: { nested: string[] } }
  20. }
  21. }
  22. class FakeBackend implements TelemetryBackend {
  23. records: TelemetryRecord[] = []
  24. calls: string[] = []
  25. emitError: Error | undefined
  26. rejectSeq: number | undefined
  27. shutdownError: Error | undefined
  28. shutdownResolved = false
  29. emit(record: TelemetryRecord): void {
  30. if (this.emitError) throw this.emitError
  31. if (this.rejectSeq !== undefined && record.attributes['event.seq'] === this.rejectSeq) {
  32. throw new Error(`backend rejected seq ${this.rejectSeq}`)
  33. }
  34. this.records.push(record)
  35. this.calls.push(`emit:${String(record.attributes['event.seq'] ?? record.attributes['telemetry.op'])}`)
  36. }
  37. flush = vi.fn()
  38. async shutdown(): Promise<void> {
  39. this.calls.push('shutdown')
  40. await new Promise(resolve => setTimeout(resolve, 5))
  41. if (this.shutdownError) throw this.shutdownError
  42. this.shutdownResolved = true
  43. }
  44. ledger(): TelemetryRecord[] {
  45. return this.records.filter(r => r.channel === 'ledger')
  46. }
  47. }
  48. async function setup(backend: FakeBackend = new FakeBackend()) {
  49. const ctx = new Context()
  50. await ctx.plugin(SessionStore)
  51. const fiber = await ctx.plugin({
  52. name: 'fake-telemetry',
  53. inject: ['sessions'],
  54. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  55. })
  56. return { ctx, backend, fiber }
  57. }
  58. function liveSession(ctx: Context, id = `s-${Math.random().toString(36).slice(2)}`): Session {
  59. return ctx.sessions.create(SessionId(id), { meta: {} })
  60. }
  61. function appendTurn(session: Session): void {
  62. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  63. session.append('user/message', { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  64. }
  65. describe('TelemetryCoordinator capture', () => {
  66. it('hands every appended event over with envelope identity and cloned body', async () => {
  67. const { ctx, backend } = await setup()
  68. const session = liveSession(ctx, 'cap')
  69. appendTurn(session)
  70. const start = backend.ledger()[0]!
  71. const message = backend.ledger()[1]!
  72. expect(start.attributes).toMatchObject({ 'session.id': 'cap', 'event.type': 'turn/start', 'event.seq': 0 })
  73. expect(start.time).toBe(session.events[0]!.time)
  74. expect(start.severity).toBe('info')
  75. expect(message.attributes['event.seq']).toBe(1)
  76. // Deep-copy isolation: mutating the handed-off body never reaches the log.
  77. ;(message.body as { content: { text: string }[] }).content[0]!.text = 'tampered'
  78. const logged = session.events[1] as SessionEvent<'user/message'>
  79. expect(logged.data.content[0]).toMatchObject({ text: 'hello' })
  80. })
  81. it('stamps header facts on every record when present', async () => {
  82. const { ctx, backend } = await setup()
  83. const parent = SessionId('parent')
  84. const session = ctx.sessions.create(SessionId('child'), { meta: { cwd: '/tmp/proj', parentSession: parent } })
  85. appendTurn(session)
  86. for (const record of backend.ledger()) {
  87. expect(record.attributes['session.cwd']).toBe('/tmp/proj')
  88. expect(record.attributes['session.parent_id']).toBe('parent')
  89. }
  90. })
  91. it('maps outcome flags to severity, unknown types falling through as info', async () => {
  92. const { ctx, backend } = await setup()
  93. const session = liveSession(ctx)
  94. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  95. session.append('tool/result', { turn: 1, step: 1, callId: 'c1' as never, content: [], isError: true }, { surfaceOp: 'append' })
  96. session.append('tool/result', { turn: 1, step: 1, callId: 'c2' as never, content: [], isError: false }, { surfaceOp: 'append' })
  97. session.append('telemetry-test/opaque', { payload: { nested: [] } })
  98. session.append('turn/end', { turn: 1, reason: { kind: 'error', step: 1, message: 'boom' } })
  99. const severities = backend.ledger().map(r => [r.attributes['event.type'], r.severity])
  100. expect(severities).toEqual([
  101. ['turn/start', 'info'],
  102. ['tool/result', 'error'],
  103. ['tool/result', 'info'],
  104. ['telemetry-test/opaque', 'info'],
  105. ['turn/end', 'error'],
  106. ])
  107. })
  108. it('passes unknown merged event types through unchanged', async () => {
  109. const { ctx, backend } = await setup()
  110. const session = liveSession(ctx)
  111. session.append('telemetry-test/opaque', { payload: { nested: ['a', 'b'] } })
  112. const record = backend.ledger()[0]!
  113. expect(record.attributes['event.type']).toBe('telemetry-test/opaque')
  114. expect(record.severity).toBe('info')
  115. expect(record.body).toEqual({ payload: { nested: ['a', 'b'] } })
  116. })
  117. it('ships only the first chunk of each (turn, step), per session', async () => {
  118. const { ctx, backend } = await setup()
  119. const a = liveSession(ctx, 'a')
  120. const b = liveSession(ctx, 'b')
  121. const chunk = (s: Session, turn: number, step: number, text: string) =>
  122. s.append('assistant/chunk', { turn, step, chunk: { type: 'text-delta', index: 0, text } })
  123. chunk(a, 1, 1, 'a11-first')
  124. chunk(a, 1, 1, 'a11-second')
  125. chunk(a, 1, 2, 'a12-first')
  126. chunk(b, 1, 1, 'b11-first')
  127. chunk(b, 1, 1, 'b11-second')
  128. const shipped = backend.ledger().map(r => [r.attributes['session.id'], (r.body as { chunk: { text: string } }).chunk.text])
  129. expect(shipped).toEqual([
  130. ['a', 'a11-first'],
  131. ['a', 'a12-first'],
  132. ['b', 'b11-first'],
  133. ])
  134. })
  135. })
  136. describe('TelemetryCoordinator adoption', () => {
  137. it('starts export at the construction boundary: seeded history never re-exports', async () => {
  138. const backend = new FakeBackend()
  139. const ctx = new Context()
  140. await ctx.plugin(SessionStore)
  141. const parent = liveSession(ctx, 'seed-parent')
  142. appendTurn(parent)
  143. const child = ctx.sessions.create(SessionId('seeded'), { seed: [...parent.events], meta: {} })
  144. await ctx.plugin({
  145. name: 'fake-telemetry',
  146. inject: ['sessions'],
  147. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  148. })
  149. // The live parent (no constructor seed) replays in full; the child's
  150. // inherited prefix already left the process under another identity (the
  151. // parent's id here; the same id in a previous process for a resume) and
  152. // must not be re-exported — only its live suffix ships.
  153. const seqs = backend.ledger().map(r => [r.attributes['session.id'], r.attributes['event.seq']])
  154. expect(seqs).toEqual(expect.arrayContaining([['seed-parent', 0], ['seed-parent', 1]]))
  155. expect(seqs.filter(([id]) => id === 'seeded')).toEqual([])
  156. child.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  157. expect(backend.ledger().map(r => [r.attributes['session.id'], r.attributes['event.seq']]))
  158. .toEqual(expect.arrayContaining([['seeded', 2]]))
  159. })
  160. it('resume shape: a full-log seed exports nothing yet still rebuilds the chunk projection', async () => {
  161. const backend = new FakeBackend()
  162. const ctx = new Context()
  163. await ctx.plugin(SessionStore)
  164. const donor = ctx.sessions.create(SessionId('donor'), { meta: {} })
  165. donor.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  166. donor.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'first' } })
  167. const resumed = ctx.sessions.create(SessionId('resumed'), { seed: [...donor.events], meta: {} })
  168. await ctx.plugin({
  169. name: 'fake-telemetry',
  170. inject: ['sessions'],
  171. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  172. })
  173. const ofResumed = () => backend.ledger()
  174. .filter(r => r.attributes['session.id'] === 'resumed')
  175. .map(r => r.attributes['event.seq'])
  176. expect(ofResumed()).toEqual([])
  177. // The seed fed the projection: the (turn 1, step 1) first chunk already
  178. // shipped from the original process, so its continuation is re-dropped…
  179. resumed.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'continuation' } })
  180. expect(ofResumed()).toEqual([])
  181. // …while a new step's first chunk exports normally.
  182. resumed.append('assistant/chunk', { turn: 1, step: 2, chunk: { type: 'text-delta', index: 0, text: 'next step' } })
  183. expect(ofResumed()).toEqual([3])
  184. })
  185. it('stamps session.seed_length from the header so receivers can stitch fork streams', async () => {
  186. const backend = new FakeBackend()
  187. const ctx = new Context()
  188. await ctx.plugin(SessionStore)
  189. const parent = liveSession(ctx, 'stitch-parent')
  190. appendTurn(parent)
  191. const child = ctx.sessions.create(SessionId('stitch-child'), {
  192. seed: [...parent.events],
  193. meta: { parentSession: SessionId('stitch-parent'), seedLength: 2 },
  194. })
  195. await ctx.plugin({
  196. name: 'fake-telemetry',
  197. inject: ['sessions'],
  198. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  199. })
  200. child.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  201. const record = backend.ledger().find(r => r.attributes['session.id'] === 'stitch-child')!
  202. expect(record.attributes['session.parent_id']).toBe('stitch-parent')
  203. expect(record.attributes['session.seed_length']).toBe(2)
  204. })
  205. it('adopts exactly once when created fires after the sweep', async () => {
  206. const backend = new FakeBackend()
  207. const ctx = new Context()
  208. await ctx.plugin(SessionStore)
  209. // The enter/announce window: prepare+enter puts the session in the store
  210. // (visible to the constructor sweep) before `session/created` fires, so a
  211. // coordinator loaded inside that window sees the session twice — sweep
  212. // first, created second. The second adoption must be a no-op.
  213. const session = ctx.sessions.prepare(SessionId('overlap'))
  214. appendTurn(session)
  215. ctx.sessions.enter(session)
  216. await ctx.plugin({
  217. name: 'fake-telemetry',
  218. inject: ['sessions'],
  219. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  220. })
  221. expect(backend.ledger()).toHaveLength(2)
  222. ctx.sessions.announce(session)
  223. expect(backend.ledger()).toHaveLength(2)
  224. })
  225. it('resumes from the handoff cursor across a reload, re-dropping mid-step chunks', async () => {
  226. const backend = new FakeBackend()
  227. const { ctx, fiber } = await setup(backend)
  228. const session = liveSession(ctx, 'hmr')
  229. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  230. session.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'first' } })
  231. expect(backend.ledger()).toHaveLength(2)
  232. await fiber.dispose()
  233. // The reload window: appends while no telemetry listener is registered.
  234. session.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'mid-step continuation' } })
  235. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  236. const second = new FakeBackend()
  237. await ctx.plugin({
  238. name: 'fake-telemetry-2',
  239. inject: ['sessions'],
  240. apply: (inner: Context) => void new TelemetryCoordinator(inner, second),
  241. })
  242. // Only the window events past the cursor are re-handed, and the mid-step
  243. // continuation is re-dropped because ≤cursor events rebuilt the projection.
  244. expect(second.ledger().map(r => r.attributes['event.type'])).toEqual(['turn/end'])
  245. })
  246. it('replays past a record the backend rejects: one event withheld, the rest adopted', async () => {
  247. const backend = new FakeBackend()
  248. const ctx = new Context()
  249. await ctx.plugin(SessionStore)
  250. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  251. const session = liveSession(ctx, 'partial')
  252. appendTurn(session)
  253. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  254. // The backend rejects exactly the middle historical event: fail-closed
  255. // must withhold THAT record only — an adoption replay that dies on the
  256. // first contained failure would silently skip the rest of the log while
  257. // the session stays marked adopted.
  258. backend.rejectSeq = 1
  259. await ctx.plugin({
  260. name: 'fake-telemetry',
  261. inject: ['sessions'],
  262. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  263. })
  264. expect(backend.ledger().map(r => r.attributes['event.seq'])).toEqual([0, 2])
  265. expect(warn).toHaveBeenCalled()
  266. })
  267. it('re-hands the full log when no cursor survived (fresh session object)', async () => {
  268. const backend = new FakeBackend()
  269. const ctx = new Context()
  270. await ctx.plugin(SessionStore)
  271. const session = liveSession(ctx, 'fresh')
  272. appendTurn(session)
  273. await ctx.plugin({
  274. name: 'fake-telemetry',
  275. inject: ['sessions'],
  276. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  277. })
  278. expect(backend.ledger().map(r => r.attributes['event.seq'])).toEqual([0, 1])
  279. })
  280. })
  281. describe('TelemetryCoordinator lifecycle and containment', () => {
  282. it('forwards session/flush as a hint without awaiting backend work', async () => {
  283. const { ctx, backend } = await setup()
  284. const session = liveSession(ctx)
  285. let settled = false
  286. backend.flush.mockImplementation(() => {
  287. // The backend may kick off arbitrary async work; the loop's parallel must not wait for it.
  288. void new Promise(resolve => setTimeout(resolve, 50)).then(() => { settled = true })
  289. })
  290. await ctx.parallel('session/flush', session)
  291. expect(backend.flush).toHaveBeenCalledTimes(1)
  292. expect(settled).toBe(false)
  293. })
  294. it('ignores flush hints for sessions it never adopted', async () => {
  295. const { ctx, backend } = await setup()
  296. const stranger = ctx.sessions.prepare(SessionId('stranger'), { meta: {} })
  297. await ctx.parallel('session/flush', stranger)
  298. expect(backend.flush).not.toHaveBeenCalled()
  299. })
  300. it('emits no marker for a session whose announcement was vetoed before adoption', async () => {
  301. const backend = new FakeBackend()
  302. const ctx = new Context()
  303. await ctx.plugin(SessionStore)
  304. // A listener registered BEFORE the coordinator vetoes publication: the
  305. // store still emits the paired `session/disposed` for rollback, but the
  306. // coordinator never saw `session/created` — a marker for a session the
  307. // receiver saw no activity from would be noise, not signal.
  308. ctx.on('session/created', () => {
  309. throw new Error('vetoed by an earlier listener')
  310. })
  311. await ctx.plugin({
  312. name: 'fake-telemetry',
  313. inject: ['sessions'],
  314. apply: (inner: Context) => void new TelemetryCoordinator(inner, backend),
  315. })
  316. expect(() => ctx.sessions.create(SessionId('vetoed'), { meta: {} })).toThrow('vetoed')
  317. expect(backend.records.filter(r => r.channel === 'ops')).toHaveLength(0)
  318. })
  319. it('emits each adopted session’s shutdown record before awaiting backend shutdown', async () => {
  320. const { ctx, backend, fiber } = await setup()
  321. liveSession(ctx, 's1')
  322. liveSession(ctx, 's2')
  323. await fiber.dispose()
  324. expect(backend.calls).toEqual(['emit:shutdown', 'emit:shutdown', 'shutdown'])
  325. expect(backend.shutdownResolved).toBe(true)
  326. const ops = backend.records.filter(r => r.channel === 'ops')
  327. expect(ops.map(r => r.attributes['session.id']).sort()).toEqual(['s1', 's2'])
  328. expect(ops.every(r => r.attributes['telemetry.op'] === 'shutdown' && r.severity === 'info')).toBe(true)
  329. expect(ops.every(r => !('event.seq' in r.attributes) && !('event.type' in r.attributes))).toBe(true)
  330. })
  331. it('emits the shutdown marker at the session’s own disposal edge, then retires it', async () => {
  332. const { ctx, backend, fiber } = await setup()
  333. liveSession(ctx, 'survivor')
  334. // A session owned by its own fiber: disposing the fiber detaches it from
  335. // the store and emits `session/disposed` — the authoritative termination
  336. // edge. The marker must ride THAT edge (receivers classify a session with
  337. // activity and no marker as crashed, so a normally closed session in a
  338. // long-running host must not look like a crash), and the session retires
  339. // from the adopted set so unload neither retains it nor re-marks it.
  340. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  341. inner.sessions.create(SessionId('ephemeral'), { meta: {} })
  342. }, { inject: ['sessions'] }))
  343. await owner.dispose()
  344. const atEdge = backend.records.filter(r => r.channel === 'ops')
  345. expect(atEdge.map(r => r.attributes['session.id'])).toEqual(['ephemeral'])
  346. expect(atEdge[0]!.attributes['telemetry.op']).toBe('shutdown')
  347. await fiber.dispose()
  348. const ops = backend.records.filter(r => r.channel === 'ops')
  349. expect(ops.map(r => r.attributes['session.id'])).toEqual(['ephemeral', 'survivor'])
  350. })
  351. it('warns instead of throwing when backend shutdown fails', async () => {
  352. const backend = new FakeBackend()
  353. backend.shutdownError = new Error('exporter unreachable')
  354. const { ctx, fiber } = await setup(backend)
  355. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  356. liveSession(ctx)
  357. await expect(fiber.dispose()).resolves.not.toThrow()
  358. expect(warn.mock.calls.some(args => String(args[0]).includes('shutdown failed'))).toBe(true)
  359. })
  360. it('contains emit failures: the append succeeds and capture heals', async () => {
  361. const { ctx, backend } = await setup()
  362. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  363. const session = liveSession(ctx)
  364. backend.emitError = new Error('backend broke')
  365. expect(() => session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })).not.toThrow()
  366. expect(warn).toHaveBeenCalled()
  367. backend.emitError = undefined
  368. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  369. expect(backend.ledger().map(r => r.attributes['event.type'])).toEqual(['turn/end'])
  370. })
  371. it.each([
  372. ['Error values', new TypeError('adapter exploded'), 'TypeError', 'adapter exploded'],
  373. ['non-Error values', 'plain failure', 'Error', 'plain failure'],
  374. ])('relays agent/error %s as an ops record with normalized identity', async (_label, error, name, message) => {
  375. const { ctx, backend } = await setup()
  376. const session = liveSession(ctx, 'erring')
  377. // Only the members the relay reads; the full Agent surface is irrelevant here.
  378. const agent = { id: 'agent-1', session } as Agent
  379. ctx.emit('agent/error', agent, 3, 2, error)
  380. const record = backend.records.find(r => r.channel === 'ops')!
  381. expect(record.severity).toBe('error')
  382. expect(record.attributes).toMatchObject({
  383. 'telemetry.op': 'agent-error',
  384. 'session.id': 'erring',
  385. 'agent.id': 'agent-1',
  386. 'error.name': name,
  387. turn: 3,
  388. step: 2,
  389. })
  390. expect(record.body).toEqual({ name, message })
  391. })
  392. })