[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D9Q5D641TB7XT7TWHMBG0R":3,"skill-same:01M7D9Q5D641TB7XT7TWHMBG0R":85},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":63,"commitSha":64,"skillDirectory":65,"forksCount":14,"repositoryHtmlUrl":66,"repositoryHomepageUrl":6,"ownerHtmlUrl":67,"ownerBlogUrl":68,"ownerDescription":69,"updatedAt":70,"install":71,"resources":84},"01M7D9Q5D641TB7XT7TWHMBG0R","Streaming API Testing",null,"Streaming API testing skill covering Server-Sent Events testing, chunked transfer encoding, gRPC streaming, real-time data validation, backpressure testing, connection resilience, and AI\u002FLLM streaming response testing.","GrupoANDevelopment-m\u002Falberto-ai","GrupoANDevelopment-m","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F257455179?v=4","01M7D69X2N2KEVN0SJF6WGM6SH","Antônio  Ndombe","01M7D69X3P5JTT8H8S904N3888",0,"MIT","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fstreaming-api-testing\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: Streaming API Testing\ndescription: Streaming API testing skill covering Server-Sent Events testing, chunked transfer encoding, gRPC streaming, real-time data validation, backpressure testing, connection resilience, and AI\u002FLLM streaming response testing.\nversion: 1.0.0\nauthor: thetestingacademy\nlicense: MIT\ntags: [streaming, sse, server-sent-events, grpc-streaming, real-time, chunked-transfer, ai-streaming, backpressure]\ntestingTypes: [api, integration, performance]\nframeworks: [playwright, jest, vitest]\nlanguages: [typescript, javascript, python]\ndomains: [api, backend, ai]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# Streaming API Testing Skill\n\nYou are an expert software engineer specializing in testing streaming APIs, real-time data protocols, and event-driven architectures. When the user asks you to write, review, or debug tests for streaming endpoints including SSE, gRPC streaming, chunked responses, and AI\u002FLLM streaming, follow these detailed instructions.\n\n## Core Principles\n\n1. **Test the stream lifecycle** -- Verify connection establishment, data flow, and graceful termination.\n2. **Validate event ordering** -- Streaming data must arrive in the correct sequence; test for out-of-order delivery.\n3. **Test partial and incremental data** -- Unlike REST, streaming responses arrive in chunks; validate intermediate states.\n4. **Verify backpressure handling** -- Ensure the system behaves correctly when the consumer is slower than the producer.\n5. **Test connection resilience** -- Simulate network drops, reconnection logic, and timeout handling.\n6. **Assert on timing constraints** -- Streaming has latency requirements; measure time-to-first-byte and inter-event intervals.\n7. **Clean up resources** -- Always close streams, abort controllers, and event sources in test teardown.\n\n## Project Structure\n\n```\nproject\u002F\n  src\u002F\n    api\u002F\n      sse-endpoint.ts\n      grpc-service.ts\n      chunked-endpoint.ts\n      llm-stream.ts\n    tests\u002F\n      sse\u002F\n        sse-basic.test.ts\n        sse-reconnection.test.ts\n        sse-backpressure.test.ts\n      grpc\u002F\n        server-streaming.test.ts\n        client-streaming.test.ts\n        bidirectional.test.ts\n      chunked\u002F\n        chunked-transfer.test.ts\n        chunked-json.test.ts\n      llm\u002F\n        llm-stream.test.ts\n        token-validation.test.ts\n      helpers\u002F\n        stream-collector.ts\n        mock-sse-server.ts\n        mock-grpc-server.ts\n        timing-utils.ts\n  vitest.config.ts\n```\n\n## SSE Endpoint Testing\n\n### Basic SSE Connection and Event Validation\n\n```typescript\n\u002F\u002F tests\u002Fsse\u002Fsse-basic.test.ts\nimport { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { createServer, Server } from 'http';\nimport EventSource from 'eventsource';\n\nlet server: Server;\nlet baseUrl: string;\n\nbeforeAll(async () => {\n  server = createServer((req, res) => {\n    if (req.url === '\u002Fevents') {\n      res.writeHead(200, {\n        'Content-Type': 'text\u002Fevent-stream',\n        'Cache-Control': 'no-cache',\n        Connection: 'keep-alive',\n      });\n\n      let count = 0;\n      const interval = setInterval(() => {\n        count++;\n        res.write(`id: ${count}\\n`);\n        res.write(`event: message\\n`);\n        res.write(`data: ${JSON.stringify({ count, timestamp: Date.now() })}\\n\\n`);\n\n        if (count >= 5) {\n          clearInterval(interval);\n          res.end();\n        }\n      }, 100);\n\n      req.on('close', () => clearInterval(interval));\n    }\n  });\n\n  await new Promise\u003Cvoid>((resolve) => {\n    server.listen(0, () => {\n      const addr = server.address();\n      if (typeof addr === 'object' && addr) {\n        baseUrl = `http:\u002F\u002Flocalhost:${addr.port}`;\n      }\n      resolve();\n    });\n  });\n});\n\nafterAll(() => {\n  server.close();\n});\n\ndescribe('SSE Basic', () => {\n  it('should receive all events in order', async () => {\n    const events: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve, reject) => {\n      const es = new EventSource(`${baseUrl}\u002Fevents`);\n      const timeout = setTimeout(() => {\n        es.close();\n        reject(new Error('Timeout waiting for events'));\n      }, 5000);\n\n      es.onmessage = (event) => {\n        events.push(JSON.parse(event.data));\n      };\n\n      es.onerror = () => {\n        clearTimeout(timeout);\n        es.close();\n        resolve(); \u002F\u002F SSE error fires on stream end\n      };\n    });\n\n    expect(events).toHaveLength(5);\n    expect(events.map((e) => e.count)).toEqual([1, 2, 3, 4, 5]);\n  });\n\n  it('should set correct SSE headers', async () => {\n    const response = await fetch(`${baseUrl}\u002Fevents`);\n\n    expect(response.headers.get('content-type')).toBe('text\u002Fevent-stream');\n    expect(response.headers.get('cache-control')).toBe('no-cache');\n    expect(response.headers.get('connection')).toBe('keep-alive');\n\n    \u002F\u002F Clean up the stream\n    await response.body?.cancel();\n  });\n\n  it('should include event IDs for resumption', async () => {\n    const eventIds: string[] = [];\n\n    await new Promise\u003Cvoid>((resolve) => {\n      const es = new EventSource(`${baseUrl}\u002Fevents`);\n\n      es.onmessage = (event) => {\n        eventIds.push(event.lastEventId);\n        if (eventIds.length >= 5) {\n          es.close();\n          resolve();\n        }\n      };\n\n      es.onerror = () => {\n        es.close();\n        resolve();\n      };\n    });\n\n    expect(eventIds).toEqual(['1', '2', '3', '4', '5']);\n  });\n});\n```\n\n### SSE Reconnection Testing\n\n```typescript\n\u002F\u002F tests\u002Fsse\u002Fsse-reconnection.test.ts\nimport { describe, it, expect } from 'vitest';\nimport { createServer, Server, IncomingMessage, ServerResponse } from 'http';\n\ndescribe('SSE Reconnection', () => {\n  it('should reconnect and resume from last event ID', async () => {\n    let connectionCount = 0;\n\n    const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n      connectionCount++;\n      const lastEventId = req.headers['last-event-id'];\n\n      res.writeHead(200, {\n        'Content-Type': 'text\u002Fevent-stream',\n        'Cache-Control': 'no-cache',\n        Connection: 'keep-alive',\n      });\n\n      const startFrom = lastEventId ? parseInt(lastEventId as string) + 1 : 1;\n\n      if (connectionCount === 1) {\n        \u002F\u002F First connection: send events 1-3, then drop\n        for (let i = startFrom; i \u003C= 3; i++) {\n          res.write(`id: ${i}\\ndata: ${JSON.stringify({ n: i })}\\n\\n`);\n        }\n        res.destroy(); \u002F\u002F Simulate connection drop\n      } else {\n        \u002F\u002F Reconnection: send events 4-6\n        for (let i = startFrom; i \u003C= 6; i++) {\n          res.write(`id: ${i}\\ndata: ${JSON.stringify({ n: i })}\\n\\n`);\n        }\n        res.end();\n      }\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const allEvents: number[] = [];\n\n    await new Promise\u003Cvoid>((resolve) => {\n      const es = new EventSource(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n      const timeout = setTimeout(() => {\n        es.close();\n        resolve();\n      }, 5000);\n\n      es.onmessage = (event) => {\n        const data = JSON.parse(event.data);\n        allEvents.push(data.n);\n\n        if (data.n >= 6) {\n          clearTimeout(timeout);\n          es.close();\n          resolve();\n        }\n      };\n    });\n\n    server.close();\n\n    \u002F\u002F Verify all events received across reconnection\n    expect(allEvents).toEqual([1, 2, 3, 4, 5, 6]);\n    expect(connectionCount).toBe(2);\n  });\n\n  it('should handle server-sent retry interval', async () => {\n    const server = createServer((req, res) => {\n      res.writeHead(200, {\n        'Content-Type': 'text\u002Fevent-stream',\n        'Cache-Control': 'no-cache',\n      });\n\n      \u002F\u002F Set custom retry interval (500ms)\n      res.write('retry: 500\\n\\n');\n      res.write('data: hello\\n\\n');\n      res.end();\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const reconnectTimes: number[] = [];\n    let lastDisconnect = 0;\n\n    await new Promise\u003Cvoid>((resolve) => {\n      let messageCount = 0;\n      const es = new EventSource(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n\n      es.onmessage = () => {\n        messageCount++;\n      };\n\n      es.onerror = () => {\n        if (lastDisconnect > 0) {\n          reconnectTimes.push(Date.now() - lastDisconnect);\n        }\n        lastDisconnect = Date.now();\n\n        if (messageCount >= 2) {\n          es.close();\n          resolve();\n        }\n      };\n\n      setTimeout(() => {\n        es.close();\n        resolve();\n      }, 3000);\n    });\n\n    server.close();\n\n    \u002F\u002F Reconnect time should be approximately 500ms (within tolerance)\n    if (reconnectTimes.length > 0) {\n      expect(reconnectTimes[0]).toBeGreaterThan(400);\n      expect(reconnectTimes[0]).toBeLessThan(1000);\n    }\n  });\n});\n```\n\n## Chunked Transfer Encoding Testing\n\n```typescript\n\u002F\u002F tests\u002Fchunked\u002Fchunked-transfer.test.ts\nimport { describe, it, expect } from 'vitest';\nimport { createServer, Server } from 'http';\n\ndescribe('Chunked Transfer Encoding', () => {\n  let server: Server;\n  let baseUrl: string;\n\n  beforeAll(async () => {\n    server = createServer((req, res) => {\n      if (req.url === '\u002Fchunked-json') {\n        res.writeHead(200, {\n          'Content-Type': 'application\u002Fjson',\n          'Transfer-Encoding': 'chunked',\n        });\n\n        const items = [\n          { id: 1, name: 'first' },\n          { id: 2, name: 'second' },\n          { id: 3, name: 'third' },\n        ];\n\n        let index = 0;\n        const sendNext = () => {\n          if (index \u003C items.length) {\n            const prefix = index === 0 ? '[' : ',';\n            const suffix = index === items.length - 1 ? ']' : '';\n            res.write(`${prefix}${JSON.stringify(items[index])}${suffix}`);\n            index++;\n            setTimeout(sendNext, 50);\n          } else {\n            res.end();\n          }\n        };\n\n        sendNext();\n      }\n\n      if (req.url === '\u002Fndjson') {\n        res.writeHead(200, {\n          'Content-Type': 'application\u002Fx-ndjson',\n        });\n\n        const lines = [\n          { event: 'start', ts: 1 },\n          { event: 'data', value: 42, ts: 2 },\n          { event: 'data', value: 84, ts: 3 },\n          { event: 'end', ts: 4 },\n        ];\n\n        let index = 0;\n        const sendNext = () => {\n          if (index \u003C lines.length) {\n            res.write(JSON.stringify(lines[index]) + '\\n');\n            index++;\n            setTimeout(sendNext, 50);\n          } else {\n            res.end();\n          }\n        };\n\n        sendNext();\n      }\n    });\n\n    await new Promise\u003Cvoid>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        baseUrl = `http:\u002F\u002Flocalhost:${typeof addr === 'object' ? addr!.port : 0}`;\n        resolve();\n      });\n    });\n  });\n\n  afterAll(() => server.close());\n\n  it('should collect chunked JSON array', async () => {\n    const response = await fetch(`${baseUrl}\u002Fchunked-json`);\n    const data = await response.json();\n\n    expect(data).toEqual([\n      { id: 1, name: 'first' },\n      { id: 2, name: 'second' },\n      { id: 3, name: 'third' },\n    ]);\n  });\n\n  it('should process NDJSON stream line by line', async () => {\n    const response = await fetch(`${baseUrl}\u002Fndjson`);\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const events: any[] = [];\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.trim()) {\n          events.push(JSON.parse(line));\n        }\n      }\n    }\n\n    expect(events).toHaveLength(4);\n    expect(events[0].event).toBe('start');\n    expect(events[3].event).toBe('end');\n  });\n\n  it('should measure time-to-first-byte for chunked response', async () => {\n    const startTime = performance.now();\n    const response = await fetch(`${baseUrl}\u002Fndjson`);\n    const reader = response.body!.getReader();\n\n    const { value } = await reader.read();\n    const ttfb = performance.now() - startTime;\n\n    expect(value).toBeTruthy();\n    expect(ttfb).toBeLessThan(1000); \u002F\u002F First byte within 1 second\n\n    \u002F\u002F Clean up\n    await reader.cancel();\n  });\n});\n```\n\n## gRPC Streaming Tests\n\n```typescript\n\u002F\u002F tests\u002Fgrpc\u002Fserver-streaming.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\nimport * as grpc from '@grpc\u002Fgrpc-js';\nimport * as protoLoader from '@grpc\u002Fproto-loader';\n\n\u002F\u002F Proto definition for reference:\n\u002F\u002F service StockService {\n\u002F\u002F   rpc StreamPrices (PriceRequest) returns (stream PriceUpdate);\n\u002F\u002F   rpc SendOrders (stream Order) returns (OrderSummary);\n\u002F\u002F   rpc TradeChat (stream ChatMessage) returns (stream ChatMessage);\n\u002F\u002F }\n\ndescribe('gRPC Server Streaming', () => {\n  let client: any;\n  let server: grpc.Server;\n\n  beforeAll(async () => {\n    const packageDef = protoLoader.loadSync('protos\u002Fstock.proto');\n    const proto = grpc.loadPackageDefinition(packageDef) as any;\n\n    \u002F\u002F Set up mock gRPC server\n    server = new grpc.Server();\n    server.addService(proto.stock.StockService.service, {\n      streamPrices: (call: any) => {\n        const symbols = call.request.symbols;\n        let tick = 0;\n\n        const interval = setInterval(() => {\n          tick++;\n          for (const symbol of symbols) {\n            call.write({\n              symbol,\n              price: 100 + Math.random() * 10,\n              tick,\n              timestamp: Date.now(),\n            });\n          }\n\n          if (tick >= 5) {\n            clearInterval(interval);\n            call.end();\n          }\n        }, 100);\n\n        call.on('cancelled', () => clearInterval(interval));\n      },\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve, reject) => {\n      server.bindAsync(\n        '0.0.0.0:0',\n        grpc.ServerCredentials.createInsecure(),\n        (err, port) => {\n          if (err) reject(err);\n          else resolve(port);\n        }\n      );\n    });\n\n    server.start();\n\n    client = new proto.stock.StockService(\n      `localhost:${port}`,\n      grpc.credentials.createInsecure()\n    );\n  });\n\n  afterAll(() => {\n    server.forceShutdown();\n  });\n\n  it('should receive all price updates from server stream', async () => {\n    const updates: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve, reject) => {\n      const call = client.streamPrices({ symbols: ['AAPL', 'GOOG'] });\n\n      call.on('data', (update: any) => {\n        updates.push(update);\n      });\n\n      call.on('end', () => resolve());\n      call.on('error', (err: Error) => reject(err));\n    });\n\n    \u002F\u002F 5 ticks * 2 symbols = 10 updates\n    expect(updates).toHaveLength(10);\n\n    \u002F\u002F Verify ordering: ticks should be sequential\n    const applUpdates = updates.filter((u) => u.symbol === 'AAPL');\n    const ticks = applUpdates.map((u) => u.tick);\n    expect(ticks).toEqual([1, 2, 3, 4, 5]);\n\n    \u002F\u002F Verify price is within expected range\n    for (const update of updates) {\n      expect(update.price).toBeGreaterThan(90);\n      expect(update.price).toBeLessThan(120);\n    }\n  });\n\n  it('should handle client cancellation of server stream', async () => {\n    const updates: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve) => {\n      const call = client.streamPrices({ symbols: ['AAPL'] });\n\n      call.on('data', (update: any) => {\n        updates.push(update);\n        if (updates.length >= 2) {\n          call.cancel(); \u002F\u002F Cancel after 2 updates\n        }\n      });\n\n      call.on('error', (err: any) => {\n        if (err.code === grpc.status.CANCELLED) {\n          resolve(); \u002F\u002F Expected cancellation\n        }\n      });\n    });\n\n    expect(updates.length).toBeGreaterThanOrEqual(2);\n    expect(updates.length).toBeLessThan(10);\n  });\n});\n\n\u002F\u002F tests\u002Fgrpc\u002Fbidirectional.test.ts\ndescribe('gRPC Bidirectional Streaming', () => {\n  it('should support bidirectional message exchange', async () => {\n    const received: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve, reject) => {\n      const call = client.tradeChat();\n\n      call.on('data', (msg: any) => {\n        received.push(msg);\n      });\n\n      call.on('end', () => resolve());\n      call.on('error', (err: Error) => reject(err));\n\n      \u002F\u002F Send messages from client\n      call.write({ user: 'trader1', message: 'Buy AAPL' });\n      call.write({ user: 'trader1', message: 'Sell GOOG' });\n      call.end();\n    });\n\n    expect(received.length).toBeGreaterThan(0);\n    for (const msg of received) {\n      expect(msg).toHaveProperty('user');\n      expect(msg).toHaveProperty('message');\n    }\n  });\n});\n```\n\n## AI\u002FLLM Streaming Response Testing\n\n```typescript\n\u002F\u002F tests\u002Fllm\u002Fllm-stream.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\nimport { createServer, Server } from 'http';\n\ndescribe('LLM Streaming Response', () => {\n  let server: Server;\n  let baseUrl: string;\n\n  beforeAll(async () => {\n    server = createServer((req, res) => {\n      if (req.url === '\u002Fv1\u002Fchat\u002Fcompletions' && req.method === 'POST') {\n        res.writeHead(200, {\n          'Content-Type': 'text\u002Fevent-stream',\n          'Cache-Control': 'no-cache',\n        });\n\n        const tokens = ['Hello', ',', ' how', ' can', ' I', ' help', ' you', '?'];\n        let index = 0;\n\n        const sendToken = () => {\n          if (index \u003C tokens.length) {\n            const chunk = {\n              id: 'chatcmpl-abc123',\n              object: 'chat.completion.chunk',\n              created: Math.floor(Date.now() \u002F 1000),\n              model: 'gpt-4',\n              choices: [\n                {\n                  index: 0,\n                  delta: { content: tokens[index] },\n                  finish_reason: null,\n                },\n              ],\n            };\n            res.write(`data: ${JSON.stringify(chunk)}\\n\\n`);\n            index++;\n            setTimeout(sendToken, 30);\n          } else {\n            \u002F\u002F Send final chunk with finish_reason\n            const finalChunk = {\n              id: 'chatcmpl-abc123',\n              object: 'chat.completion.chunk',\n              created: Math.floor(Date.now() \u002F 1000),\n              model: 'gpt-4',\n              choices: [\n                {\n                  index: 0,\n                  delta: {},\n                  finish_reason: 'stop',\n                },\n              ],\n            };\n            res.write(`data: ${JSON.stringify(finalChunk)}\\n\\n`);\n            res.write('data: [DONE]\\n\\n');\n            res.end();\n          }\n        };\n\n        sendToken();\n      }\n    });\n\n    await new Promise\u003Cvoid>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        baseUrl = `http:\u002F\u002Flocalhost:${typeof addr === 'object' ? addr!.port : 0}`;\n        resolve();\n      });\n    });\n  });\n\n  afterAll(() => server.close());\n\n  it('should collect all tokens from streaming response', async () => {\n    const response = await fetch(`${baseUrl}\u002Fv1\u002Fchat\u002Fcompletions`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        model: 'gpt-4',\n        messages: [{ role: 'user', content: 'Hello' }],\n        stream: true,\n      }),\n    });\n\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const tokens: string[] = [];\n    let finishReason: string | null = null;\n    let receivedDone = false;\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.startsWith('data: ')) {\n          const data = line.slice(6).trim();\n\n          if (data === '[DONE]') {\n            receivedDone = true;\n            continue;\n          }\n\n          const parsed = JSON.parse(data);\n          const delta = parsed.choices[0].delta;\n\n          if (delta.content) {\n            tokens.push(delta.content);\n          }\n\n          if (parsed.choices[0].finish_reason) {\n            finishReason = parsed.choices[0].finish_reason;\n          }\n        }\n      }\n    }\n\n    const fullText = tokens.join('');\n    expect(fullText).toBe('Hello, how can I help you?');\n    expect(finishReason).toBe('stop');\n    expect(receivedDone).toBe(true);\n    expect(tokens).toHaveLength(8);\n  });\n\n  it('should measure token latency', async () => {\n    const response = await fetch(`${baseUrl}\u002Fv1\u002Fchat\u002Fcompletions`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        model: 'gpt-4',\n        messages: [{ role: 'user', content: 'Hello' }],\n        stream: true,\n      }),\n    });\n\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const tokenTimestamps: number[] = [];\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.startsWith('data: ') && line.slice(6).trim() !== '[DONE]') {\n          const parsed = JSON.parse(line.slice(6));\n          if (parsed.choices[0].delta.content) {\n            tokenTimestamps.push(performance.now());\n          }\n        }\n      }\n    }\n\n    \u002F\u002F Calculate inter-token latencies\n    const latencies: number[] = [];\n    for (let i = 1; i \u003C tokenTimestamps.length; i++) {\n      latencies.push(tokenTimestamps[i] - tokenTimestamps[i - 1]);\n    }\n\n    const avgLatency = latencies.reduce((a, b) => a + b, 0) \u002F latencies.length;\n    const maxLatency = Math.max(...latencies);\n\n    \u002F\u002F Assert reasonable latency bounds\n    expect(avgLatency).toBeLessThan(200); \u002F\u002F Average under 200ms\n    expect(maxLatency).toBeLessThan(500); \u002F\u002F No single gap over 500ms\n  });\n\n  it('should handle abort during streaming', async () => {\n    const controller = new AbortController();\n    const tokensReceived: string[] = [];\n\n    const response = await fetch(`${baseUrl}\u002Fv1\u002Fchat\u002Fcompletions`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        model: 'gpt-4',\n        messages: [{ role: 'user', content: 'Hello' }],\n        stream: true,\n      }),\n      signal: controller.signal,\n    });\n\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n\n    try {\n      let buffer = '';\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        buffer += decoder.decode(value, { stream: true });\n        const lines = buffer.split('\\n');\n        buffer = lines.pop() || '';\n\n        for (const line of lines) {\n          if (line.startsWith('data: ') && line.slice(6).trim() !== '[DONE]') {\n            const parsed = JSON.parse(line.slice(6));\n            if (parsed.choices[0].delta.content) {\n              tokensReceived.push(parsed.choices[0].delta.content);\n              if (tokensReceived.length >= 3) {\n                controller.abort();\n              }\n            }\n          }\n        }\n      }\n    } catch (err: any) {\n      expect(err.name).toBe('AbortError');\n    }\n\n    expect(tokensReceived.length).toBeGreaterThanOrEqual(3);\n    expect(tokensReceived.length).toBeLessThan(8);\n  });\n});\n```\n\n## Backpressure and Flow Control Testing\n\n```typescript\n\u002F\u002F tests\u002Fsse\u002Fsse-backpressure.test.ts\nimport { describe, it, expect } from 'vitest';\nimport { createServer, Server } from 'http';\nimport { Readable, Transform } from 'stream';\n\ndescribe('Backpressure Testing', () => {\n  it('should handle slow consumer without losing data', async () => {\n    const totalEvents = 100;\n    const consumerDelayMs = 10;\n\n    const server = createServer((req, res) => {\n      res.writeHead(200, { 'Content-Type': 'text\u002Fevent-stream' });\n\n      for (let i = 0; i \u003C totalEvents; i++) {\n        const canWrite = res.write(`data: ${JSON.stringify({ seq: i })}\\n\\n`);\n        if (!canWrite) {\n          \u002F\u002F Wait for drain event when buffer is full\n          res.once('drain', () => {});\n        }\n      }\n      res.end();\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const response = await fetch(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const received: number[] = [];\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      \u002F\u002F Simulate slow consumer\n      await new Promise((r) => setTimeout(r, consumerDelayMs));\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.startsWith('data: ')) {\n          const data = JSON.parse(line.slice(6));\n          received.push(data.seq);\n        }\n      }\n    }\n\n    server.close();\n\n    \u002F\u002F All events should be received despite slow consumer\n    expect(received).toHaveLength(totalEvents);\n    expect(received).toEqual(Array.from({ length: totalEvents }, (_, i) => i));\n  });\n\n  it('should detect memory leaks in long-running streams', async () => {\n    const server = createServer((req, res) => {\n      res.writeHead(200, { 'Content-Type': 'text\u002Fevent-stream' });\n\n      let count = 0;\n      const interval = setInterval(() => {\n        count++;\n        const largePayload = 'x'.repeat(1024); \u002F\u002F 1KB per event\n        res.write(`data: ${JSON.stringify({ count, payload: largePayload })}\\n\\n`);\n\n        if (count >= 1000) {\n          clearInterval(interval);\n          res.end();\n        }\n      }, 1);\n\n      req.on('close', () => clearInterval(interval));\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const memBefore = process.memoryUsage().heapUsed;\n\n    const response = await fetch(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n    const reader = response.body!.getReader();\n    let eventCount = 0;\n\n    while (true) {\n      const { done } = await reader.read();\n      if (done) break;\n      eventCount++;\n    }\n\n    const memAfter = process.memoryUsage().heapUsed;\n    const memGrowthMB = (memAfter - memBefore) \u002F (1024 * 1024);\n\n    server.close();\n\n    expect(eventCount).toBeGreaterThan(0);\n    \u002F\u002F Memory growth should be bounded (not proportional to total data received)\n    expect(memGrowthMB).toBeLessThan(50);\n  });\n});\n```\n\n## Connection Resilience Testing\n\n```typescript\n\u002F\u002F tests\u002Fhelpers\u002Fstream-collector.ts\nexport interface StreamCollectorOptions {\n  timeoutMs?: number;\n  maxEvents?: number;\n  onEvent?: (event: any) => void;\n}\n\nexport async function collectSSEEvents(\n  url: string,\n  options: StreamCollectorOptions = {}\n): Promise\u003C{ events: any[]; errors: Error[]; reconnections: number }> {\n  const { timeoutMs = 10000, maxEvents = Infinity } = options;\n  const events: any[] = [];\n  const errors: Error[] = [];\n  let reconnections = 0;\n\n  return new Promise((resolve) => {\n    const timeout = setTimeout(() => {\n      es.close();\n      resolve({ events, errors, reconnections });\n    }, timeoutMs);\n\n    const es = new EventSource(url);\n\n    es.onopen = () => {\n      if (events.length > 0) reconnections++;\n    };\n\n    es.onmessage = (event) => {\n      const data = JSON.parse(event.data);\n      events.push(data);\n      options.onEvent?.(data);\n\n      if (events.length >= maxEvents) {\n        clearTimeout(timeout);\n        es.close();\n        resolve({ events, errors, reconnections });\n      }\n    };\n\n    es.onerror = (err) => {\n      errors.push(new Error('SSE connection error'));\n    };\n  });\n}\n```\n\n## Streaming Performance Testing\n\n```python\n# tests\u002Fperformance\u002Fstream_load_test.py\n\"\"\"\nLoad test for streaming endpoints using asyncio.\nSimulates multiple concurrent SSE consumers.\n\"\"\"\n\nimport asyncio\nimport aiohttp\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import List\n\n\n@dataclass\nclass StreamMetrics:\n    connection_time_ms: float = 0\n    time_to_first_event_ms: float = 0\n    total_events: int = 0\n    total_duration_ms: float = 0\n    inter_event_latencies: List[float] = field(default_factory=list)\n    errors: List[str] = field(default_factory=list)\n\n    @property\n    def avg_inter_event_latency(self) -> float:\n        if not self.inter_event_latencies:\n            return 0\n        return sum(self.inter_event_latencies) \u002F len(self.inter_event_latencies)\n\n    @property\n    def p99_inter_event_latency(self) -> float:\n        if not self.inter_event_latencies:\n            return 0\n        sorted_latencies = sorted(self.inter_event_latencies)\n        idx = int(len(sorted_latencies) * 0.99)\n        return sorted_latencies[idx]\n\n\nasync def consume_sse_stream(url: str, max_events: int = 100) -> StreamMetrics:\n    \"\"\"Consume an SSE stream and collect performance metrics.\"\"\"\n    metrics = StreamMetrics()\n    start = time.monotonic()\n\n    try:\n        async with aiohttp.ClientSession() as session:\n            connect_start = time.monotonic()\n            async with session.get(url) as response:\n                metrics.connection_time_ms = (time.monotonic() - connect_start) * 1000\n\n                last_event_time = None\n                async for line in response.content:\n                    decoded = line.decode('utf-8').strip()\n                    if decoded.startswith('data: '):\n                        now = time.monotonic()\n\n                        if metrics.total_events == 0:\n                            metrics.time_to_first_event_ms = (now - start) * 1000\n\n                        if last_event_time:\n                            latency = (now - last_event_time) * 1000\n                            metrics.inter_event_latencies.append(latency)\n\n                        last_event_time = now\n                        metrics.total_events += 1\n\n                        if metrics.total_events >= max_events:\n                            break\n\n    except Exception as e:\n        metrics.errors.append(str(e))\n\n    metrics.total_duration_ms = (time.monotonic() - start) * 1000\n    return metrics\n\n\nasync def load_test_streams(\n    url: str,\n    concurrent_consumers: int = 50,\n    events_per_consumer: int = 100,\n) -> List[StreamMetrics]:\n    \"\"\"Run concurrent SSE consumers and collect aggregate metrics.\"\"\"\n    tasks = [\n        consume_sse_stream(url, events_per_consumer)\n        for _ in range(concurrent_consumers)\n    ]\n    return await asyncio.gather(*tasks)\n\n\ndef print_report(results: List[StreamMetrics]):\n    \"\"\"Print a summary report of the load test.\"\"\"\n    successful = [r for r in results if not r.errors]\n    failed = [r for r in results if r.errors]\n\n    print(f\"\\n{'='*60}\")\n    print(f\"Streaming Load Test Report\")\n    print(f\"{'='*60}\")\n    print(f\"Total consumers:    {len(results)}\")\n    print(f\"Successful:         {len(successful)}\")\n    print(f\"Failed:             {len(failed)}\")\n\n    if successful:\n        avg_ttfe = sum(r.time_to_first_event_ms for r in successful) \u002F len(successful)\n        avg_conn = sum(r.connection_time_ms for r in successful) \u002F len(successful)\n        all_latencies = [l for r in successful for l in r.inter_event_latencies]\n        all_latencies.sort()\n\n        print(f\"\\nAvg connection time:       {avg_conn:.1f}ms\")\n        print(f\"Avg time to first event:   {avg_ttfe:.1f}ms\")\n        if all_latencies:\n            p50 = all_latencies[len(all_latencies) \u002F\u002F 2]\n            p95 = all_latencies[int(len(all_latencies) * 0.95)]\n            p99 = all_latencies[int(len(all_latencies) * 0.99)]\n            print(f\"Inter-event latency p50:   {p50:.1f}ms\")\n            print(f\"Inter-event latency p95:   {p95:.1f}ms\")\n            print(f\"Inter-event latency p99:   {p99:.1f}ms\")\n\n\nif __name__ == '__main__':\n    import sys\n\n    url = sys.argv[1] if len(sys.argv) > 1 else 'http:\u002F\u002Flocalhost:3000\u002Fevents'\n    results = asyncio.run(load_test_streams(url, concurrent_consumers=50))\n    print_report(results)\n```\n\n## Best Practices\n\n1. **Always set timeouts on stream consumers** -- A test that waits forever for a stream event blocks the entire suite.\n2. **Use AbortController for fetch-based streams** -- Clean cancellation prevents resource leaks in tests.\n3. **Validate intermediate state, not just final state** -- Streaming is about the journey; assert on each chunk.\n4. **Buffer partial data correctly** -- Chunks can split across read boundaries; always use a line buffer.\n5. **Test empty streams** -- A stream that opens and immediately closes should not crash the consumer.\n6. **Measure time-to-first-byte separately** -- TTFB is the most critical streaming performance metric.\n7. **Test with realistic payload sizes** -- Small test payloads may miss backpressure and buffering issues.\n8. **Close streams in afterEach\u002FafterAll** -- Leaked connections cause flaky tests and port exhaustion.\n9. **Test the [DONE] signal** -- For LLM streams, verify the termination protocol is handled correctly.\n10. **Use mock servers, not production endpoints** -- Tests must be deterministic; real streaming services are not.\n\n## Anti-Patterns to Avoid\n\n1. **Collecting entire stream before asserting** -- This defeats the purpose of testing streaming; validate incrementally.\n2. **Using setTimeout as synchronization** -- Use event-driven assertions (on data, on end) instead of arbitrary delays.\n3. **Ignoring partial reads** -- A single `reader.read()` call may not return a complete event; always buffer.\n4. **Not testing connection drops** -- Real networks fail; simulate disconnections and verify recovery.\n5. **Hardcoding port numbers** -- Use port 0 and let the OS assign a free port to avoid conflicts.\n6. **Skipping error event testing** -- The SSE `onerror` and gRPC `on('error')` handlers need test coverage.\n7. **Testing only happy path timing** -- Measure latency under load, not just with a single consumer.\n8. **Forgetting to drain the stream** -- If a test does not consume the full stream, it may leave the server hanging.\n9. **Not validating Content-Type headers** -- `text\u002Fevent-stream` for SSE is required; wrong headers cause silent failures.\n10. **Sharing server instances across parallel tests** -- Each test should have its own server to avoid interference.\n\n## Running Tests\n\n```bash\n# Run all streaming tests\nnpx vitest run tests\u002Fsse\u002F tests\u002Fgrpc\u002F tests\u002Fchunked\u002F tests\u002Fllm\u002F\n\n# Run SSE tests only\nnpx vitest run tests\u002Fsse\u002F\n\n# Run gRPC streaming tests\nnpx vitest run tests\u002Fgrpc\u002F\n\n# Run LLM streaming tests\nnpx vitest run tests\u002Fllm\u002F\n\n# Run with verbose timing output\nnpx vitest run tests\u002F --reporter=verbose\n\n# Run performance load test (Python)\npython3 tests\u002Fperformance\u002Fstream_load_test.py http:\u002F\u002Flocalhost:3000\u002Fevents\n\n# Run with coverage\nnpx vitest run tests\u002F --coverage\n\n# Watch mode for development\nnpx vitest watch tests\u002Fsse\u002F\n\n# Debug a specific test\nnpx vitest run tests\u002Fllm\u002Fllm-stream.test.ts --reporter=verbose\n```\n","# Streaming API Testing Skill\n\nYou are an expert software engineer specializing in testing streaming APIs, real-time data protocols, and event-driven architectures. When the user asks you to write, review, or debug tests for streaming endpoints including SSE, gRPC streaming, chunked responses, and AI\u002FLLM streaming, follow these detailed instructions.\n\n## Core Principles\n\n1. **Test the stream lifecycle** -- Verify connection establishment, data flow, and graceful termination.\n2. **Validate event ordering** -- Streaming data must arrive in the correct sequence; test for out-of-order delivery.\n3. **Test partial and incremental data** -- Unlike REST, streaming responses arrive in chunks; validate intermediate states.\n4. **Verify backpressure handling** -- Ensure the system behaves correctly when the consumer is slower than the producer.\n5. **Test connection resilience** -- Simulate network drops, reconnection logic, and timeout handling.\n6. **Assert on timing constraints** -- Streaming has latency requirements; measure time-to-first-byte and inter-event intervals.\n7. **Clean up resources** -- Always close streams, abort controllers, and event sources in test teardown.\n\n## Project Structure\n\n```\nproject\u002F\n  src\u002F\n    api\u002F\n      sse-endpoint.ts\n      grpc-service.ts\n      chunked-endpoint.ts\n      llm-stream.ts\n    tests\u002F\n      sse\u002F\n        sse-basic.test.ts\n        sse-reconnection.test.ts\n        sse-backpressure.test.ts\n      grpc\u002F\n        server-streaming.test.ts\n        client-streaming.test.ts\n        bidirectional.test.ts\n      chunked\u002F\n        chunked-transfer.test.ts\n        chunked-json.test.ts\n      llm\u002F\n        llm-stream.test.ts\n        token-validation.test.ts\n      helpers\u002F\n        stream-collector.ts\n        mock-sse-server.ts\n        mock-grpc-server.ts\n        timing-utils.ts\n  vitest.config.ts\n```\n\n## SSE Endpoint Testing\n\n### Basic SSE Connection and Event Validation\n\n```typescript\n\u002F\u002F tests\u002Fsse\u002Fsse-basic.test.ts\nimport { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';\nimport { createServer, Server } from 'http';\nimport EventSource from 'eventsource';\n\nlet server: Server;\nlet baseUrl: string;\n\nbeforeAll(async () => {\n  server = createServer((req, res) => {\n    if (req.url === '\u002Fevents') {\n      res.writeHead(200, {\n        'Content-Type': 'text\u002Fevent-stream',\n        'Cache-Control': 'no-cache',\n        Connection: 'keep-alive',\n      });\n\n      let count = 0;\n      const interval = setInterval(() => {\n        count++;\n        res.write(`id: ${count}\\n`);\n        res.write(`event: message\\n`);\n        res.write(`data: ${JSON.stringify({ count, timestamp: Date.now() })}\\n\\n`);\n\n        if (count >= 5) {\n          clearInterval(interval);\n          res.end();\n        }\n      }, 100);\n\n      req.on('close', () => clearInterval(interval));\n    }\n  });\n\n  await new Promise\u003Cvoid>((resolve) => {\n    server.listen(0, () => {\n      const addr = server.address();\n      if (typeof addr === 'object' && addr) {\n        baseUrl = `http:\u002F\u002Flocalhost:${addr.port}`;\n      }\n      resolve();\n    });\n  });\n});\n\nafterAll(() => {\n  server.close();\n});\n\ndescribe('SSE Basic', () => {\n  it('should receive all events in order', async () => {\n    const events: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve, reject) => {\n      const es = new EventSource(`${baseUrl}\u002Fevents`);\n      const timeout = setTimeout(() => {\n        es.close();\n        reject(new Error('Timeout waiting for events'));\n      }, 5000);\n\n      es.onmessage = (event) => {\n        events.push(JSON.parse(event.data));\n      };\n\n      es.onerror = () => {\n        clearTimeout(timeout);\n        es.close();\n        resolve(); \u002F\u002F SSE error fires on stream end\n      };\n    });\n\n    expect(events).toHaveLength(5);\n    expect(events.map((e) => e.count)).toEqual([1, 2, 3, 4, 5]);\n  });\n\n  it('should set correct SSE headers', async () => {\n    const response = await fetch(`${baseUrl}\u002Fevents`);\n\n    expect(response.headers.get('content-type')).toBe('text\u002Fevent-stream');\n    expect(response.headers.get('cache-control')).toBe('no-cache');\n    expect(response.headers.get('connection')).toBe('keep-alive');\n\n    \u002F\u002F Clean up the stream\n    await response.body?.cancel();\n  });\n\n  it('should include event IDs for resumption', async () => {\n    const eventIds: string[] = [];\n\n    await new Promise\u003Cvoid>((resolve) => {\n      const es = new EventSource(`${baseUrl}\u002Fevents`);\n\n      es.onmessage = (event) => {\n        eventIds.push(event.lastEventId);\n        if (eventIds.length >= 5) {\n          es.close();\n          resolve();\n        }\n      };\n\n      es.onerror = () => {\n        es.close();\n        resolve();\n      };\n    });\n\n    expect(eventIds).toEqual(['1', '2', '3', '4', '5']);\n  });\n});\n```\n\n### SSE Reconnection Testing\n\n```typescript\n\u002F\u002F tests\u002Fsse\u002Fsse-reconnection.test.ts\nimport { describe, it, expect } from 'vitest';\nimport { createServer, Server, IncomingMessage, ServerResponse } from 'http';\n\ndescribe('SSE Reconnection', () => {\n  it('should reconnect and resume from last event ID', async () => {\n    let connectionCount = 0;\n\n    const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n      connectionCount++;\n      const lastEventId = req.headers['last-event-id'];\n\n      res.writeHead(200, {\n        'Content-Type': 'text\u002Fevent-stream',\n        'Cache-Control': 'no-cache',\n        Connection: 'keep-alive',\n      });\n\n      const startFrom = lastEventId ? parseInt(lastEventId as string) + 1 : 1;\n\n      if (connectionCount === 1) {\n        \u002F\u002F First connection: send events 1-3, then drop\n        for (let i = startFrom; i \u003C= 3; i++) {\n          res.write(`id: ${i}\\ndata: ${JSON.stringify({ n: i })}\\n\\n`);\n        }\n        res.destroy(); \u002F\u002F Simulate connection drop\n      } else {\n        \u002F\u002F Reconnection: send events 4-6\n        for (let i = startFrom; i \u003C= 6; i++) {\n          res.write(`id: ${i}\\ndata: ${JSON.stringify({ n: i })}\\n\\n`);\n        }\n        res.end();\n      }\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const allEvents: number[] = [];\n\n    await new Promise\u003Cvoid>((resolve) => {\n      const es = new EventSource(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n      const timeout = setTimeout(() => {\n        es.close();\n        resolve();\n      }, 5000);\n\n      es.onmessage = (event) => {\n        const data = JSON.parse(event.data);\n        allEvents.push(data.n);\n\n        if (data.n >= 6) {\n          clearTimeout(timeout);\n          es.close();\n          resolve();\n        }\n      };\n    });\n\n    server.close();\n\n    \u002F\u002F Verify all events received across reconnection\n    expect(allEvents).toEqual([1, 2, 3, 4, 5, 6]);\n    expect(connectionCount).toBe(2);\n  });\n\n  it('should handle server-sent retry interval', async () => {\n    const server = createServer((req, res) => {\n      res.writeHead(200, {\n        'Content-Type': 'text\u002Fevent-stream',\n        'Cache-Control': 'no-cache',\n      });\n\n      \u002F\u002F Set custom retry interval (500ms)\n      res.write('retry: 500\\n\\n');\n      res.write('data: hello\\n\\n');\n      res.end();\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const reconnectTimes: number[] = [];\n    let lastDisconnect = 0;\n\n    await new Promise\u003Cvoid>((resolve) => {\n      let messageCount = 0;\n      const es = new EventSource(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n\n      es.onmessage = () => {\n        messageCount++;\n      };\n\n      es.onerror = () => {\n        if (lastDisconnect > 0) {\n          reconnectTimes.push(Date.now() - lastDisconnect);\n        }\n        lastDisconnect = Date.now();\n\n        if (messageCount >= 2) {\n          es.close();\n          resolve();\n        }\n      };\n\n      setTimeout(() => {\n        es.close();\n        resolve();\n      }, 3000);\n    });\n\n    server.close();\n\n    \u002F\u002F Reconnect time should be approximately 500ms (within tolerance)\n    if (reconnectTimes.length > 0) {\n      expect(reconnectTimes[0]).toBeGreaterThan(400);\n      expect(reconnectTimes[0]).toBeLessThan(1000);\n    }\n  });\n});\n```\n\n## Chunked Transfer Encoding Testing\n\n```typescript\n\u002F\u002F tests\u002Fchunked\u002Fchunked-transfer.test.ts\nimport { describe, it, expect } from 'vitest';\nimport { createServer, Server } from 'http';\n\ndescribe('Chunked Transfer Encoding', () => {\n  let server: Server;\n  let baseUrl: string;\n\n  beforeAll(async () => {\n    server = createServer((req, res) => {\n      if (req.url === '\u002Fchunked-json') {\n        res.writeHead(200, {\n          'Content-Type': 'application\u002Fjson',\n          'Transfer-Encoding': 'chunked',\n        });\n\n        const items = [\n          { id: 1, name: 'first' },\n          { id: 2, name: 'second' },\n          { id: 3, name: 'third' },\n        ];\n\n        let index = 0;\n        const sendNext = () => {\n          if (index \u003C items.length) {\n            const prefix = index === 0 ? '[' : ',';\n            const suffix = index === items.length - 1 ? ']' : '';\n            res.write(`${prefix}${JSON.stringify(items[index])}${suffix}`);\n            index++;\n            setTimeout(sendNext, 50);\n          } else {\n            res.end();\n          }\n        };\n\n        sendNext();\n      }\n\n      if (req.url === '\u002Fndjson') {\n        res.writeHead(200, {\n          'Content-Type': 'application\u002Fx-ndjson',\n        });\n\n        const lines = [\n          { event: 'start', ts: 1 },\n          { event: 'data', value: 42, ts: 2 },\n          { event: 'data', value: 84, ts: 3 },\n          { event: 'end', ts: 4 },\n        ];\n\n        let index = 0;\n        const sendNext = () => {\n          if (index \u003C lines.length) {\n            res.write(JSON.stringify(lines[index]) + '\\n');\n            index++;\n            setTimeout(sendNext, 50);\n          } else {\n            res.end();\n          }\n        };\n\n        sendNext();\n      }\n    });\n\n    await new Promise\u003Cvoid>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        baseUrl = `http:\u002F\u002Flocalhost:${typeof addr === 'object' ? addr!.port : 0}`;\n        resolve();\n      });\n    });\n  });\n\n  afterAll(() => server.close());\n\n  it('should collect chunked JSON array', async () => {\n    const response = await fetch(`${baseUrl}\u002Fchunked-json`);\n    const data = await response.json();\n\n    expect(data).toEqual([\n      { id: 1, name: 'first' },\n      { id: 2, name: 'second' },\n      { id: 3, name: 'third' },\n    ]);\n  });\n\n  it('should process NDJSON stream line by line', async () => {\n    const response = await fetch(`${baseUrl}\u002Fndjson`);\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const events: any[] = [];\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.trim()) {\n          events.push(JSON.parse(line));\n        }\n      }\n    }\n\n    expect(events).toHaveLength(4);\n    expect(events[0].event).toBe('start');\n    expect(events[3].event).toBe('end');\n  });\n\n  it('should measure time-to-first-byte for chunked response', async () => {\n    const startTime = performance.now();\n    const response = await fetch(`${baseUrl}\u002Fndjson`);\n    const reader = response.body!.getReader();\n\n    const { value } = await reader.read();\n    const ttfb = performance.now() - startTime;\n\n    expect(value).toBeTruthy();\n    expect(ttfb).toBeLessThan(1000); \u002F\u002F First byte within 1 second\n\n    \u002F\u002F Clean up\n    await reader.cancel();\n  });\n});\n```\n\n## gRPC Streaming Tests\n\n```typescript\n\u002F\u002F tests\u002Fgrpc\u002Fserver-streaming.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\nimport * as grpc from '@grpc\u002Fgrpc-js';\nimport * as protoLoader from '@grpc\u002Fproto-loader';\n\n\u002F\u002F Proto definition for reference:\n\u002F\u002F service StockService {\n\u002F\u002F   rpc StreamPrices (PriceRequest) returns (stream PriceUpdate);\n\u002F\u002F   rpc SendOrders (stream Order) returns (OrderSummary);\n\u002F\u002F   rpc TradeChat (stream ChatMessage) returns (stream ChatMessage);\n\u002F\u002F }\n\ndescribe('gRPC Server Streaming', () => {\n  let client: any;\n  let server: grpc.Server;\n\n  beforeAll(async () => {\n    const packageDef = protoLoader.loadSync('protos\u002Fstock.proto');\n    const proto = grpc.loadPackageDefinition(packageDef) as any;\n\n    \u002F\u002F Set up mock gRPC server\n    server = new grpc.Server();\n    server.addService(proto.stock.StockService.service, {\n      streamPrices: (call: any) => {\n        const symbols = call.request.symbols;\n        let tick = 0;\n\n        const interval = setInterval(() => {\n          tick++;\n          for (const symbol of symbols) {\n            call.write({\n              symbol,\n              price: 100 + Math.random() * 10,\n              tick,\n              timestamp: Date.now(),\n            });\n          }\n\n          if (tick >= 5) {\n            clearInterval(interval);\n            call.end();\n          }\n        }, 100);\n\n        call.on('cancelled', () => clearInterval(interval));\n      },\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve, reject) => {\n      server.bindAsync(\n        '0.0.0.0:0',\n        grpc.ServerCredentials.createInsecure(),\n        (err, port) => {\n          if (err) reject(err);\n          else resolve(port);\n        }\n      );\n    });\n\n    server.start();\n\n    client = new proto.stock.StockService(\n      `localhost:${port}`,\n      grpc.credentials.createInsecure()\n    );\n  });\n\n  afterAll(() => {\n    server.forceShutdown();\n  });\n\n  it('should receive all price updates from server stream', async () => {\n    const updates: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve, reject) => {\n      const call = client.streamPrices({ symbols: ['AAPL', 'GOOG'] });\n\n      call.on('data', (update: any) => {\n        updates.push(update);\n      });\n\n      call.on('end', () => resolve());\n      call.on('error', (err: Error) => reject(err));\n    });\n\n    \u002F\u002F 5 ticks * 2 symbols = 10 updates\n    expect(updates).toHaveLength(10);\n\n    \u002F\u002F Verify ordering: ticks should be sequential\n    const applUpdates = updates.filter((u) => u.symbol === 'AAPL');\n    const ticks = applUpdates.map((u) => u.tick);\n    expect(ticks).toEqual([1, 2, 3, 4, 5]);\n\n    \u002F\u002F Verify price is within expected range\n    for (const update of updates) {\n      expect(update.price).toBeGreaterThan(90);\n      expect(update.price).toBeLessThan(120);\n    }\n  });\n\n  it('should handle client cancellation of server stream', async () => {\n    const updates: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve) => {\n      const call = client.streamPrices({ symbols: ['AAPL'] });\n\n      call.on('data', (update: any) => {\n        updates.push(update);\n        if (updates.length >= 2) {\n          call.cancel(); \u002F\u002F Cancel after 2 updates\n        }\n      });\n\n      call.on('error', (err: any) => {\n        if (err.code === grpc.status.CANCELLED) {\n          resolve(); \u002F\u002F Expected cancellation\n        }\n      });\n    });\n\n    expect(updates.length).toBeGreaterThanOrEqual(2);\n    expect(updates.length).toBeLessThan(10);\n  });\n});\n\n\u002F\u002F tests\u002Fgrpc\u002Fbidirectional.test.ts\ndescribe('gRPC Bidirectional Streaming', () => {\n  it('should support bidirectional message exchange', async () => {\n    const received: any[] = [];\n\n    await new Promise\u003Cvoid>((resolve, reject) => {\n      const call = client.tradeChat();\n\n      call.on('data', (msg: any) => {\n        received.push(msg);\n      });\n\n      call.on('end', () => resolve());\n      call.on('error', (err: Error) => reject(err));\n\n      \u002F\u002F Send messages from client\n      call.write({ user: 'trader1', message: 'Buy AAPL' });\n      call.write({ user: 'trader1', message: 'Sell GOOG' });\n      call.end();\n    });\n\n    expect(received.length).toBeGreaterThan(0);\n    for (const msg of received) {\n      expect(msg).toHaveProperty('user');\n      expect(msg).toHaveProperty('message');\n    }\n  });\n});\n```\n\n## AI\u002FLLM Streaming Response Testing\n\n```typescript\n\u002F\u002F tests\u002Fllm\u002Fllm-stream.test.ts\nimport { describe, it, expect, beforeAll, afterAll } from 'vitest';\nimport { createServer, Server } from 'http';\n\ndescribe('LLM Streaming Response', () => {\n  let server: Server;\n  let baseUrl: string;\n\n  beforeAll(async () => {\n    server = createServer((req, res) => {\n      if (req.url === '\u002Fv1\u002Fchat\u002Fcompletions' && req.method === 'POST') {\n        res.writeHead(200, {\n          'Content-Type': 'text\u002Fevent-stream',\n          'Cache-Control': 'no-cache',\n        });\n\n        const tokens = ['Hello', ',', ' how', ' can', ' I', ' help', ' you', '?'];\n        let index = 0;\n\n        const sendToken = () => {\n          if (index \u003C tokens.length) {\n            const chunk = {\n              id: 'chatcmpl-abc123',\n              object: 'chat.completion.chunk',\n              created: Math.floor(Date.now() \u002F 1000),\n              model: 'gpt-4',\n              choices: [\n                {\n                  index: 0,\n                  delta: { content: tokens[index] },\n                  finish_reason: null,\n                },\n              ],\n            };\n            res.write(`data: ${JSON.stringify(chunk)}\\n\\n`);\n            index++;\n            setTimeout(sendToken, 30);\n          } else {\n            \u002F\u002F Send final chunk with finish_reason\n            const finalChunk = {\n              id: 'chatcmpl-abc123',\n              object: 'chat.completion.chunk',\n              created: Math.floor(Date.now() \u002F 1000),\n              model: 'gpt-4',\n              choices: [\n                {\n                  index: 0,\n                  delta: {},\n                  finish_reason: 'stop',\n                },\n              ],\n            };\n            res.write(`data: ${JSON.stringify(finalChunk)}\\n\\n`);\n            res.write('data: [DONE]\\n\\n');\n            res.end();\n          }\n        };\n\n        sendToken();\n      }\n    });\n\n    await new Promise\u003Cvoid>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        baseUrl = `http:\u002F\u002Flocalhost:${typeof addr === 'object' ? addr!.port : 0}`;\n        resolve();\n      });\n    });\n  });\n\n  afterAll(() => server.close());\n\n  it('should collect all tokens from streaming response', async () => {\n    const response = await fetch(`${baseUrl}\u002Fv1\u002Fchat\u002Fcompletions`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        model: 'gpt-4',\n        messages: [{ role: 'user', content: 'Hello' }],\n        stream: true,\n      }),\n    });\n\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const tokens: string[] = [];\n    let finishReason: string | null = null;\n    let receivedDone = false;\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.startsWith('data: ')) {\n          const data = line.slice(6).trim();\n\n          if (data === '[DONE]') {\n            receivedDone = true;\n            continue;\n          }\n\n          const parsed = JSON.parse(data);\n          const delta = parsed.choices[0].delta;\n\n          if (delta.content) {\n            tokens.push(delta.content);\n          }\n\n          if (parsed.choices[0].finish_reason) {\n            finishReason = parsed.choices[0].finish_reason;\n          }\n        }\n      }\n    }\n\n    const fullText = tokens.join('');\n    expect(fullText).toBe('Hello, how can I help you?');\n    expect(finishReason).toBe('stop');\n    expect(receivedDone).toBe(true);\n    expect(tokens).toHaveLength(8);\n  });\n\n  it('should measure token latency', async () => {\n    const response = await fetch(`${baseUrl}\u002Fv1\u002Fchat\u002Fcompletions`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        model: 'gpt-4',\n        messages: [{ role: 'user', content: 'Hello' }],\n        stream: true,\n      }),\n    });\n\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const tokenTimestamps: number[] = [];\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.startsWith('data: ') && line.slice(6).trim() !== '[DONE]') {\n          const parsed = JSON.parse(line.slice(6));\n          if (parsed.choices[0].delta.content) {\n            tokenTimestamps.push(performance.now());\n          }\n        }\n      }\n    }\n\n    \u002F\u002F Calculate inter-token latencies\n    const latencies: number[] = [];\n    for (let i = 1; i \u003C tokenTimestamps.length; i++) {\n      latencies.push(tokenTimestamps[i] - tokenTimestamps[i - 1]);\n    }\n\n    const avgLatency = latencies.reduce((a, b) => a + b, 0) \u002F latencies.length;\n    const maxLatency = Math.max(...latencies);\n\n    \u002F\u002F Assert reasonable latency bounds\n    expect(avgLatency).toBeLessThan(200); \u002F\u002F Average under 200ms\n    expect(maxLatency).toBeLessThan(500); \u002F\u002F No single gap over 500ms\n  });\n\n  it('should handle abort during streaming', async () => {\n    const controller = new AbortController();\n    const tokensReceived: string[] = [];\n\n    const response = await fetch(`${baseUrl}\u002Fv1\u002Fchat\u002Fcompletions`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        model: 'gpt-4',\n        messages: [{ role: 'user', content: 'Hello' }],\n        stream: true,\n      }),\n      signal: controller.signal,\n    });\n\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n\n    try {\n      let buffer = '';\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        buffer += decoder.decode(value, { stream: true });\n        const lines = buffer.split('\\n');\n        buffer = lines.pop() || '';\n\n        for (const line of lines) {\n          if (line.startsWith('data: ') && line.slice(6).trim() !== '[DONE]') {\n            const parsed = JSON.parse(line.slice(6));\n            if (parsed.choices[0].delta.content) {\n              tokensReceived.push(parsed.choices[0].delta.content);\n              if (tokensReceived.length >= 3) {\n                controller.abort();\n              }\n            }\n          }\n        }\n      }\n    } catch (err: any) {\n      expect(err.name).toBe('AbortError');\n    }\n\n    expect(tokensReceived.length).toBeGreaterThanOrEqual(3);\n    expect(tokensReceived.length).toBeLessThan(8);\n  });\n});\n```\n\n## Backpressure and Flow Control Testing\n\n```typescript\n\u002F\u002F tests\u002Fsse\u002Fsse-backpressure.test.ts\nimport { describe, it, expect } from 'vitest';\nimport { createServer, Server } from 'http';\nimport { Readable, Transform } from 'stream';\n\ndescribe('Backpressure Testing', () => {\n  it('should handle slow consumer without losing data', async () => {\n    const totalEvents = 100;\n    const consumerDelayMs = 10;\n\n    const server = createServer((req, res) => {\n      res.writeHead(200, { 'Content-Type': 'text\u002Fevent-stream' });\n\n      for (let i = 0; i \u003C totalEvents; i++) {\n        const canWrite = res.write(`data: ${JSON.stringify({ seq: i })}\\n\\n`);\n        if (!canWrite) {\n          \u002F\u002F Wait for drain event when buffer is full\n          res.once('drain', () => {});\n        }\n      }\n      res.end();\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const response = await fetch(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n    const reader = response.body!.getReader();\n    const decoder = new TextDecoder();\n    const received: number[] = [];\n\n    let buffer = '';\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n\n      \u002F\u002F Simulate slow consumer\n      await new Promise((r) => setTimeout(r, consumerDelayMs));\n\n      buffer += decoder.decode(value, { stream: true });\n      const lines = buffer.split('\\n');\n      buffer = lines.pop() || '';\n\n      for (const line of lines) {\n        if (line.startsWith('data: ')) {\n          const data = JSON.parse(line.slice(6));\n          received.push(data.seq);\n        }\n      }\n    }\n\n    server.close();\n\n    \u002F\u002F All events should be received despite slow consumer\n    expect(received).toHaveLength(totalEvents);\n    expect(received).toEqual(Array.from({ length: totalEvents }, (_, i) => i));\n  });\n\n  it('should detect memory leaks in long-running streams', async () => {\n    const server = createServer((req, res) => {\n      res.writeHead(200, { 'Content-Type': 'text\u002Fevent-stream' });\n\n      let count = 0;\n      const interval = setInterval(() => {\n        count++;\n        const largePayload = 'x'.repeat(1024); \u002F\u002F 1KB per event\n        res.write(`data: ${JSON.stringify({ count, payload: largePayload })}\\n\\n`);\n\n        if (count >= 1000) {\n          clearInterval(interval);\n          res.end();\n        }\n      }, 1);\n\n      req.on('close', () => clearInterval(interval));\n    });\n\n    const port = await new Promise\u003Cnumber>((resolve) => {\n      server.listen(0, () => {\n        const addr = server.address();\n        resolve(typeof addr === 'object' ? addr!.port : 0);\n      });\n    });\n\n    const memBefore = process.memoryUsage().heapUsed;\n\n    const response = await fetch(`http:\u002F\u002Flocalhost:${port}\u002Fevents`);\n    const reader = response.body!.getReader();\n    let eventCount = 0;\n\n    while (true) {\n      const { done } = await reader.read();\n      if (done) break;\n      eventCount++;\n    }\n\n    const memAfter = process.memoryUsage().heapUsed;\n    const memGrowthMB = (memAfter - memBefore) \u002F (1024 * 1024);\n\n    server.close();\n\n    expect(eventCount).toBeGreaterThan(0);\n    \u002F\u002F Memory growth should be bounded (not proportional to total data received)\n    expect(memGrowthMB).toBeLessThan(50);\n  });\n});\n```\n\n## Connection Resilience Testing\n\n```typescript\n\u002F\u002F tests\u002Fhelpers\u002Fstream-collector.ts\nexport interface StreamCollectorOptions {\n  timeoutMs?: number;\n  maxEvents?: number;\n  onEvent?: (event: any) => void;\n}\n\nexport async function collectSSEEvents(\n  url: string,\n  options: StreamCollectorOptions = {}\n): Promise\u003C{ events: any[]; errors: Error[]; reconnections: number }> {\n  const { timeoutMs = 10000, maxEvents = Infinity } = options;\n  const events: any[] = [];\n  const errors: Error[] = [];\n  let reconnections = 0;\n\n  return new Promise((resolve) => {\n    const timeout = setTimeout(() => {\n      es.close();\n      resolve({ events, errors, reconnections });\n    }, timeoutMs);\n\n    const es = new EventSource(url);\n\n    es.onopen = () => {\n      if (events.length > 0) reconnections++;\n    };\n\n    es.onmessage = (event) => {\n      const data = JSON.parse(event.data);\n      events.push(data);\n      options.onEvent?.(data);\n\n      if (events.length >= maxEvents) {\n        clearTimeout(timeout);\n        es.close();\n        resolve({ events, errors, reconnections });\n      }\n    };\n\n    es.onerror = (err) => {\n      errors.push(new Error('SSE connection error'));\n    };\n  });\n}\n```\n\n## Streaming Performance Testing\n\n```python\n# tests\u002Fperformance\u002Fstream_load_test.py\n\"\"\"\nLoad test for streaming endpoints using asyncio.\nSimulates multiple concurrent SSE consumers.\n\"\"\"\n\nimport asyncio\nimport aiohttp\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import List\n\n\n@dataclass\nclass StreamMetrics:\n    connection_time_ms: float = 0\n    time_to_first_event_ms: float = 0\n    total_events: int = 0\n    total_duration_ms: float = 0\n    inter_event_latencies: List[float] = field(default_factory=list)\n    errors: List[str] = field(default_factory=list)\n\n    @property\n    def avg_inter_event_latency(self) -> float:\n        if not self.inter_event_latencies:\n            return 0\n        return sum(self.inter_event_latencies) \u002F len(self.inter_event_latencies)\n\n    @property\n    def p99_inter_event_latency(self) -> float:\n        if not self.inter_event_latencies:\n            return 0\n        sorted_latencies = sorted(self.inter_event_latencies)\n        idx = int(len(sorted_latencies) * 0.99)\n        return sorted_latencies[idx]\n\n\nasync def consume_sse_stream(url: str, max_events: int = 100) -> StreamMetrics:\n    \"\"\"Consume an SSE stream and collect performance metrics.\"\"\"\n    metrics = StreamMetrics()\n    start = time.monotonic()\n\n    try:\n        async with aiohttp.ClientSession() as session:\n            connect_start = time.monotonic()\n            async with session.get(url) as response:\n                metrics.connection_time_ms = (time.monotonic() - connect_start) * 1000\n\n                last_event_time = None\n                async for line in response.content:\n                    decoded = line.decode('utf-8').strip()\n                    if decoded.startswith('data: '):\n                        now = time.monotonic()\n\n                        if metrics.total_events == 0:\n                            metrics.time_to_first_event_ms = (now - start) * 1000\n\n                        if last_event_time:\n                            latency = (now - last_event_time) * 1000\n                            metrics.inter_event_latencies.append(latency)\n\n                        last_event_time = now\n                        metrics.total_events += 1\n\n                        if metrics.total_events >= max_events:\n                            break\n\n    except Exception as e:\n        metrics.errors.append(str(e))\n\n    metrics.total_duration_ms = (time.monotonic() - start) * 1000\n    return metrics\n\n\nasync def load_test_streams(\n    url: str,\n    concurrent_consumers: int = 50,\n    events_per_consumer: int = 100,\n) -> List[StreamMetrics]:\n    \"\"\"Run concurrent SSE consumers and collect aggregate metrics.\"\"\"\n    tasks = [\n        consume_sse_stream(url, events_per_consumer)\n        for _ in range(concurrent_consumers)\n    ]\n    return await asyncio.gather(*tasks)\n\n\ndef print_report(results: List[StreamMetrics]):\n    \"\"\"Print a summary report of the load test.\"\"\"\n    successful = [r for r in results if not r.errors]\n    failed = [r for r in results if r.errors]\n\n    print(f\"\\n{'='*60}\")\n    print(f\"Streaming Load Test Report\")\n    print(f\"{'='*60}\")\n    print(f\"Total consumers:    {len(results)}\")\n    print(f\"Successful:         {len(successful)}\")\n    print(f\"Failed:             {len(failed)}\")\n\n    if successful:\n        avg_ttfe = sum(r.time_to_first_event_ms for r in successful) \u002F len(successful)\n        avg_conn = sum(r.connection_time_ms for r in successful) \u002F len(successful)\n        all_latencies = [l for r in successful for l in r.inter_event_latencies]\n        all_latencies.sort()\n\n        print(f\"\\nAvg connection time:       {avg_conn:.1f}ms\")\n        print(f\"Avg time to first event:   {avg_ttfe:.1f}ms\")\n        if all_latencies:\n            p50 = all_latencies[len(all_latencies) \u002F\u002F 2]\n            p95 = all_latencies[int(len(all_latencies) * 0.95)]\n            p99 = all_latencies[int(len(all_latencies) * 0.99)]\n            print(f\"Inter-event latency p50:   {p50:.1f}ms\")\n            print(f\"Inter-event latency p95:   {p95:.1f}ms\")\n            print(f\"Inter-event latency p99:   {p99:.1f}ms\")\n\n\nif __name__ == '__main__':\n    import sys\n\n    url = sys.argv[1] if len(sys.argv) > 1 else 'http:\u002F\u002Flocalhost:3000\u002Fevents'\n    results = asyncio.run(load_test_streams(url, concurrent_consumers=50))\n    print_report(results)\n```\n\n## Best Practices\n\n1. **Always set timeouts on stream consumers** -- A test that waits forever for a stream event blocks the entire suite.\n2. **Use AbortController for fetch-based streams** -- Clean cancellation prevents resource leaks in tests.\n3. **Validate intermediate state, not just final state** -- Streaming is about the journey; assert on each chunk.\n4. **Buffer partial data correctly** -- Chunks can split across read boundaries; always use a line buffer.\n5. **Test empty streams** -- A stream that opens and immediately closes should not crash the consumer.\n6. **Measure time-to-first-byte separately** -- TTFB is the most critical streaming performance metric.\n7. **Test with realistic payload sizes** -- Small test payloads may miss backpressure and buffering issues.\n8. **Close streams in afterEach\u002FafterAll** -- Leaked connections cause flaky tests and port exhaustion.\n9. **Test the [DONE] signal** -- For LLM streams, verify the termination protocol is handled correctly.\n10. **Use mock servers, not production endpoints** -- Tests must be deterministic; real streaming services are not.\n\n## Anti-Patterns to Avoid\n\n1. **Collecting entire stream before asserting** -- This defeats the purpose of testing streaming; validate incrementally.\n2. **Using setTimeout as synchronization** -- Use event-driven assertions (on data, on end) instead of arbitrary delays.\n3. **Ignoring partial reads** -- A single `reader.read()` call may not return a complete event; always buffer.\n4. **Not testing connection drops** -- Real networks fail; simulate disconnections and verify recovery.\n5. **Hardcoding port numbers** -- Use port 0 and let the OS assign a free port to avoid conflicts.\n6. **Skipping error event testing** -- The SSE `onerror` and gRPC `on('error')` handlers need test coverage.\n7. **Testing only happy path timing** -- Measure latency under load, not just with a single consumer.\n8. **Forgetting to drain the stream** -- If a test does not consume the full stream, it may leave the server hanging.\n9. **Not validating Content-Type headers** -- `text\u002Fevent-stream` for SSE is required; wrong headers cause silent failures.\n10. **Sharing server instances across parallel tests** -- Each test should have its own server to avoid interference.\n\n## Running Tests\n\n```bash\n# Run all streaming tests\nnpx vitest run tests\u002Fsse\u002F tests\u002Fgrpc\u002F tests\u002Fchunked\u002F tests\u002Fllm\u002F\n\n# Run SSE tests only\nnpx vitest run tests\u002Fsse\u002F\n\n# Run gRPC streaming tests\nnpx vitest run tests\u002Fgrpc\u002F\n\n# Run LLM streaming tests\nnpx vitest run tests\u002Fllm\u002F\n\n# Run with verbose timing output\nnpx vitest run tests\u002F --reporter=verbose\n\n# Run performance load test (Python)\npython3 tests\u002Fperformance\u002Fstream_load_test.py http:\u002F\u002Flocalhost:3000\u002Fevents\n\n# Run with coverage\nnpx vitest run tests\u002F --coverage\n\n# Watch mode for development\nnpx vitest watch tests\u002Fsse\u002F\n\n# Debug a specific test\nnpx vitest run tests\u002Fllm\u002Fllm-stream.test.ts --reporter=verbose\n```\n",{"name":5,"tags":24,"agents":33,"author":46,"domains":47,"license":15,"version":51,"languages":52,"frameworks":56,"description":7,"testingTypes":60},[25,26,27,28,29,30,31,32],"streaming","sse","server-sent-events","grpc-streaming","real-time","chunked-transfer","ai-streaming","backpressure",[34,35,36,37,38,39,40,41,42,43,44,45],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","thetestingacademy",[48,49,50],"api","backend","ai","1.0.0",[53,54,55],"typescript","javascript","python",[57,58,59],"playwright","jest","vitest",[48,61,62],"integration","performance","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fstreaming-api-testing","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m","https:\u002F\u002Fid-preview--d5bef06d-6c9e-4563-a3d4-a855b9d61610.lovable.app\u002F","Eu sou Antonio B. B. Ndombe \r\nEu sou um Pesquisador e desenvolvedor de sistema autonomia cognitivos, fundador de sistemas ODCs ( organismos digital conscientes)","2026-11-04 06:53:39",{"source":8,"skillName":5,"commands":72,"prompt":82,"zipAvailable":83},[73,76,79],{"tool":74,"command":75},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Streaming API Testing\"",{"tool":77,"command":78},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Streaming API Testing\"",{"tool":80,"command":81},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Streaming API Testing\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fstreaming-api-testing\u002FSKILL.md",true,[],[86,94,101,108,115,122],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M7DASC6FSCJP49JZBSK0NY1Z","nemoclaw-user-reference","Describes the NemoClaw integration layer and blueprint architecture and how they orchestrate compatible agent sandboxes. Use when looking up architecture, agent integration, plugin structure, or blueprint design. Trigger keywords - nemoclaw architecture, nemoclaw agent architecture, nemoclaw plugin blueprint structure, nemoclaw vs openshell, which cli, nemoclaw cli, openshell cli, sandbox commands, nemoclaw cli commands, nemoclaw command reference, nemoclaw network policy, sandbox egress control operator approval, nemoclaw troubleshooting, nemoclaw debug sandbox issues.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-reference\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M7DAS5S79VK33XFGVAM2TFWF","nemoclaw-user-overview","Explains how OpenClaw, OpenShell, and NemoClaw form the ecosystem, NemoClaw's position in the stack, what NemoClaw adds beyond the community sandbox, and when to prefer NemoClaw versus integrating OpenShell and OpenClaw directly. Use when users ask about the relationship between OpenClaw, OpenShell, and NemoClaw, or when to use NemoClaw versus OpenShell. Trigger keywords - nemoclaw ecosystem, openclaw openshell, nemoclaw vs openshell, sandboxed openclaw, how nemoclaw works, nemoclaw sandbox lifecycle blueprint, nemoclaw overview, openclaw always-on assistants, nvidia openshell, nvidia nemotron, nemoclaw release notes, nemoclaw changelog.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-overview\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":19},"01M7DAS0PQEMET5MNGZ1ABSZVS","nemoclaw-user-monitor-sandbox","Inspects sandbox health, traces agent behavior, and diagnoses problems. Use when monitoring a running sandbox, debugging agent issues, or checking sandbox logs. Trigger keywords - monitor nemoclaw sandbox, debug nemoclaw agent issues.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-monitor-sandbox\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":19},"01M7DARQYGF7E9A69VH6S3CGN9","nemoclaw-user-manage-sandboxes","Explains operational tasks after the quickstart: listing sandboxes, status and health checks, logs, diagnostics, port forwards, multiple sandboxes, credential reset, rebuilds, network presets, upgrades, and uninstall. Trigger keywords - manage nemoclaw sandboxes, nemoclaw status, nemoclaw list, nemoclaw dashboard port, nemoclaw rebuild, nemoclaw upgrade sandboxes, nemoclaw uninstall, sandbox mutability, sandbox runtime configuration, sandbox rebuild, nemoclaw backup, nemoclaw restore, workspace backup, openshell sandbox download upload, nemoclaw messaging channels, nemoclaw telegram, nemoclaw discord, nemoclaw slack, nemoclaw wechat, nemoclaw whatsapp, openshell channel messaging, nemoclaw workspace files, soul.md, user.md, identity.md, agents.md, sandbox persistence.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-sandboxes\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":19},"01M7DARH8BRTG51TRCAB7YWDJ4","nemoclaw-user-manage-policy","Adds, removes, or modifies allowed endpoints in the sandbox policy. Use when customizing network policy, changing egress rules, or configuring sandbox endpoint access. Trigger keywords - customize nemoclaw network policy, sandbox egress policy configuration, nemoclaw integration policy examples, post-install policy setup, openshell approval workflow, policy preset, nemoclaw approve network requests, sandbox egress approval tui.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-policy\u002FSKILL.md",[],[],{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":19},"01M7DARAT62M2VR37590VCZ5NS","nemoclaw-user-get-started","Installs NemoClaw, launches a sandbox, and runs the first agent prompt. Use when onboarding, installing, or launching a NemoClaw sandbox for the first time. Trigger keywords - nemoclaw quickstart, install nemoclaw openclaw sandbox, nemohermes quickstart, hermes agent nemoclaw, run hermes openshell sandbox, nemoclaw prerequisites, nemoclaw supported platforms, nemoclaw hardware software, nemoclaw windows wsl2 setup, nemoclaw install windows docker desktop.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-get-started\u002FSKILL.md",[],[]]