Skip to content

Commit 32bd1cb

Browse files
committed
test: parse Cohere drift streams by the SSE spec
parseCohereSSE threw on legal SSE a server or proxy can send: a single trailing newline, no space after the field colon, `:` keepalive comments, and id/retry fields. That would raise a false drift alert. Parse line by line per the WHATWG event-stream rules: any line ending, blank line dispatches, comments and id/retry/unknown fields ignored, optional space after the colon, multi-line data joined, final event dispatched without a trailing blank line. Malformed data JSON, a non-object payload, an event/type mismatch and events after [DONE] still throw.
1 parent e1902c3 commit 32bd1cb

1 file changed

Lines changed: 86 additions & 23 deletions

File tree

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

Lines changed: 86 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -135,33 +135,67 @@ function cohereChatStreamEventShapes(): SSEEventShape[] {
135135
}
136136

137137
/**
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.
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]`.
142148
*/
143149
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)}`);
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)}`);
153172
}
154-
const type = lines[0].slice("event: ".length);
155-
const data: unknown = JSON.parse(lines[1].slice("data: ".length));
156173
if (data === null || typeof data !== "object" || Array.isArray(data)) {
157-
throw new Error(`Cohere SSE data is not an object: ${JSON.stringify(frame)}`);
174+
throw new Error(`Cohere SSE data is not an object: ${JSON.stringify(raw)}`);
158175
}
159176
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)}`);
177+
if (record.type !== name) {
178+
throw new Error(`Cohere SSE event name ${name} != data.type ${String(record.type)}`);
162179
}
163-
return { type, data: record };
164-
});
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;
165199
}
166200

167201
// ---------------------------------------------------------------------------
@@ -556,12 +590,41 @@ describe("parseCohereSSE", () => {
556590
]);
557591
});
558592

559-
it("rejects frames it does not understand instead of dropping them", () => {
560-
expect(() => parseCohereSSE('data: {"type":"message-start"}\n\n')).toThrow(/Unsupported/);
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);
613+
}
614+
});
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/);
561620
expect(() => parseCohereSSE('event: content-end\ndata: {"type":"content-start"}\n\n')).toThrow(
562621
/event name/,
563622
);
564-
expect(() => parseCohereSSE("event: content-end\ndata: [1]\n\n")).toThrow(/not an object/);
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\]/);
565628
});
566629
});
567630

0 commit comments

Comments
 (0)