Read an answer that arrives with an SSE terminator glued to it
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

A gateway may answer a request that did not ask for streaming with SSE framing
anyway: the whole chat.completion object followed by "\ndata: [DONE]". That body
is not JSON, so readJson's strict parse rejected it, `data` came back null, and
the job failed with "unexpected response shape: Cannot read properties of null
(reading 'choices')" — while the answer it wanted sat in the first few kilobytes.

Not hypothetical: the OpenAI-compatible router behind this fork's own instance
answers exactly that way, which made every coach job fail against it with a
message that says nothing about the real problem.

The lenient read takes the first complete JSON value and ignores what follows,
counting braces outside of strings so a "}" inside a rationale cannot end the
scan early. It cannot paper over a truncated answer — an object that never closes
still returns null, which is what the token-limit path depends on — and there are
three tests for that: the terminator case, trailing junk after a complete object,
and an object that never closes.
This commit is contained in:
dsantillan committed 2026-09-21 15:05:03 -04:00
1 parent 1c201ab6f9
commit ea1af681c2
2 files changed
+70 -1

No files matched your search

+40 -1
View File
@@ -53,9 +53,48 @@ async function call(fetchImpl, url, init, timeoutMs, signal) {
}
}
/**
* The first complete JSON object or array in `text`, or null if it never closes.
*
* Braces are counted outside of strings only, so a `}` inside a rationale cannot end the scan
* early — and an answer cut off by the token limit returns null, which is the honest reading: a
* half-written object is not a response.
*/
function firstJsonValue(text) {
const start = text.search(/[[{]/);
if (start === -1) return null;
const open = text[start], close = open === '{' ? '}' : ']';
let depth = 0, inString = false, escaped = false;
for (let i = start; i < text.length; i++) {
const c = text[i];
if (inString) {
if (escaped) escaped = false;
else if (c === '\\') escaped = true;
else if (c === '"') inString = false;
continue;
}
if (c === '"') inString = true;
else if (c === open) depth++;
else if (c === close && --depth === 0) return text.slice(start, i + 1);
}
return null;
}
async function readJson(res) {
const text = await res.text();
try { return { data: JSON.parse(text), text }; } catch { return { data: null, text }; }
try { return { data: JSON.parse(text), text }; } catch { /* lenient read below */ }
// Some gateways answer a request that did not ask for streaming with SSE framing anyway: the
// whole `chat.completion` object followed by the streaming terminator, `data: [DONE]`. That
// body is not JSON, so the strict parse above rejects it and the job dies with "unexpected
// response shape" (a null body) while the answer it wanted is in the first few kilobytes.
// Taking the first complete JSON value covers that and any other trailing bytes, without
// needing to know which gateway appended what — and it cannot paper over a truncated answer,
// whose object never closes.
const head = firstJsonValue(text);
if (head) {
try { return { data: JSON.parse(head), text }; } catch { /* not JSON after all */ }
}
return { data: null, text };
}
export function httpAdapter(spec) {
+30
View File
@@ -107,6 +107,36 @@ test('compatible: the configured base URL, max_tokens, and no Authorization head
assert.equal(g.calls[0].headers.authorization, 'Bearer compat-1');
});
// A gateway that answers a request which did NOT ask for streaming with the streaming terminator
// glued to the end: the whole completion object, then "\ndata: [DONE]". That body is not JSON, so
// the strict parse rejects it and the job died with "unexpected response shape" — a null body —
// while the answer it wanted sat in the first few kilobytes. This is not hypothetical: the router
// behind gym.dploy.lol answers exactly this way.
test('compatible: a body with an SSE [DONE] terminator appended is still the answer', async () => {
const body = JSON.stringify({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] }) + '\ndata: [DONE]\n\n';
const f = fakeFetch([{ status: 200, body }]);
const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env, model: 'llama3', fetch: f });
assert.equal(r.code, 0);
assert.equal(r.text, ANSWER);
});
// The lenient read must not paper over a half-written answer: an object that never closes is a
// failure, which is what the token-limit path depends on.
test('compatible: a body whose object never closes is still a failure', async () => {
const f = fakeFetch([{ status: 200, body: '{"choices":[{"message":{"content":"{\\"coach' }]);
const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env, model: 'llama3', fetch: f });
assert.equal(r.code, 1);
assert.match(r.stderr, /unexpected response shape/);
});
// …and an earlier, complete value followed by a broken one is read from the first value only.
test('compatible: trailing junk after a complete object is ignored, not parsed', async () => {
const f = fakeFetch([{ status: 200, body: JSON.stringify({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] }) + '{"broken":' }]);
const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env, model: 'llama3', fetch: f });
assert.equal(r.code, 0);
assert.equal(r.text, ANSWER);
});
test('compatible: no endpoint configured, or no model chosen, is a clean failure rather than a request', async () => {
const f = fakeFetch([]);
const none = await compatible.invoke({ cfg: {}, prompt: 'P', env: {}, model: 'x', fetch: f });