Skip to content

Commit e1902c3

Browse files
committed
test: make the Cohere streaming drift leg compare real event frames
The streaming /v2/chat shape leg parsed both bodies with parseDataOnlySSE, which drops every frame that has an `event:` line. Cohere v2 streams are all `event:` + `data:` frames, so both chunk lists were empty and the comparison never ran. Parse the frames with a strict Cohere parser (event name must equal data.type, trailing `data: [DONE]` dropped, any other frame throws), require non-empty streams that open with message-start and close with message-end, and compare every event type with compareSSESequences. A live stream that ends in the no-generation terminal (finish_reason ERROR, empty usage) is a skip that cites the upstream code and id, the same way the 422 envelope already is. isCohereNoGenerationStreamEnd now takes the allowed error types, like cohereNoGenerationError.
1 parent 1ba9750 commit e1902c3

3 files changed

Lines changed: 186 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: 161 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,17 +86,81 @@ 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+
},
101+
},
102+
},
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+
},
98131
},
99132
},
133+
];
134+
return events.map((e) => ({ type: e.type, dataShape: extractShape(e.data) }));
135+
}
136+
137+
/**
138+
* Parse a Cohere v2 SSE body. Every frame is `event: <type>` + `data: <json>`
139+
* whose JSON `type` equals the event name; a final `data: [DONE]` sentinel is
140+
* allowed and dropped. Any other frame throws, so a framing change is loud
141+
* instead of silently parsing to an empty list.
142+
*/
143+
function parseCohereSSE(body: string): { type: string; data: Record<string, unknown> }[] {
144+
const frames = body
145+
.replace(/\r\n/g, "\n")
146+
.split("\n\n")
147+
.filter((frame) => frame.trim() !== "");
148+
if (frames.at(-1) === "data: [DONE]") frames.pop();
149+
return frames.map((frame) => {
150+
const lines = frame.split("\n");
151+
if (lines.length !== 2 || !lines[0].startsWith("event: ") || !lines[1].startsWith("data: ")) {
152+
throw new Error(`Unsupported Cohere SSE frame: ${JSON.stringify(frame)}`);
153+
}
154+
const type = lines[0].slice("event: ".length);
155+
const data: unknown = JSON.parse(lines[1].slice("data: ".length));
156+
if (data === null || typeof data !== "object" || Array.isArray(data)) {
157+
throw new Error(`Cohere SSE data is not an object: ${JSON.stringify(frame)}`);
158+
}
159+
const record = data as Record<string, unknown>;
160+
if (record.type !== type) {
161+
throw new Error(`Cohere SSE event name ${type} != data.type ${String(record.type)}`);
162+
}
163+
return { type, data: record };
100164
});
101165
}
102166

@@ -382,7 +446,6 @@ describe.skipIf(!HAS_CREDENTIALS)("Cohere drift", () => {
382446
}
383447
const model = resolved.model;
384448

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

388451
const [realRes, mockRes] = await Promise.all([
@@ -413,59 +476,92 @@ describe.skipIf(!HAS_CREDENTIALS)("Cohere drift", () => {
413476
}
414477

415478
expect(realRes.status).toBe(200);
416-
expect(mockRes.status).toBeLessThan(500);
479+
expect(mockRes.status).toBe(200);
480+
481+
const realEvents = parseCohereSSE(realRes.body);
482+
const mockEvents = parseCohereSSE(mockRes.body);
483+
expect(realEvents.length, "Real API returned no SSE events").toBeGreaterThan(0);
484+
expect(mockEvents.length, "Mock returned no SSE events").toBeGreaterThan(0);
485+
486+
const realEnd = realEvents.at(-1);
487+
if (
488+
realEnd?.type === "message-end" &&
489+
isCohereNoGenerationStreamEnd(
490+
cohereRecord(realEnd.data.delta),
491+
COHERE_SHAPE_LEG_NO_GENERATION,
492+
)
493+
) {
494+
// Upstream generated nothing: a 200 stream whose message-end is
495+
// finish_reason ERROR with empty usage. No success terminal to compare.
496+
expect(
497+
realEvents.some((e) => e.type === "content-start"),
498+
"content before no-generation terminal",
499+
).toBe(false);
500+
ctx.skip(
501+
cohereNoGenerationSkipReason([
502+
{ errorType: "NO_VALID_RESPONSE_GENERATED", id: cohereString(realEvents[0].data.id) },
503+
]),
504+
);
505+
return;
506+
}
417507

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-
);
508+
for (const [side, events] of [
509+
["real", realEvents],
510+
["mock", mockEvents],
511+
] as const) {
512+
expect(events[0].type, `${side} stream must open with message-start`).toBe("message-start");
513+
expect(events.at(-1)?.type, `${side} stream must close with message-end`).toBe("message-end");
514+
}
434515

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-
});
516+
const diffs = compareSSESequences(
517+
cohereChatStreamEventShapes(),
518+
realEvents.map((e) => ({ type: e.type, dataShape: extractShape(e.data) })),
519+
mockEvents.map((e) => ({ type: e.type, dataShape: extractShape(e.data) })),
520+
);
521+
const report = formatDriftReport("Cohere /v2/chat (streaming events)", diffs, "cohere-chat");
452522

453-
const realLastShape = extractShape(realChunks[realChunks.length - 1]);
454-
const mockLastShape = extractShape(mockChunks[mockChunks.length - 1]);
523+
expect(
524+
diffs.filter((d) => d.severity === "critical"),
525+
report,
526+
).toEqual([]);
527+
});
528+
});
455529

456-
const lastDiffs = triangulate(sdkLastChunkShape, realLastShape, mockLastShape);
457-
const lastReport = formatDriftReport(
458-
"Cohere /v2/chat (streaming last chunk)",
459-
lastDiffs,
460-
"cohere-chat",
461-
);
530+
describe("parseCohereSSE", () => {
531+
it("parses recorded live event: + data: frames and drops the [DONE] sentinel", async () => {
532+
const body = (
533+
await readFile(new URL("./fixtures/cohere-k5-stream.sse", import.meta.url))
534+
).toString();
535+
const events = parseCohereSSE(body);
536+
expect(events.length).toBeGreaterThan(2);
537+
expect(events[0].type).toBe("message-start");
538+
expect(events.at(-1)?.type).toBe("message-end");
539+
for (const e of events) expect(e.data.type).toBe(e.type);
540+
});
462541

463-
expect(
464-
lastDiffs.filter((d) => d.severity === "critical"),
465-
lastReport,
466-
).toEqual([]);
467-
}
468-
}
542+
it("parses aimock's stream as a non-empty event list", async () => {
543+
const res = await httpPost(`${instance.url}/v2/chat`, {
544+
model: "command-a-03-2025",
545+
messages: [{ role: "user", content: "Say hello" }],
546+
stream: true,
547+
});
548+
expect(res.status).toBe(200);
549+
const events = parseCohereSSE(res.body);
550+
expect(events.map((e) => e.type)).toEqual([
551+
"message-start",
552+
"content-start",
553+
"content-delta",
554+
"content-end",
555+
"message-end",
556+
]);
557+
});
558+
559+
it("rejects frames it does not understand instead of dropping them", () => {
560+
expect(() => parseCohereSSE('data: {"type":"message-start"}\n\n')).toThrow(/Unsupported/);
561+
expect(() => parseCohereSSE('event: content-end\ndata: {"type":"content-start"}\n\n')).toThrow(
562+
/event name/,
563+
);
564+
expect(() => parseCohereSSE("event: content-end\ndata: [1]\n\n")).toThrow(/not an object/);
469565
});
470566
});
471567

@@ -954,7 +1050,7 @@ function readCohereK5(
9541050
}
9551051
}
9561052
const delta = cohereRecord(events.at(-1)?.delta);
957-
if (options.live && isCohereNoGenerationStreamEnd(delta)) {
1053+
if (options.live && isCohereNoGenerationStreamEnd(delta, COHERE_K5_NO_GENERATION)) {
9581054
assert.equal(calls.length, 0, "tool before no-generation terminal");
9591055
assert.equal(contentCount, 0, "content before no-generation terminal");
9601056
return {

0 commit comments

Comments
 (0)