Repository navigation
serve: keep saturated guard marks short and stable - #983
Conversation
There was a problem hiding this comment.
Verdict: MUST_FIX: malformed numeric framing still reaches handlers and permits another request.
Must fix
1. Preserve invalid whitespace until framing validation rejects it (kind A)
crates/serve/src/http.rs:238 and http.rs:272: Content-Length: 15,\x0b15 and chunk-size line f\x0b\r\n both become valid lengths because Unicode trimming removes the vertical tab. With body {"content":"x"}, both reach /tokenize and allow a pipelined GET /health. Invalid framing must instead return 400 and close.
Cost: the malformed-frame table is already in this change; adding these cases now closes the same defect on both framing paths.
Keep only HTTP space/tab trimming in the header-value push at line 165:
headers.push((k.to_owned(), v.trim_matches([' ', '\t']).to_owned()));Replace the length parser:
pub(crate) fn content_length(req: &Request) -> io::Result<Option<usize>> {
let mut length = None;
for (_, value) in req
.headers
.iter()
.filter(|(k, _)| k.eq_ignore_ascii_case("content-length"))
{
for value in value
.split(',')
.map(|value| value.trim_matches([' ', '\t']))
{
if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
return Err(bad("bad content-length"));
}
let len: usize = value.parse().map_err(|_| bad("bad content-length"))?;
if length.is_some_and(|previous| previous != len) {
return Err(bad("conflicting content-length"));
}
length = Some(len);
}
}
Ok(length)
}Replace chunk-size extraction at line 272; space/tab before an extension remains supported:
let digits = match line.split_once(';') {
Some((digits, _)) => digits.trim_end_matches([' ', '\t']),
None => line.as_str(),
};Add the two payloads above to malformed_request_framing_closes_the_connection, plus a scalar length with leading vertical tab to cover header-value trimming.
Non-blocking
⚠ Retain the real-server probe: crates/serve/src/api.rs:6733. The new test uses MockEngine. The PR lists raw-socket PASS output, but supplies no runnable real-server probe. Retain the client under tools/, or identify existing diagnostics that supply the fix contract's debugging layer.
Checked
Duplicates: the findings are distinct. Both public and body-reading routes reuse content_length.
Complexity: the added branches validate framing; complexity alone is not a finding.
Silent failure: whitespace erasure occurs before numeric validation on both framing paths.
Tests, static mutation: dropping http.rs:243's conflict refusal lets an existing malformed-frame case reach the handler instead of returning 400. The new tests omit the invalid whitespace cases above.
Gates: no existing threshold or test removed or relaxed; the new EOF/reset assertion has a dated PIN.
Escape catalog: no patterns matched. No ledger lessons apply. No decode, prefill, kernel or expert-tier work changed.
Notes
Validation was static; Rust tests were not run. GPU evidence lacks the required nvidia-smi line, both revisions and gate-command output.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
9737899 to
bf821d6
Compare
There was a problem hiding this comment.
Since the last review:
- Previous must-fix: fixed. HTTP whitespace trimming and single-CRLF removal preserve invalid bytes for numeric validation.
- Previous probe request: addressed by adding
tools/ref/serve-framing.sh. Its response reader has the defect below.
Verdict: MUST_FIX: the new framing probe rejects valid fragmented responses.
Must fix
1. Handle short socket reads in the framing probe (kind A)
tools/ref/serve-framing.sh:22: buffering=0 gives the HTTPResponse.read() call at line 33 a raw reader. A valid Content-Length: 10 body arriving in 3+7 bytes raises IncompleteRead(3 bytes read, 7 more expected) after the first read, even though the connection remains open. The probe exits before reporting the remaining cases.
Cost: correcting this now prevents transport fragmentation from being reported as a server defect.
Use a one-byte buffer. It fills body reads and leaves the next response unread:
def makefile(self, mode="r", buffering=None, **kwargs):
# Fill body reads without reading past the current response.
return super().makefile(mode, buffering=1, **kwargs)Checked
Duplicates: 3 new definitions checked; no duplicate owner found. Dryer reported 0 pairs.
Complexity: read_body 10 → 16 adds framing-validation branches; keep_alive 17 → 18 reuses length validation. Neither function changes further in this interdiff.
Silent failure: 4 edited normalization sites followed; invalid numeric framing reaches a named 400 and closes the connection.
Tests: static mutation check of malformed_request_framing_closes_the_connection: restoring Unicode trimming at http.rs:168, :243 or :279, or repeated CR stripping at :121, makes the new malformed-frame assertions fail. Positive cases retain HTTP whitespace and chunk extensions. An in-memory transport reproduces the short-read failure; the suggested replacement reads both pipelined responses completely.
Gates: no existing test, threshold or pin removed or relaxed.
Escape catalog: C1–C4 do not match. No ledger lessons apply. No decode, prefill, kernel or expert-tier path changed.
Notes
Validation used an in-memory transport and static code checks. Rust tests and real-server checks were not rerun.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
| class WireSocket(socket.socket): | ||
| def makefile(self, mode="r", buffering=None, **kwargs): | ||
| # Response parsing must leave pipelined bytes visible to the EOF check. | ||
| return super().makefile(mode, buffering=0, **kwargs) |
There was a problem hiding this comment.
Fill body reads across short socket reads to avoid IncompleteRead; a one-byte buffer preserves the next response.
| return super().makefile(mode, buffering=0, **kwargs) | |
| return super().makefile(mode, buffering=1, **kwargs) |
bf821d6 to
d3f36e5
Compare
There was a problem hiding this comment.
Since the last review:
- Previous must-fix: fixed at tools/ref/serve-framing.sh:22. The one-byte buffer fills short reads and preserves the next response.
Verdict: CLEAN: the interdiff fixes the probe's short-read failure without consuming pipelined responses.
Checked
Duplicates: 0 new definitions in the interdiff; the edited method reuses socket.makefile. Dryer reported 0 pairs.
Complexity: crapper reports read_body 10 → 16 (framing-validation branches) and keep_alive 17 → 18 (shared length validation). Neither changes in this interdiff.
Silent failure: 1 edited response-reading site followed; premature EOF raises IncompleteRead, and bytes after a complete response remain visible.
Tests: no tests changed in the interdiff. Nine in-memory cases passed for fragmented, coalesced and byte-at-a-time content-length, chunked and empty responses. Premature EOF raises IncompleteRead. Restoring buffering=0 reproduces the failure after 3 of 10 body bytes. Shell syntax passed.
Gates: no gate, threshold or pin changed.
Escape catalog: C1–C4 do not match. No ledger lessons apply. No inference hot path changed.
Notes
Validation used the actual socket.makefile implementation over an in-memory recv_into. Rust tests and real-server checks were not rerun. The PR lacks the complete GPU evidence list: the nvidia-smi line, both commit hashes and just gate-* commands with output.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
Validate every Content-Length value before reading a fixed-length body and require CRLF chunk boundaries and a complete trailer terminator. Keep chunked Transfer-Encoding precedence over Content-Length. Close a connection that ends with request bytes unread (a 400, a 401, or a public handler that ignores a body) by shutting the write side and draining what the client still sends, as the 503 refusal already did, so the client reads the answer instead of a reset. Choose guard markers only for client control spellings and use longer absent markers when every short pair occurs.
Extend the least frequent symbol prefix until it is absent, then use distinct endings for the two marker halves. Long input runs no longer enlarge every insertion or shift a guard boundary past a client control spelling.
d3f36e5 to
74a4feb
Compare
There was a problem hiding this comment.
Since the last review:
- The earlier probe short-read fix remains at tools/ref/serve-framing.sh:22. No earlier findings remain open.
Verdict: CLEAN: the interdiff shares bounded connection draining across early responses and preserves valid keep-alive dispatch.
Checked
Duplicates: 2 new definitions checked by Grep; neither duplicates an existing owner. The drain moves out of refuse_with. Dryer reported 0 pairs.
Complexity: read_body 10 → 16 adds framing validation and is unchanged in this interdiff; keep_alive 17 → 20 adds branches for closing existing request paths.
Silent failure: 5 transport-result sites followed. Failed writes, shutdowns, timeout setup or drain reads end the connection; unread bytes never become another request.
Tests (static mutation review): removing the drain calls at api.rs:1447, :1474 or :1486 exposes resets to the delayed-body write/EOF checks in the authorization and framing tests. The tightened framing assertion rejects ConnectionReset. Shell syntax passed.
Gates: the EOF assertion is stricter; no gate or threshold was relaxed.
Escape catalog: C1–C4 do not match. No ledger lessons apply. No inference hot path changed.
Adversarial checks: delayed bodies, buffered pipelines, stalled senders and failed writes are bounded or close; valid keep-alive requests bypass draining.
Notes
Rust tests and real-server checks were not rerun. The PR lacks complete GPU evidence: the nvidia-smi line, both commit hashes and just gate-* commands with output.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
|
The review is done and the contribution check passed, so I'm merging this. |
HTTP 요청의 길이와 chunk 경계를 엄격히 검사하고, 일반 텍스트가 guard 때문에 거부되던 문제를 고칩니다.
What and why
The server accepted requests with conflicting
Content-Lengthvalues and with broken chunk framing (junk or a bare LF after chunk data, a trailer cut off before its empty line). It then served the next request on the same connection. Now conflicting or non-numeric lengths are refused before the body is read, chunk data must be followed by exactly CRLF, and a trailer must end with an empty CRLF line. Each of these returns 400 and closes the connection.Transfer-Encoding: chunkedstill takes precedence overContent-Length.The control-token guard also picked its marker before it knew whether the input held any special token. Ordinary text with a few symbol pairs got a 400, and a long run of one symbol made the marker grow with the run (3517 bytes for a 1467 byte input). The marker is now chosen only when there is a token to protect, stays short on long runs, and cannot merge with neighbouring symbols in the text.
Release notes: Fixed | the server refuses ambiguous request lengths and broken chunk framing, and no longer rejects ordinary text containing symbol pairs.
Code shape
read_bodyand chunk lines share the existing maximum line length.render_chatthat can no longer happen is removed.cargo fmtandcargo clippyare clean on what I touched; the lint count did not go up.Duplication found or removed (
path:line), or "none": noneWhat I ran
Before the fix, each new test failed on its own commit with these lines:
After the fix, on an RTX 5090 machine:
Real server on a DGX Spark, with the existing
qwen3.8-fp4lcheckpoint, built and run with:The server started once and a client sent each case over raw sockets:
In the two special-token cases the guarded
prompt_idshold exactly one fewer<|im_end|>than the raw prompt tokenizes to, and detokenizing them returns the original prompt. No kernel, launch or decode path changed, so this PR makes no speed claim.Hardware (if the change is for a machine)
qwen3.8-fp4l(Qwen3.8-Flash-Next-FP4-Local)AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.