Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

harness-observability.spec.ts

382 lines12.4 KB

1import { encodeWsFrame } from '@tanstack/ai'
2import { test, expect } from './fixtures'
3import type { APIRequestContext } from '@playwright/test'
4import type { AttributeValue } from '@opentelemetry/api'
5import type { OperationReport, SessionEvent } from '@tanstack/ai-harness'
6​
7type Scenario = 'wire' | 'gap' | 'tree' | 'lifecycle' | 'tracing'
8​
9/** One frame of an SSE stream, with the `id` of its SSE event. */
10interface Read {
11 id: string | null
12 frame: {
13 type: string
14 v?: number
15 cursor?: string
16 threadId?: string
17 operationId?: string
18 event?: {
19 type: string
20 name?: string
21 value?: unknown
22 parentRunId?: string
23 }
24 }
26​
27interface RecordedSpan {
28 name: string
29 attributes: Record<string, AttributeValue>
30 links: Array<{ context: unknown }> | null
31 hasParent: boolean
32 ended: boolean
34​
35interface Traces {
36 spans: Array<RecordedSpan>
37 reports: Array<OperationReport>
39​
40const TRACE_ID = '4bf92f3577b34da6a3ce929d0e0e4736'
41const CALLER = `00-${TRACE_ID}-00f067aa0ba902b7-01`
42/** The span context that `CALLER` names. */
43const CALLER_CONTEXT = {
44 traceId: TRACE_ID,
45 spanId: '00f067aa0ba902b7',
46 traceFlags: 1,
47 isRemote: true,
49​
50const ROUTE = '/api/harness-observability'
51​
52/** Start a run of `scenario`. */
53async function start(request: APIRequestContext, scenario: Scenario) {
54 const res = await request.post(`${ROUTE}/start`, { data: { scenario } })
55 expect(res.ok()).toBe(true)
56 const started: { error?: string; runId: string; threadId: string } =
57 await res.json()
58 expect(started.error ?? null).toBeNull()
59 return started
61​
62async function report<T>(request: APIRequestContext, runId: string) {
63 const res = await request.get(`${ROUTE}/report?runId=${runId}`)
64 const body: T & { error?: string } = await res.json()
65 expect(body.error ?? null).toBeNull()
66 return body
68​
69const stop = (request: APIRequestContext, runId: string) =>
70 request.post(`${ROUTE}/stop?runId=${runId}`)
71​
72/**
73 * Read `GET events` of the run until `isDone` is true for the frames so
74 * far. `: ping` comments have no `data:` line, so they are skipped.
75 */
76async function readEvents(
77 url: string,
78 isDone: (frames: Array<Read>) => boolean,
79 headers: Record<string, string> = {},
80) {
81 const response = await fetch(url, { headers })
82 if (!response.body) throw new Error('The session stream has no body.')
83 const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
84 const frames: Array<Read> = []
85 let buffer = ''
86 while (!isDone(frames)) {
87 const read = await reader.read()
88 if (read.done) break
89 buffer += read.value
90 const blocks = buffer.split('\n\n')
91 buffer = blocks.pop() ?? ''
92 for (const block of blocks) {
93 const lines = block.split('\n')
94 const data = lines.find((line) => line.startsWith('data: '))
95 if (!data) continue
96 const id = lines.find((line) => line.startsWith('id: '))
97 frames.push({
98 id: id ? id.slice('id: '.length) : null,
99 frame: JSON.parse(data.slice('data: '.length)),
100 })
101 }
102 }
103 await reader.cancel()
104 return { response, frames }
106​
107const isFinished = ({ frame }: Read) =>
108 frame.event?.type === 'CUSTOM' &&
109 frame.event.name === 'harness.operation.finished'
110​
111/** The values of the `name` events in `frames`, in order. */
112const valuesOf = (frames: Array<Read>, name: string) =>
113 frames.flatMap(({ frame }) =>
114 frame.event?.type === 'CUSTOM' && frame.event.name === name
115 ? [frame.event.value]
116 : [],
117 )
118​
119test.describe('harness observability', () => {
120 test('every frame of GET events is a wire chunk and starts with hello', async ({
121 request,
122 baseURL,
123 }) => {
124 const { runId, threadId } = await start(request, 'wire')
125 try {
126 const { response, frames } = await readEvents(
127 `${baseURL}${ROUTE}/events?runId=${runId}&threadId=${threadId}&v=2&from=0`,
128 (seen) => seen.some(isFinished),
129 { 'X-Request-Id': 'obs-wire-1' },
130 )
131 expect(response.headers.get('X-Request-Id')).toBe('obs-wire-1')
132 expect(frames[0]).toEqual({
133 id: null,
134 frame: { type: 'harness.hello', v: 2, threadId },
135 })
136​
137 const events = frames.slice(1)
138 const { logged } = await report<{ logged: Array<SessionEvent> }>(
139 request,
140 runId,
141 )
142 expect(events.map(({ frame }) => frame.type)).toEqual(
143 logged.map(() => 'harness.event'),
144 )
145 // The SSE id and the frame cursor are the cursor of the logged event.
146 expect(events.map(({ id, frame }) => [id, frame.cursor])).toEqual(
147 logged.map((entry) => [entry.cursor, entry.cursor]),
148 )
149 events.forEach(({ frame }, index) => {
150 const entry = logged[index]!
151 expect(frame.threadId).toBe(threadId)
152 expect(frame.operationId).toBe(entry.operationId)
153 expect(frame.event).toEqual(
154 JSON.parse(encodeWsFrame(entry.event, undefined)),
155 )
156 })
157 // At least one logged chunk has keys that the wire drops, so an
158 // internal chunk on the wire fails the check above.
159 const isLossy = logged.some(
160 (entry) =>
161 encodeWsFrame(entry.event, undefined) !== JSON.stringify(entry.event),
162 )
163 expect(isLossy).toBe(true)
164 } finally {
165 await stop(request, runId)
166 }
167 })
168​
169 test('a cursor from before a truncation gets harness.gap', async ({
170 request,
171 baseURL,
172 }) => {
173 const { runId, threadId } = await start(request, 'gap')
174 try {
175 const { head } = await report<{ head: string }>(request, runId)
176 const gap = {
177 id: head,
178 frame: {
179 type: 'harness.event',
180 cursor: head,
181 threadId,
182 operationId: 'session',
183 event: {
184 type: 'CUSTOM',
185 name: 'harness.gap',
186 value: { from: '0', resumeAt: head, reason: 'truncated' },
187 timestamp: expect.any(Number),
188 },
189 },
190 }
191 const url = `${baseURL}${ROUTE}/events?runId=${runId}&threadId=${threadId}`
192 const fromQuery = await readEvents(
193 `${url}&from=0`,
194 (seen) => seen.length >= 2,
195 )
196 expect(fromQuery.frames).toEqual([
197 { id: null, frame: { type: 'harness.hello', v: 2, threadId } },
198 gap,
199 ])
200​
201 // A client that resumes with `Last-Event-ID` gets the same gap.
202 const resumed = await readEvents(url, (seen) => seen.length >= 2, {
203 'Last-Event-ID': '0',
204 })
205 expect(resumed.frames[1]).toEqual(gap)
206 } finally {
207 await stop(request, runId)
208 }
209 })
210​
211 test('a parallel group of agents gives the whole tree in one stream', async ({
212 request,
213 baseURL,
214 }) => {
215 const { runId, threadId } = await start(request, 'tree')
216 try {
217 const run = await report<{
218 result: string
219 leadRunId: string
220 agentRuns: Array<{ runId: string; parentRunId: string | null }>
221 }>(request, runId)
222 expect(run.result).toBe('helped helped')
223 // The lead, its helper and nester, and the helper of the nester.
224 const expected = Object.fromEntries(
225 run.agentRuns.map((item) => [item.runId, item.parentRunId]),
226 )
227 expect(Object.keys(expected)).toHaveLength(4)
228 expect(expected[run.leadRunId]).toBeNull()
229 const children = run.agentRuns.filter(
230 (item) => item.parentRunId === run.leadRunId,
231 )
232 expect(children).toHaveLength(2)
233 const grandchildren = run.agentRuns.filter((item) =>
234 children.some((child) => child.runId === item.parentRunId),
235 )
236 expect(grandchildren).toHaveLength(1)
237​
238 const { frames } = await readEvents(
239 `${baseURL}${ROUTE}/events?runId=${runId}&threadId=${threadId}&from=0`,
240 (seen) =>
241 seen.some(
242 (read) =>
243 read.frame.operationId === run.leadRunId && isFinished(read),
244 ),
245 )
246​
247 // The tree from the frames alone: the `parentRunId` of the AG-UI
248 // RUN_STARTED of each operation.
249 const tree = new Map<string, string | null>()
250 for (const { frame } of frames.slice(1)) {
251 expect(frame.threadId).toBe(threadId)
252 if (frame.event?.type !== 'RUN_STARTED') continue
253 tree.set(frame.operationId ?? '', frame.event.parentRunId ?? null)
254 }
255 // The session has operations of its own, for example its inputs.
256 const agentTree = Object.fromEntries(
257 [...tree].filter(([operationId]) => operationId in expected),
258 )
259 expect(agentTree).toEqual(expected)
260 } finally {
261 await stop(request, runId)
262 }
263 })
264​
265 test('a new thread gets harness.ownership.changed, and a send during a turn gets harness.input.queued', async ({
266 request,
267 baseURL,
268 }) => {
269 const { runId, threadId } = await start(request, 'lifecycle')
270 try {
271 // The first turn runs and waits for the model.
272 const receipt = await request.post(`${ROUTE}/control?runId=${runId}`, {
273 data: {
274 threadId,
275 input: {
276 op: 'prompt',
277 message: '[harness-observability] two',
278 inputId: 'in-2',
279 },
280 },
281 })
282 expect(await receipt.json()).toMatchObject({
283 status: 'queued',
284 inputId: 'in-2',
285 })
286 await request.post(`${ROUTE}/release?runId=${runId}`)
287​
288 const { frames } = await readEvents(
289 `${baseURL}${ROUTE}/events?runId=${runId}&threadId=${threadId}&from=0`,
290 (seen) => seen.filter(isFinished).length >= 2,
291 )
292 expect(valuesOf(frames, 'harness.ownership.changed')).toEqual([
293 { epoch: 1, reason: 'acquired' },
294 ])
295 expect(valuesOf(frames, 'harness.input.queued')).toEqual([
296 { inputId: 'in-2', delivery: 'queue' },
297 ])
298 // The host owns the log before the first turn starts.
299 const names = frames.map(({ frame }) => frame.event?.name)
300 expect(names.indexOf('harness.ownership.changed')).toBeLessThan(
301 names.indexOf('harness.operation.started'),
302 )
303 } finally {
304 await stop(request, runId)
305 }
306 })
307​
308 test('a traceparent on POST control links the span of the run on the host that runs it', async ({
309 request,
310 }) => {
311 const { runId, threadId } = await start(request, 'tracing')
312 try {
313 // The other host stores the input in the log. The owner runs it after
314 // its turn.
315 const receipt = await request.post(`${ROUTE}/control?runId=${runId}`, {
316 headers: { traceparent: CALLER },
317 data: {
318 threadId,
319 input: { op: 'followUp', message: '[harness-observability] then' },
320 },
321 })
322 expect(await receipt.json()).toMatchObject({ status: 'queued' })
323 await request.post(`${ROUTE}/release?runId=${runId}`)
324​
325 type Traced = {
326 owner: Traces
327 other: Traces
328 ownerCalls: number
329 otherCalls: number
330 }
331 let traced: Traced | undefined
332 const operations = (traces: Traces) =>
333 traces.spans.filter((span) => span.name === 'harness.operation')
334 await expect
335 .poll(
336 async () => {
337 traced = await report<Traced>(request, runId)
338 const ended = operations(traced.owner).filter((span) => span.ended)
339 return [ended.length, traced.owner.reports.length]
340 },
341 { timeout: 20_000 },
342 )
343 .toEqual([2, 4])
344 const { owner, other, ownerCalls, otherCalls } = traced!
345​
346 const spans = operations(owner)
347 for (const span of spans) {
348 expect(span.attributes).toMatchObject({
349 'harness.thread_id': threadId,
350 'harness.operation.kind': 'chat',
351 'harness.operation.status': 'completed',
352 })
353 // A link, not a parent: the caller is on another machine.
354 expect(span.hasParent).toBe(false)
355 }
356 const linked = spans.filter((span) => span.links !== null)
357 expect(linked).toHaveLength(1)
358 expect(linked[0]?.links).toEqual([{ context: CALLER_CONTEXT }])
359​
360 // `onOperation` reports each run once when it starts and once when it
361 // settles.
362 for (const span of spans) {
363 const runOf = owner.reports.filter(
364 (item) => item.operation.id === span.attributes['harness.run_id'],
365 )
366 expect(runOf.map((item) => item.phase)).toEqual(['started', 'settled'])
367 expect(runOf[1]?.operation).toMatchObject({
368 threadId,
369 kind: 'chat',
370 status: 'completed',
371 })
372 }
373 // The host that only stored the input runs nothing, so it reports
374 // nothing.
375 expect(other).toEqual({ spans: [], reports: [] })
376 expect(ownerCalls).toBe(2)
377 expect(otherCalls).toBe(0)
378 } finally {
379 await stop(request, runId)
380 }
381 })
382})