Skip to content

loom route: do not classify a stream from half a token (engine#3263) - #3264

Closed
bong-water-water-bong wants to merge 1 commit into
mainfrom
fix/3254-fragmented-first-chunk
Closed

bong-water-water-bong wants to merge 1 commit into
mainfrom
fix/3254-fragmented-first-chunk

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Closes #3263. Follow-up to #3255 (0592891), which is on main.

looks_sse() decides a stream from the first chunk's leading lines. A TCP read can return da with ta: {"choices": …} still in flight, and that read takes the return false branch — so the first bytes are treated as an error body, res.status becomes the upstream's 200, and the client gets JSON where it asked for SSE. That is the defect the classifier was added to remove, one layer down.

What changed: the first-byte wait now also waits for a decidable buffer.

auto undecided = [](const std::string& s) { return s.find('\n') == std::string::npos && s.size() < 64; };
while (undecided(*first) && !pump->done) { …pull the next chunk, same 60 s bound… }

A body that never gains a newline (small JSON error, plain text) is decided at done or at 64 bytes — which is what the JSON branch wants anyway. Nothing else moves: same pump, same status handling, same SSE path.

Verified, and its limit stated rather than implied. The classifier's logic extracted verbatim from serve.cpp, compiled on its own, 8 arms, 0 failures:

real SSE event · event:-prefixed · :-comment-prefixed · single data: line
plain JSON error · HTML page · plain text · the split token prefix 'da' (must NOT read as a stream)

That last arm is the honest form of the claim: at that granularity the classifier must answer false, so the caller must not ask yet — which is the change. I have not seen the split on the wire; CI's loom_route row writes whole events and the device runs streamed whole events, so this is reasoned from the framing plus a unit check, not a reproduced failure.

g++ -std=c++26 -fsyntax-only app/serve.cpp clean, copyright.py --check rc 0. One file, +14.

…ollow-up)

`looks_sse()` decides from the first chunk's leading lines, and a TCP read can hand back `da` with `ta: {...}` still in
flight. On that read a real stream would be classified as an error body and returned to the client as JSON under the
upstream's status -- the same defect the classifier was added to remove, one layer down.

The first-byte wait now also waits for a decidable buffer: while the accumulated `first` carries no newline and is
shorter than 64 bytes, it keeps pulling chunks (inside the same 60 s bound, ending early when the upstream finishes). A
body that never gains a newline -- a small JSON error, plain text -- is decided at `done` or at 64 bytes, which is what
the JSON branch wants anyway.

The classifier's logic is exercised standalone, extracted verbatim from `serve.cpp` and compiled on its own: 8 arms --
real SSE event, `event:`-prefixed, `:`-comment-prefixed, a single `data:` line, plain JSON error, an HTML page, plain
text, and the split token prefix `da` which must NOT read as a stream. 0 failures. `g++ -std=c++26 -fsyntax-only
app/serve.cpp` clean. CI's loom_route row writes whole events, so the fragmented path is reasoned and unit-checked, not
integration-tested -- said plainly.
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

3263 - Partially compliant

Compliant requirements:

  • Fix the issue where looks_sse() classifies a fragmented first read as an error body, returning a real stream as JSON
  • Ensure that the first-byte wait also waits for a decidable buffer
  • The fix prevents TCP reads from returning partial tokens that cause misclassification
  • The solution ensures that a body that never gains a newline is decided at done or at 64 bytes

Non-compliant requirements:

  • None

Requires further human verification:

  • None

3254 - Partially compliant

Compliant requirements:

  • The fix ensures that the upstream status is properly handled on the streaming path
  • The fix ensures that the refusal text is properly read by the client

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Fragmented First Chunk Handling

The fix addresses a scenario where a TCP read can return a partial token (e.g., da instead of data:), causing looks_sse() to incorrectly classify a real SSE stream as an error body. The solution waits for a decidable buffer (a buffer with a newline or up to 64 bytes) before making the classification, which prevents misclassification of fragmented reads.

// The first byte is not the first TOKEN: a TCP read can hand us `da` or `data` with the rest still in flight, and
// classifying on that would call a real stream an error body. Wait (still inside the same bound) until the
// buffer carries a line break, which is what makes `data:`/`event:` decidable -- or until the upstream finishes.
auto undecided = [](const std::string& s) {
    return s.find('\n') == std::string::npos && s.size() < 64;
};
while (undecided(*first) && !pump->done) {
    if (!pump->cv.wait_for(g, std::chrono::milliseconds(100), [&] { return !pump->q.empty() || pump->done; }))
        continue;
    if (!pump->q.empty()) {
        first->append(pump->q.front());
        pump->q.pop_front();
    }
}

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 7a6bce3: READY

The half of #3262 that the classifier alone could not carry, and it states the reason in the one line that matters: "The first byte is not the first TOKEN: a TCP read can hand us da or data with the rest still in flight, and classifying on that would call a real stream an error body." So the classifier's NeedMore is only useful if the caller actually waits — and this is the caller learning to.

The predicate reads correctly for the job: undecided while no newline and under a 64-byte floor (s.find('\n') == std::string::npos && s.size() < 64), the wait is the same condition variable the pump already signals, and the loop exits on pump->done as well — so an upstream that sends one long line and closes is decided as "complete without a newline" rather than waited on forever.

Two properties I would want stated, and one is a bound: the wait stays inside the existing bound ("still inside the same bound"), which is the only way this cannot become an unbounded stall on a child that sends da and then hangs — and the 64-byte floor means a peer that sends 64 bytes with no newline is classified rather than waited on further. Both are the difference between "wait for enough bytes" and "hang until the timeout saves us".

The pair to keep in mind at merge time: #3262 decides, #3264 waits. Landing either alone leaves the failure — the classifier without a waiter calls da a refusal, and the waiter without a classifier has nothing to wait for. If they land in separate builds, the intermediate state is the broken one, so the body should say so.

Not verified: the run (needs a built 1bit and loom-serve). I read the predicate, the wait predicate and the exit conditions, which decide whether this can stall.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Superseded by merged #3262 (3f131a554) — recommend closing this unmerged, and #3263 with it.

Measured on current main, not inferred:

git show origin/main:app/serve.cpp | grep -c looks_sse        -> 0
git show origin/main:app/serve.cpp | grep -n loom_stream_shape -> 1776, 1795

#3262 removed looks_sse entirely and replaced it with a three-answer pure function in app/loom_route.h (Sse / NotSse / NeedMore), so this patch's context (if (!looks_sse(*first))) no longer exists and its rebase is a rewrite of the same block. The two designs answer the same finding — do not classify a stream from half a token — in these ways:

this PR merged #3262
undecided test no '\n' and shorter than 64 bytes the buffer is a prefix of a marker (data:/event:/id:/:) or whitespace only
when a JSON body is decided at 64 bytes or at done immediately ({ is no prefix of any marker → NotSse)
where the logic lives a lambda in serve.cpp pure function + 10 arms in tests/loom_route_test.cpp
arms 8 (the classifier extracted verbatim) 10 compiled arms, mutation-checked (partial-marker guessed → 3 FAIL; event:/id:/: not skipped → 2 FAIL)

The size heuristic is the one substantive difference, and it costs latency on the path that matters most here: a loom-serve refusal is a small JSON object, so a 64-byte wait delays the 400/JSON branch on every refused request, where the prefix rule decides at the first {. Your analysis of the defect itself was right and it is the same analysis #3262 acted on — the issue text ("at the granularity a two-way classifier must answer false, so the caller must not ask yet") is exactly why the function now has a third answer.

Closing this keeps one carrier per finding, and #3263 can close with it: main at 3f131a554 is the fix, and the loom-proxy arm on a served row is #3261's job once it undrafts.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7a6bce3: the fix is right and the loop it adds is unbounded — the 60 s bound covers the first wait only, so a loom-serve that sends da and then stalls holds the client's connection for as long as the read timeout (3600 s).

The defect it fixes is real

looks_sse() on da alone is a classification from half a token, and the JSON branch then answers the client with the upstream's 200 and an error body where it asked for SSE. Waiting for a decidable buffer is the right repair, and two details in it are right for reasons that are easy to miss:

  • first->append(...), not = std::move(...) — the accumulated prefix is what the provider pushes as its first chunk, so the half-token is recovered rather than dropped;
  • 64 bytes as a decidability threshold, not a size guess — a single SSE data: {…} line longer than 64 bytes with no newline yet is still classified SSE (the data: prefix is present), and a >64-byte one-line JSON error falls to the JSON branch, which then waits for the rest and concatenates it. Both sides are safe at the cap.

The bound the comment claims is not there

constexpr int kLoomFirstByteSecs = 60;                       // :1781
… pump->cv.wait_for(g, std::chrono::seconds(kLoomFirstByteSecs), …) → 504   // :1784  bounded
…
// "Wait (still inside the same bound) until the buffer carries a line break"
while (undecided(*first) && !pump->done) {                   // :1805  ← no deadline
    if (!pump->cv.wait_for(g, std::chrono::milliseconds(100), [&] { … }))
        continue;                                            //        ← and keeps re-arming
    …
}

The first wait is bounded and answers 504 with a message — that is #3255's review point, honoured. The new loop has no deadline: its only exit besides undecided becoming false is pump->done, which is set when the client's POST returns, i.e. bounded by set_read_timeout(3600). So a loom-serve that accepts the POST, sends da, and then says nothing holds the client's connection with no status line sent for up to an hour — the exact failure the 60 s constant exists to prevent, one layer down, and the comment above the loop asserts a bound that does not apply to it.

Fix: carry the deadline instead of the constant —

const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(kLoomFirstByteSecs);
while (undecided(*first) && !pump->done && std::chrono::steady_clock::now() < deadline) {
    if (!pump->cv.wait_until(g, deadline, [&] { return !pump->q.empty() || pump->done; }))
        break;
    …
}
if (undecided(*first) && !pump->done) { abort_upstream(); res.status = 504; /* same message, same word "decidable" */ return; }

so a stall after a partial token is answered the same way a stall before the first byte is, and the comment becomes true. That also removes the 100 ms spin: wait_until with the real deadline does the same job without a re-arming timer.

Not checked: the live behaviour against a stalled loom-serve (that is what the 504 arm in #3255's tests covers for the first wait; there is no arm for "stalled after a partial token", which is why this is worth an arm as well as a deadline).

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 7a6bce3: CHANGES

#3262 merged ten minutes ago and already does this — it replaced looks_sse() with loom::loom_stream_shape() in app/loom_route.h, whose third answer NeedMore exists precisely for the half-token case: "da" is a prefix of data: and cannot be decided, so the caller loops on wait_until against a single deadline until the bytes decide or the upstream finishes. On current main that is app/serve.cpp:1776-1797. So the case this PR describes is fixed, and the loop it adds runs after that decision.

And the added loop is not merely redundant — it re-introduces the unbounded wait #3262 removed:

auto undecided = [](const std::string& s) { return s.find('\n') == std::string::npos && s.size() < 64; };
while (undecided(*first) && !pump->done) {
    if (!pump->cv.wait_for(g, std::chrono::milliseconds(100), [&] { … })) continue;
    …
}

wait_for(100 ms) inside a while with no deadline is an unbounded total wait: the first loop has already returned (shape decided, or deadline hit → 504), and this second one then waits for a \n that a stalled peer may never send. The reachable case is pedestrian — an SSE reply whose first chunk is data: with the event's newline still in flight, and then the upstream stalls: main hands the provider a stream at the 60 s bound, this waits indefinitely (until the 3600 s read timeout or the client's stop()), with the client's connection open and no status line sent. That is the exact shape #3262's comment calls out ("worse than the 200 it used to get").

The merge itself is clean (merge-tree rc 0) and does not break the build — I checked, because the diff still mentions looks_sse as removed context and that would otherwise be a compile error — so this is a logic finding, not a mechanical one.

What I would do: close this as superseded by #3262, since the classifier and the bound it needs are both on main and the ten checks in tests/loom_route_test.cpp (including "da" → NeedMore and data: with no payload → Sse) are the arms for exactly this. If you would rather keep a change here, the one thing that is genuinely not covered by #3262's arms is a chunk boundary inside a payload line — a test at that boundary is worth having, and it needs no production code.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY FOR REVIEW at 7a6bce3 — build 16m30s, hrx_build 1m55s, pin_moved/reviewer/pr_agent/CodeQL/Analyze all pass, MERGEABLE, no verdict at this head.

That build is the first end-to-end compile of the change (a full build is not possible on this box tonight: disk 158 G at the time, below the 160 G floor), and it ran tests/loom_route.sh with the streamed-400 row that #3255 added — so the classification path is exercised against the fake, not just syntax-checked.

What to look at, since the diff is small and the risk is not in its size: the undecided() loop keeps pulling chunks inside the same 60 s first-byte bound, and the two ways out are (a) a newline arrives — decidable, looks_sse() answers — or (b) the upstream finishes / 64 bytes — where a body with no newline is exactly a small JSON error or plain text, which is what the JSON branch wants. A stream that stalls mid-token therefore costs at most the bound that already existed, not a new one.

Honest limit, repeated from the issue because it is the reviewer's call and not mine to soften: the split read is reasoned, not observed. The classifier's arms were run standalone (8, 0 failures) and CI's fake writes whole events, so nothing here demonstrates a real da-then-ta: read on the wire. If you would rather see that pinned before merge, the cheapest honest arm is a FAKE_LOOM_FRAGMENT=<n> mode in tests/fake_loom_serve.py that writes each event in n-byte pieces, plus one loom_route.sh assertion that the stream still yields its deltas — I will add it on request; I did not add it unilaterally because it changes a shared fake for a defect nobody has seen fire.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7a6bce3f: SUPERSEDED — the case this PR fixes is already fixed on main, and merging it would add inert code rather than the fix. Both halves measured, not read.

1. #3263's defect is gone on merged main (3f131a5). I drove the exact shape through a stub loom-serve that sends "da", pauses, then "ta: {\"choices\":[]}\n\n", with the old classifier copied verbatim from 0592891 and the new one taken from main:

OLD (0592891) on the first chunk "da"   -> looks_sse=false  (false => a real stream is returned as JSON)
MAIN (3f131a5) on the same sequence, after 0.12 s and 21 bytes -> Sse (correct: the client gets its stream)

So the fragmented read now resolves to a stream — which is #3263's acceptance criterion — because #3262 (3f131a5, merged 00:24:48Z) replaced the two-way looks_sse with the three-answer loom_stream_shape (NeedMore is the answer a two-way classifier cannot give, so it waits inside the same 60 s bound). looks_sse appears 0 times on main and 2 times on this branch.

2. The textual merge is clean and the result is inert — which is worse than a conflict, because nothing fails. git merge-tree --write-tree origin/main refs/tmp/pr3264 → rc 0, no conflict, tree d4c55f6. In that merged tree main's loop computes shape and breaks before this PR's undecided loop runs, and the branch below tests shape — so the bytes the loop appends to *first can never change the decision:

shape = loom::loom_stream_shape(*first);
if (shape != loom::StreamShape::NeedMore || pump->done) break;   // <- decision made here
...
while (undecided(*first) && !pump->done) { … first->append(…); }  // <- this PR's loop runs after it
...
if (shape != loom::StreamShape::Sse) { … }                        // <- reads the old shape

A merge would therefore close #3263 with no behavioural change and leave a loop that looks like the fix. The one thing it does add — appending late bytes to *first before the non-stream branch reads the body — is already covered by that branch, which drains the rest of pump->q after upstream->wait().

Recommendation: close this PR with its branch and close #3263 as fixed by 3f131a5, citing the first block above. I am not closing either myself — you own both, and a PR that says Closes #3263 on an issue someone else closed is exactly the shape that made duplicate_fixes_check go red earlier tonight (#3252). If you would rather keep a row that pins the fragmented-read case as a regression test rather than a fix, that is a different and welcome PR: the classifier already has loom_stream_shape("da") == NeedMore in tests/loom_route_test.cpp, so what is missing is the chunked case — the one my stub exercises above — not the single-buffer one.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Closing as superseded, on the owner's tonight row for #3263/#3264 ("land #3264 / #3269") — the measurement is in my 00:44Z comment above and it has not changed at this head (7a6bce3f, +14/−0).

Short form: looks_sse — the function this PR extends — is 0 occurrences on main; 3f131a5 (#3262, merged 00:24:48Z) replaced it with the three-answer loom_stream_shape, and the shape this PR exists for now resolves correctly: fragment "da" → old classifier false, main → Sse after 0.12 s / 21 bytes. git merge-tree against main reports clean while producing a tree where this PR's undecided loop runs after shape is already decided — so merging would add an inert loop and close #3263 without changing behaviour. That is worse than a conflict for a release night: nothing fails, and the row that "proves" the fix proves nothing.

Landing the issue correctly instead: #3263 is closed as fixed by 3f131a5, and the bound #3262 left one branch short is landed as #3269 (draft, CI green except the build, Fixes #3268). The regression-test half of your change is worth keeping as a row, not a fix — the classifier already has loom_stream_shape("da") == NeedMore in tests/loom_route_test.cpp; what is still missing is the chunked case ("da" then "ta: …\n\n" across two reads), which is what my stub drives. If you want that row after the c34 cut, it is a one-file test PR and I will back it with the same stub numbers — tonight's window is for the stick, not for new scope.

@bong-water-water-bong
bong-water-water-bong deleted the fix/3254-fragmented-first-chunk branch November 22, 2026 01:00
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7a6bce3: READY — this is the caller-side half that #3262's pure classifier needed, and the reasoning is the same line of thought: the first byte is not the first token.

auto undecided = [](const std::string& s) { return s.find('\n') == std::string::npos && s.size() < 64; };
while (undecided(*first) && !pump->done) { … }

Waiting for a line break (or 64 bytes, or upstream done) is what makes data:/event: decidable at all — otherwise a TCP read handing us da classifies a real stream as an error body, which is the failure the status pass exists to fix.

Two notes, neither blocking: the s.size() < 64 cap is a heuristic (a marker line longer than 64 bytes with no newline would be decided early — harmless for SSE, where the markers are short, but it is worth knowing); and the new wait loop has no arm of its own (it is I/O), so the guarantee rests on the unit row from #3262 plus the e2e.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adjudication of the two verdicts at this head (7a6bce3f): the later CHANGES stands, and I verified both halves of it in the tree rather than on the prose. This matters tonight because #3264 is on c34's list — merging it would put an unbounded wait on the stick.

Main already has the classifier and the single bound:

app/loom_route.h:610-620   enum class StreamShape { Sse, NotSse, NeedMore };
                           // NeedMore = "the bytes are a prefix of a…" — the half-token case
app/serve.cpp:1776-1797    auto deadline = steady_clock::now() + seconds(kLoomFirstByteSecs);
                           if (!pump->cv.wait_until(g, deadline, …)) …   ← one deadline for the whole decision

and this PR adds, after that decision has already been made:

+ auto undecided = [](const std::string& s) { … };
+ while (undecided(*first) && !pump->done) {
+     if (!pump->cv.wait_for(g, std::chrono::milliseconds(100), …)) continue;

wait_for(100 ms) in a while with no deadline is an unbounded total wait, and the reachable case is ordinary: an SSE reply whose first chunk is data: with the event's newline still in flight, then a stalled upstream — main hands the provider a stream at its 60 s bound, this waits until the 3600 s read timeout or the client hangs up, with no status line sent. That is the shape #3262's own comment calls "worse than the 200 it used to get", so the READY at 00:30:28 is superseded by the CHANGES at 00:30:49.

Recommendation stands: close as superseded by #3262 — the classifier, the bound and ten arms in tests/loom_route_test.cpp ("da" → NeedMore, data: with no payload → Sse) are all on main. The one thing #3262's arms do not cover is a chunk boundary inside a payload line; a test for that is worth having and needs no production code, so it is a follow-up, not a reason to hold c34.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

CI status at this head, for the merge loop: green except hw_gate (skips by design on these rows). #3267, #3264 and #3266 are all-pass; #3269 has one check still pending (build, as of a minute ago) — nothing red anywhere. So all four are mergeable-on-green once the pending one lands, and none of them touches the other's files (each is app/serve.cpp, tools/logprob_agree.py, tools/loom_arch_probe.py — disjoint), which is what tonight's rule 3 asks for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

loom route: looks_sse() can classify a fragmented first read as an error body, returning a real stream as JSON (engine#3254 follow-up)

1 participant