mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 05:17:01 +01:00
Found by using the chat. Asked Loki a question on prod; it answered in 10.8s and the reply ended mid-word: - The active Claude sessions reported right now are running on `research- An unclosed backtick, a dangling hyphen, and nothing anywhere saying the answer was incomplete. The stored row is 243 chars and genuinely ends there, so this was severed at generation, not at render. `grep -rn finish_reason src/ home/` returned ZERO. The field rides the same frames this code already parses for `usage` — the one field that separates a finished answer from a severed one — and both readers dropped it: readBufferedBody destructures only `message`, readStreamedBody only `delta` and `usage`. So there was no way for anything to know, and a fragment was stored, billed, and rendered exactly like a complete reply. This is not new. `frontier/propose.ts` carries a comment about an answer "cut in half. Observed in prod at maxTokens 3000", worked around by raising a number rather than by noticing the condition. And sse-stream.ts opens by warning that "a stream that drops frames does not fail — it silently truncates an answer", then never reads the vendor's own statement about it. What this does NOT do is guess. It reads the reason, classifies it, and says so. `cutOff` is carried on the turn but nothing renders it yet: what a severed answer should LOOK like is a product decision, and the grounding `Violation` channel that would be its natural home is owned by @bitbaum/ai-kit, so widening that is a change to make there, deliberately. Three rules worth keeping, each pinned: - ORDERING. The frame carrying `finish_reason` routinely carries an empty delta, so the stop reason must be read BEFORE the `if (!delta) return` guard. Read after it, the field is dropped and the answer looks whole forever — the original bug, reintroduced. - SILENCE IS A THIRD STATE. A vendor that omits the field has told us nothing. Reporting that as a problem would fire on every quiet provider, and a warning that always fires is one nobody reads. - AN UNKNOWN REASON IS SUSPICIOUS, NOT FINE. Vendors add stop reasons; a new one meaning "cut off" must not read as healthy merely because the switch predates it. Unrecognised values are surfaced verbatim, named. Measured before writing any of it: 1 of 183 stored assistant replies is truncated — this one. Rare, which is exactly why it needs a machine to notice rather than a reader. (My first detector claimed 28; it was wrong — 11 of 12 samples simply ended with a URL. The honest count came from reading them.) Proved by MUTATION, both ways: moving the read below the delta guard fails 2 of 9 cases; defaulting an unknown reason to "fine" fails 1. verify: format:check, tsc, lint (0 errors, 2 pre-existing warnings), check:design (10), check:desktop, test:home 140/140. test:unit 203/205 — activity-time-zone-stable and telegram-allowlist fail with "probe failed:" and an empty reason; both need a live server and this diff touches neither them nor anything they import. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
145 lines
5.6 KiB
TypeScript
145 lines
5.6 KiB
TypeScript
/**
|
|
* Does Loki notice when a vendor severed the answer?
|
|
*
|
|
* Until this landed, nothing in the repo read `finish_reason` — a grep for it
|
|
* across src/ and home/ returned zero. The field rides the same frames already
|
|
* parsed for `usage`, and was dropped, so a severed reply was stored and
|
|
* rendered exactly like a finished one.
|
|
*
|
|
* Observed in prod on 2026-09-18: a chat answer that ended mid-word at
|
|
* "running on `research-", unclosed backtick and all, stored at 243 chars with
|
|
* no marker anywhere. One in 183 stored replies — rare, which is precisely why
|
|
* it needs a machine to notice rather than a reader.
|
|
*
|
|
* Run: npx tsx scripts/test/cut-off-answer.ts
|
|
*/
|
|
import { cutOffReason, readStreamedBody } from "@/lib/agent/llm";
|
|
|
|
let failures = 0;
|
|
function fail(name: string, err: unknown) {
|
|
failures++;
|
|
console.log(` ✗ ${name}`);
|
|
console.log(` ${err instanceof Error ? err.message : String(err)}`);
|
|
}
|
|
function check(name: string, fn: () => void) {
|
|
try {
|
|
fn();
|
|
console.log(` ✓ ${name}`);
|
|
} catch (err) {
|
|
fail(name, err);
|
|
}
|
|
}
|
|
async function acheck(name: string, fn: () => Promise<void>) {
|
|
try {
|
|
await fn();
|
|
console.log(` ✓ ${name}`);
|
|
} catch (err) {
|
|
fail(name, err);
|
|
}
|
|
}
|
|
function assert(cond: boolean, msg: string) {
|
|
if (!cond) throw new Error(msg);
|
|
}
|
|
|
|
/** An SSE body of the shape every vendor in the chain emits. */
|
|
function sseBody(frames: object[]): Response {
|
|
const text = frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n";
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
controller.enqueue(new TextEncoder().encode(text));
|
|
controller.close();
|
|
},
|
|
});
|
|
return new Response(stream);
|
|
}
|
|
const SINK = { delta: () => {}, reset: () => {} };
|
|
|
|
async function main() {
|
|
console.log("cut-off-answer:");
|
|
|
|
check("a finished answer is not reported as a problem", () => {
|
|
assert(cutOffReason("stop") === null, "stop is whole");
|
|
assert(cutOffReason("end_turn") === null, "end_turn is whole");
|
|
});
|
|
|
|
check("stopping to call a tool is not being cut off", () => {
|
|
// The loop's normal path. Reporting this would fire on almost every turn.
|
|
assert(cutOffReason("tool_calls") === null, "tool_calls is whole");
|
|
assert(cutOffReason("function_call") === null, "function_call is whole");
|
|
});
|
|
|
|
check("silence is a third state, not an accusation", () => {
|
|
// A vendor that omits the field has told us NOTHING. Warning here would cry
|
|
// wolf on every provider that stays quiet, and a warning that always fires
|
|
// is one nobody reads.
|
|
assert(cutOffReason(null) === null, "null is unknown");
|
|
assert(cutOffReason(undefined) === null, "undefined is unknown");
|
|
assert(cutOffReason("") === null, "empty is unknown");
|
|
});
|
|
|
|
check("running out of budget is reported", () => {
|
|
assert(cutOffReason("length") === "ran out of output budget", "length");
|
|
assert(cutOffReason("max_tokens") === "ran out of output budget", "max_tokens");
|
|
// Gemini SCREAMS its reasons; the chain's free vendor must not slip through.
|
|
assert(cutOffReason("MAX_TOKENS") === "ran out of output budget", "MAX_TOKENS");
|
|
});
|
|
|
|
check("a provider filter is reported as a filter, not as truncation", () => {
|
|
// Different cause, different remedy: more budget will not help here.
|
|
assert(/filter/.test(cutOffReason("content_filter") ?? ""), "content_filter");
|
|
assert(/filter/.test(cutOffReason("RECITATION") ?? ""), "gemini RECITATION");
|
|
});
|
|
|
|
check("an unrecognised reason is surfaced verbatim, never swallowed", () => {
|
|
// THE RULE THAT KEEPS THIS HONEST. Vendors add stop reasons. A new one
|
|
// meaning "cut off" must not read as "fine" merely because this switch
|
|
// predates it — the default has to be suspicion, and it has to name the
|
|
// string so the next person can classify it.
|
|
const r = cutOffReason("model_fell_over");
|
|
assert(r !== null, "unknown reason must not pass as whole");
|
|
assert(r!.includes("model_fell_over"), `must name the reason, got: ${r}`);
|
|
});
|
|
|
|
await acheck("the stop reason survives the frame that carries no delta", async () => {
|
|
// THE ORDERING BUG, pinned. Vendors send the stop reason on a FINAL frame
|
|
// whose delta is empty or absent. Reading it after the `if (!delta) return`
|
|
// guard drops it on the floor, and the answer then looks complete forever.
|
|
const raw = await readStreamedBody(
|
|
sseBody([
|
|
{ choices: [{ delta: { content: "the agent is running on `research-" } }] },
|
|
{ choices: [{ finish_reason: "length" }] },
|
|
{ usage: { total_tokens: 61 } },
|
|
]),
|
|
SINK,
|
|
);
|
|
assert(raw.text.includes("research-"), "prose accumulated");
|
|
assert(raw.finishReason === "length", `expected length, got ${String(raw.finishReason)}`);
|
|
assert(cutOffReason(raw.finishReason) !== null, "and it reads as cut off");
|
|
});
|
|
|
|
await acheck("a clean stream reports whole, so this cannot fire every turn", async () => {
|
|
const raw = await readStreamedBody(
|
|
sseBody([
|
|
{ choices: [{ delta: { content: "all done." } }] },
|
|
{ choices: [{ finish_reason: "stop" }] },
|
|
]),
|
|
SINK,
|
|
);
|
|
assert(raw.finishReason === "stop", "stop captured");
|
|
assert(cutOffReason(raw.finishReason) === null, "and reads as whole");
|
|
});
|
|
|
|
await acheck("a vendor that never sends one leaves it unknown", async () => {
|
|
const raw = await readStreamedBody(
|
|
sseBody([{ choices: [{ delta: { content: "hi" } }] }]),
|
|
SINK,
|
|
);
|
|
assert(raw.finishReason === null, "absent stays null");
|
|
});
|
|
|
|
console.log(failures === 0 ? "\nall passed" : `\n${failures} failed`);
|
|
process.exit(failures === 0 ? 0 : 1);
|
|
}
|
|
|
|
void main();
|