Skip to content

Commit 75e04da

Browse files
authored
test: make the Cohere streaming drift leg compare real event frames (#528)
## Problem The streaming `/v2/chat` shape leg in `cohere.drift.ts` never compared anything. It parsed both bodies with `parseDataOnlySSE`, which keeps only frames that *start* with `data: `. Every Cohere v2 frame is `event: <type>` + `data: <json>`, so both lists came out empty, the `if (realChunks.length > 0 && mockChunks.length > 0)` guard was false, and the test always passed. (A non-200 mock reply was also let through without a comparison.) ## Fix (test-only; no `src/` behavior change) - `parseCohereSSE`: strict parser. Each frame must be exactly `event:` + `data:` with `data.type` equal to the event name. A trailing `data: [DONE]` is dropped. Any other frame throws instead of being dropped. - The leg now requires mock status 200 and non-empty event lists on both sides, opening with `message-start` and closing with `message-end`. It compares every event type with `compareSSESequences` against SDK shapes for message-start / content-start / content-delta / content-end / message-end (the same pattern the Anthropic stream leg uses). - Live no-generation: the 422 envelope skip is unchanged. A 200 stream whose `message-end` is the no-generation terminal (`finish_reason: "ERROR"`, empty usage) is now a skip that gives the upstream code and id (`NO_VALID_RESPONSE_GENERATED id=...`), the same as #525. `isCohereNoGenerationStreamEnd` now takes the allowed error types, like `cohereNoGenerationError`. K5 passes `COHERE_K5_NO_GENERATION`, so K5 behavior is unchanged. - Offline tests: the parser on the recorded live K5 stream fixture, on aimock's real stream, and rejection of malformed frames. Classifier test for the `allowed` param. ## Local RED (current main, live Cohere) Temporary probe in the leg: ``` RED-PROBE realChunks=0 mockChunks=0 realBytes=1607 mockBytes=709 ✓ Cohere drift > streaming /v2/chat shape matches ``` Mutant in `src/cohere.ts` (text stream `message-end`: `finish_reason` renamed to `finishReason`). The test **still passes**: ``` RED-PROBE realChunks=0 mockChunks=0 realBytes=1607 mockBytes=708 Tests 2 passed | 24 skipped (26) ``` ## Local GREEN (this branch, live Cohere) ``` GREEN-PROBE realEvents=13 [message-start,content-start,content-delta x9,content-end,message-end] mockEvents=5 [message-start,content-start,content-delta,content-end,message-end] ``` Two consecutive live runs, probe removed: ``` run 1: ✓ Cohere drift > streaming /v2/chat shape matches 304ms run 2: ✓ Cohere drift > streaming /v2/chat shape matches 317ms ``` The same `finishReason` mutant now **fails**: ``` × Cohere drift > streaming /v2/chat shape matches [critical] LLMOCK DRIFT — field in SDK + real API but missing from mock Path: SSE:message-end.delta.finish_reason ``` A second mutant (drop the `content-end` event) also **fails**: ``` [critical] LLMOCK DRIFT — real API emits event type "content-end" but mock does not ``` Both mutants reverted. ## Non-critical differences now visible (not fixed here) These come from the comparison, but the existing triangulation rules do not rate them critical: live `usage.cached_tokens`, live `content-start` carries `text: ""`, and aimock adds `content.type` on deltas plus `billed_units.search_units/classifications`. Outside the shape comparison: live ends with `data: [DONE]` and aimock's Cohere stream does not. ## Gates `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm build`, `pnpm test` (377 files, 14080 passed) all pass. ## Follow-up: parse by the SSE spec (review finding) `parseCohereSSE` threw on legal SSE: a single trailing `\n`, `event:X` with no space, `:` keepalive comments, and `id:`/`retry:` lines. It now follows the WHATWG event-stream rules: any line ending (`\n`, `\r\n`, `\r`), the space after the colon is optional, comments and `id`/`retry`/unknown fields are ignored, multi-line `data` is joined, and a final event is dispatched without a trailing blank line. These still throw: data that is not JSON, data that is not an object, an event name that does not match `data.type` (an event without `event:` is named `message` by the spec), and any event after `[DONE]`. RED: the new offline tests run against the previous parser: ``` × parseCohereSSE > accepts legal SSE variants a server or proxy may send Error: Unsupported Cohere SSE frame: "event: message-end\ndata: {...}\n" × parseCohereSSE > rejects malformed data, mismatched names and events after [DONE] ``` GREEN: all 4 parser tests pass. Live streaming leg passed 2 consecutive times. The `finishReason` mutant still fails on `SSE:message-end.delta.finish_reason`. Gates pass again (377 files, 14080 tests).
2 parents 5474090 + 32bd1cb commit 75e04da

3 files changed

Lines changed: 249 additions & 71 deletions

File tree

‎src/__tests__/drift/cohere-model.test.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,15 @@ describe("isCohereNoGenerationStreamEnd", () => {
143143
};
144144

145145
it("recognizes the exact observed mid-stream terminal", () => {
146-
expect(isCohereNoGenerationStreamEnd(end)).toBe(true);
146+
expect(isCohereNoGenerationStreamEnd(end, COHERE_K5_NO_GENERATION)).toBe(true);
147+
});
148+
149+
it("accepts only the error types the caller allows", () => {
150+
// CONSTRUCTED: the no-tools shape leg's mid-stream terminal would carry
151+
// NO_VALID_RESPONSE_GENERATED; that terminal has not been observed live.
152+
const noValid = { ...end, error_type: "NO_VALID_RESPONSE_GENERATED" };
153+
expect(isCohereNoGenerationStreamEnd(noValid, COHERE_SHAPE_LEG_NO_GENERATION)).toBe(true);
154+
expect(isCohereNoGenerationStreamEnd(end, COHERE_SHAPE_LEG_NO_GENERATION)).toBe(false);
147155
});
148156

149157
it("rejects any deviation", () => {
@@ -158,6 +166,9 @@ describe("isCohereNoGenerationStreamEnd", () => {
158166
{ ...end, extra: 1 },
159167
{ finish_reason: "ERROR", usage: {}, error_type: end.error_type },
160168
])
161-
expect(isCohereNoGenerationStreamEnd(mutant), JSON.stringify(mutant)).toBe(false);
169+
expect(
170+
isCohereNoGenerationStreamEnd(mutant, COHERE_K5_NO_GENERATION),
171+
JSON.stringify(mutant),
172+
).toBe(false);
162173
});
163174
});

‎src/__tests__/drift/cohere-model.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,14 +131,22 @@ export function cohereNoGenerationSkipReason(outcomes: CohereNoGeneration[]): st
131131
* Classify a live Cohere SSE `message-end` delta as the exact mid-stream
132132
* no-generation terminal: keys exactly `finish_reason`, `usage`, `error`,
133133
* `error_type`, with `finish_reason === "ERROR"`, `usage` an empty object,
134-
* `error` a non-empty string and `error_type` NO_TOOL_CALL_OR_RESPONSE_GENERATED.
135-
* Returns false for every other terminal.
134+
* `error` a non-empty string and `error_type` in `allowed`. Returns false for
135+
* every other terminal.
136+
*
137+
* As with `cohereNoGenerationError`, `allowed` names only the codes the
138+
* request can produce (K5 passes `COHERE_K5_NO_GENERATION`, the no-tools
139+
* shape legs pass `COHERE_SHAPE_LEG_NO_GENERATION`).
136140
*/
137-
export function isCohereNoGenerationStreamEnd(delta: Record<string, unknown>): boolean {
141+
export function isCohereNoGenerationStreamEnd(
142+
delta: Record<string, unknown>,
143+
allowed: readonly CohereNoGenerationErrorType[],
144+
): boolean {
138145
const keys = Object.keys(delta).sort();
139146
if (keys.join(",") !== "error,error_type,finish_reason,usage") return false;
140147
if (delta.finish_reason !== "ERROR") return false;
141-
if (delta.error_type !== "NO_TOOL_CALL_OR_RESPONSE_GENERATED") return false;
148+
if (!isNoGenerationErrorType(delta.error_type)) return false;
149+
if (!allowed.includes(delta.error_type)) return false;
142150
if (typeof delta.error !== "string" || delta.error.length === 0) return false;
143151
const usage = delta.usage;
144152
return (

‎src/__tests__/drift/cohere.drift.ts‎

Lines changed: 224 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,14 @@ import { CohereClientV2, CohereError, type Cohere } from "cohere-ai";
1616
import { withFaultFixture } from "../helpers/misbehavior-server.js";
1717
import { describe, it, expect, beforeAll, afterAll } from "vitest";
1818
import type { ServerInstance } from "../../server.js";
19-
import { extractShape, triangulate, formatDriftReport } from "./schema.js";
2019
import {
21-
httpPost,
22-
httpPostRaw,
23-
parseDataOnlySSE,
24-
startDriftServer,
25-
stopDriftServer,
26-
} from "./helpers.js";
20+
extractShape,
21+
triangulate,
22+
compareSSESequences,
23+
formatDriftReport,
24+
type SSEEventShape,
25+
} from "./schema.js";
26+
import { httpPost, httpPostRaw, startDriftServer, stopDriftServer } from "./helpers.js";
2727
import {
2828
COHERE_BASE_URL,
2929
COHERE_K5_NO_GENERATION,
@@ -86,18 +86,116 @@ function cohereChatResponseShape() {
8686
}
8787

8888
/**
89-
* Minimal Cohere /v2/chat streaming chunk shape.
89+
* Minimal Cohere /v2/chat streaming event shapes, one per text-stream event type.
9090
*/
91-
function cohereChatStreamChunkShape() {
92-
return extractShape({
93-
id: "chat-abc123",
94-
type: "content-delta",
95-
delta: {
96-
message: {
97-
content: { text: "Hel" },
91+
function cohereChatStreamEventShapes(): SSEEventShape[] {
92+
const events: { type: string; data: object }[] = [
93+
{
94+
type: "message-start",
95+
data: {
96+
id: "chat-abc123",
97+
type: "message-start",
98+
delta: {
99+
message: { role: "assistant", content: [], tool_plan: "", tool_calls: [], citations: [] },
100+
},
98101
},
99102
},
100-
});
103+
{
104+
type: "content-start",
105+
data: {
106+
type: "content-start",
107+
index: 0,
108+
delta: { message: { content: { type: "text" } } },
109+
},
110+
},
111+
{
112+
type: "content-delta",
113+
data: {
114+
type: "content-delta",
115+
index: 0,
116+
delta: { message: { content: { text: "Hel" } } },
117+
},
118+
},
119+
{ type: "content-end", data: { type: "content-end", index: 0 } },
120+
{
121+
type: "message-end",
122+
data: {
123+
type: "message-end",
124+
delta: {
125+
finish_reason: "COMPLETE",
126+
usage: {
127+
billed_units: { input_tokens: 10, output_tokens: 5 },
128+
tokens: { input_tokens: 10, output_tokens: 5 },
129+
},
130+
},
131+
},
132+
},
133+
];
134+
return events.map((e) => ({ type: e.type, dataShape: extractShape(e.data) }));
135+
}
136+
137+
/**
138+
* Parse a Cohere v2 SSE body by the SSE spec (WHATWG event-stream): lines end
139+
* in `\n`, `\r\n` or `\r`; a blank line dispatches the event; `:` lines are
140+
* comments; one space after the field colon is optional; `id`/`retry` and
141+
* unknown fields are ignored; multiple `data` lines join with `\n`; a final
142+
* event without a blank line is still dispatched. A `data: [DONE]` sentinel
143+
* with no event name ends the stream and is dropped.
144+
*
145+
* Still strict on content: each event's data must be a JSON object whose
146+
* `type` equals the event name (an event without `event:` is named `message`
147+
* by the spec, so it fails that check), and nothing may follow `[DONE]`.
148+
*/
149+
function parseCohereSSE(body: string): { type: string; data: Record<string, unknown> }[] {
150+
const events: { type: string; data: Record<string, unknown> }[] = [];
151+
let eventName = "";
152+
let dataLines: string[] = [];
153+
let done = false;
154+
155+
const dispatch = () => {
156+
const name = eventName || "message";
157+
const hadData = dataLines.length > 0;
158+
const raw = dataLines.join("\n");
159+
eventName = "";
160+
dataLines = [];
161+
if (!hadData) return;
162+
if (done) throw new Error(`Cohere SSE event after [DONE]: ${JSON.stringify(raw)}`);
163+
if (name === "message" && raw === "[DONE]") {
164+
done = true;
165+
return;
166+
}
167+
let data: unknown;
168+
try {
169+
data = JSON.parse(raw);
170+
} catch {
171+
throw new Error(`Cohere SSE data is not JSON: ${JSON.stringify(raw)}`);
172+
}
173+
if (data === null || typeof data !== "object" || Array.isArray(data)) {
174+
throw new Error(`Cohere SSE data is not an object: ${JSON.stringify(raw)}`);
175+
}
176+
const record = data as Record<string, unknown>;
177+
if (record.type !== name) {
178+
throw new Error(`Cohere SSE event name ${name} != data.type ${String(record.type)}`);
179+
}
180+
events.push({ type: name, data: record });
181+
};
182+
183+
for (const line of body.split(/\r\n|\r|\n/)) {
184+
if (line === "") {
185+
dispatch();
186+
continue;
187+
}
188+
if (line.startsWith(":")) continue;
189+
const colon = line.indexOf(":");
190+
const field = colon === -1 ? line : line.slice(0, colon);
191+
let value = colon === -1 ? "" : line.slice(colon + 1);
192+
if (value.startsWith(" ")) value = value.slice(1);
193+
if (field === "event") eventName = value;
194+
else if (field === "data") dataLines.push(value);
195+
// id, retry and unknown fields are ignored per the SSE spec.
196+
}
197+
dispatch();
198+
return events;
101199
}
102200

103201
// ---------------------------------------------------------------------------
@@ -382,7 +480,6 @@ describe.skipIf(!HAS_CREDENTIALS)("Cohere drift", () => {
382480
}
383481
const model = resolved.model;
384482

385-
const sdkChunkShape = cohereChatStreamChunkShape();
386483
const messages = [{ role: "user", content: "Say hello" }];
387484

388485
const [realRes, mockRes] = await Promise.all([
@@ -413,60 +510,122 @@ describe.skipIf(!HAS_CREDENTIALS)("Cohere drift", () => {
413510
}
414511

415512
expect(realRes.status).toBe(200);
416-
expect(mockRes.status).toBeLessThan(500);
513+
expect(mockRes.status).toBe(200);
514+
515+
const realEvents = parseCohereSSE(realRes.body);
516+
const mockEvents = parseCohereSSE(mockRes.body);
517+
expect(realEvents.length, "Real API returned no SSE events").toBeGreaterThan(0);
518+
expect(mockEvents.length, "Mock returned no SSE events").toBeGreaterThan(0);
519+
520+
const realEnd = realEvents.at(-1);
521+
if (
522+
realEnd?.type === "message-end" &&
523+
isCohereNoGenerationStreamEnd(
524+
cohereRecord(realEnd.data.delta),
525+
COHERE_SHAPE_LEG_NO_GENERATION,
526+
)
527+
) {
528+
// Upstream generated nothing: a 200 stream whose message-end is
529+
// finish_reason ERROR with empty usage. No success terminal to compare.
530+
expect(
531+
realEvents.some((e) => e.type === "content-start"),
532+
"content before no-generation terminal",
533+
).toBe(false);
534+
ctx.skip(
535+
cohereNoGenerationSkipReason([
536+
{ errorType: "NO_VALID_RESPONSE_GENERATED", id: cohereString(realEvents[0].data.id) },
537+
]),
538+
);
539+
return;
540+
}
417541

418-
if (mockRes.status === 200) {
419-
// Parse SSE chunks from both responses
420-
const realChunks = parseDataOnlySSE(realRes.body);
421-
const mockChunks = parseDataOnlySSE(mockRes.body);
422-
423-
if (realChunks.length > 0 && mockChunks.length > 0) {
424-
// Compare first chunk shape (content-delta)
425-
const realChunkShape = extractShape(realChunks[0]);
426-
const mockChunkShape = extractShape(mockChunks[0]);
427-
428-
const diffs = triangulate(sdkChunkShape, realChunkShape, mockChunkShape);
429-
const report = formatDriftReport(
430-
"Cohere /v2/chat (streaming first chunk)",
431-
diffs,
432-
"cohere-chat",
433-
);
542+
for (const [side, events] of [
543+
["real", realEvents],
544+
["mock", mockEvents],
545+
] as const) {
546+
expect(events[0].type, `${side} stream must open with message-start`).toBe("message-start");
547+
expect(events.at(-1)?.type, `${side} stream must close with message-end`).toBe("message-end");
548+
}
434549

435-
expect(
436-
diffs.filter((d) => d.severity === "critical"),
437-
report,
438-
).toEqual([]);
439-
440-
// Also compare the LAST chunk shape (has finish_reason, usage)
441-
const sdkLastChunkShape = extractShape({
442-
id: "chat-abc123",
443-
type: "message-end",
444-
delta: {
445-
finish_reason: "COMPLETE",
446-
usage: {
447-
billed_units: { input_tokens: 10, output_tokens: 5 },
448-
tokens: { input_tokens: 10, output_tokens: 5 },
449-
},
450-
},
451-
});
550+
const diffs = compareSSESequences(
551+
cohereChatStreamEventShapes(),
552+
realEvents.map((e) => ({ type: e.type, dataShape: extractShape(e.data) })),
553+
mockEvents.map((e) => ({ type: e.type, dataShape: extractShape(e.data) })),
554+
);
555+
const report = formatDriftReport("Cohere /v2/chat (streaming events)", diffs, "cohere-chat");
556+
557+
expect(
558+
diffs.filter((d) => d.severity === "critical"),
559+
report,
560+
).toEqual([]);
561+
});
562+
});
452563

453-
const realLastShape = extractShape(realChunks[realChunks.length - 1]);
454-
const mockLastShape = extractShape(mockChunks[mockChunks.length - 1]);
564+
describe("parseCohereSSE", () => {
565+
it("parses recorded live event: + data: frames and drops the [DONE] sentinel", async () => {
566+
const body = (
567+
await readFile(new URL("./fixtures/cohere-k5-stream.sse", import.meta.url))
568+
).toString();
569+
const events = parseCohereSSE(body);
570+
expect(events.length).toBeGreaterThan(2);
571+
expect(events[0].type).toBe("message-start");
572+
expect(events.at(-1)?.type).toBe("message-end");
573+
for (const e of events) expect(e.data.type).toBe(e.type);
574+
});
455575

456-
const lastDiffs = triangulate(sdkLastChunkShape, realLastShape, mockLastShape);
457-
const lastReport = formatDriftReport(
458-
"Cohere /v2/chat (streaming last chunk)",
459-
lastDiffs,
460-
"cohere-chat",
461-
);
576+
it("parses aimock's stream as a non-empty event list", async () => {
577+
const res = await httpPost(`${instance.url}/v2/chat`, {
578+
model: "command-a-03-2025",
579+
messages: [{ role: "user", content: "Say hello" }],
580+
stream: true,
581+
});
582+
expect(res.status).toBe(200);
583+
const events = parseCohereSSE(res.body);
584+
expect(events.map((e) => e.type)).toEqual([
585+
"message-start",
586+
"content-start",
587+
"content-delta",
588+
"content-end",
589+
"message-end",
590+
]);
591+
});
462592

463-
expect(
464-
lastDiffs.filter((d) => d.severity === "critical"),
465-
lastReport,
466-
).toEqual([]);
467-
}
593+
it("accepts legal SSE variants a server or proxy may send", () => {
594+
const start = '{"type":"message-start","id":"x"}';
595+
const end = '{"type":"message-end","delta":{}}';
596+
const expected = ["message-start", "message-end"];
597+
const variants: Record<string, string> = {
598+
canonical: `event: message-start\ndata: ${start}\n\nevent: message-end\ndata: ${end}\n\ndata: [DONE]\n\n`,
599+
"single trailing newline": `event: message-start\ndata: ${start}\n\nevent: message-end\ndata: ${end}\n`,
600+
"no trailing newline": `event: message-start\ndata: ${start}\n\nevent: message-end\ndata: ${end}`,
601+
"no space after colon": `event:message-start\ndata:${start}\n\nevent:message-end\ndata:${end}\n\n`,
602+
"keepalive comments": `: ping\n\nevent: message-start\n:mid-frame comment\ndata: ${start}\n\n:\n\nevent: message-end\ndata: ${end}\n\n`,
603+
"id and retry fields": `retry: 3000\n\nid: 1\nevent: message-start\ndata: ${start}\n\nid: 2\nevent: message-end\nretry: 10\ndata: ${end}\n\n`,
604+
CRLF: `event: message-start\r\ndata: ${start}\r\n\r\nevent: message-end\r\ndata: ${end}\r\n\r\ndata: [DONE]\r\n\r\n`,
605+
CR: `event: message-start\rdata: ${start}\r\revent: message-end\rdata: ${end}\r\r`,
606+
"multi-line data": `event: message-start\ndata: {"type":\ndata: "message-start"}\n\nevent: message-end\ndata: ${end}\n\n`,
607+
};
608+
for (const [name, body] of Object.entries(variants)) {
609+
expect(
610+
parseCohereSSE(body).map((e) => e.type),
611+
name,
612+
).toEqual(expected);
468613
}
469614
});
615+
616+
it("rejects malformed data, mismatched names and events after [DONE]", () => {
617+
expect(() => parseCohereSSE("event: message-start\ndata: {not json\n\n")).toThrow(/not JSON/);
618+
expect(() => parseCohereSSE("event: content-end\ndata: [1]\n\n")).toThrow(/not an object/);
619+
expect(() => parseCohereSSE("event: content-end\ndata: null\n\n")).toThrow(/not an object/);
620+
expect(() => parseCohereSSE('event: content-end\ndata: {"type":"content-start"}\n\n')).toThrow(
621+
/event name/,
622+
);
623+
// No event: line -> the spec names it "message", which never matches data.type.
624+
expect(() => parseCohereSSE('data: {"type":"message-start"}\n\n')).toThrow(/event name/);
625+
expect(() =>
626+
parseCohereSSE('data: [DONE]\n\nevent: content-end\ndata: {"type":"content-end"}\n\n'),
627+
).toThrow(/after \[DONE\]/);
628+
});
470629
});
471630

472631
// Local SDK and retained capture checks are independent of native credentials.
@@ -954,7 +1113,7 @@ function readCohereK5(
9541113
}
9551114
}
9561115
const delta = cohereRecord(events.at(-1)?.delta);
957-
if (options.live && isCohereNoGenerationStreamEnd(delta)) {
1116+
if (options.live && isCohereNoGenerationStreamEnd(delta, COHERE_K5_NO_GENERATION)) {
9581117
assert.equal(calls.length, 0, "tool before no-generation terminal");
9591118
assert.equal(contentCount, 0, "content before no-generation terminal");
9601119
return {

0 commit comments

Comments
 (0)