Skip to content

serve: keep saturated guard marks short and stable - #983

Merged
juliankang4 merged 4 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-sa-q8-serve-input
Oct 29, 2026
Merged

juliankang4 merged 4 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-sa-q8-serve-input

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

HTTP 요청의 길이와 chunk 경계를 엄격히 검사하고, 일반 텍스트가 guard 때문에 거부되던 문제를 고칩니다.

What and why

The server accepted requests with conflicting Content-Length values 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: chunked still takes precedence over Content-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

  • No second copy. The length check lives in read_body and chunk lines share the existing maximum line length.
  • Model code holds only architecture facts. No model file changed.
  • Dead code is gone. The guard error mapping in render_chat that can no longer happen is removed.
  • No silent failure. Bad framing is a named 400 with the connection closed.
  • Comments state what is true now.
  • No relaxed gate. No band, tolerance or lint moved.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": none

What I ran

Before the fix, each new test failed on its own commit with these lines:

cargo test -p bloomery-serve --lib malformed_request_framing_closes_the_connection -- --nocapture
test result: FAILED. 0 passed; 1 failed
cargo test -p bloomery-serve --lib symbol_pairs_do_not_refuse_client_text -- --nocapture
test result: FAILED. 0 passed; 1 failed
guard expansion: 3517 bytes for 1467 bytes
the client control spelling stays text beside the symbol run

After the fix, on an RTX 5090 machine:

cargo test -p bloomery-serve --lib malformed_request_framing_closes_the_connection -- --nocapture
test result: ok. 1 passed; 0 failed; 0 ignored
cargo test -p bloomery-serve --lib ctl_tests:: -- --nocapture
test result: ok. 14 passed; 0 failed; 0 ignored
cargo test -p bloomery-serve --lib http::tests:: -- --nocapture
test result: ok. 3 passed; 0 failed; 0 ignored

Real server on a DGX Spark, with the existing qwen3.8-fp4l checkpoint, built and run with:

cargo oxide build --arch sm_121a -- -p bloomery-gpu-gates --features deepseek41,gemma-embedding2,hf,checkpoint --release --bin bloomery-serve-qwen38
BLOOMERY_DRAFT=off BLOOMERY_RESIDENCY=off BLOOMERY_BOX_CARD=local BLOOMERY_GATE_BOUND=290 bash tools/gpu-gate.sh bloomery-serve-qwen38 --host 127.0.0.1 --port 54833 --parallel 1 --ctx-size 1024 --cache-ram 0 -ub 128

The server started once and a client sent each case over raw sockets:

PASS cargo oxide build
PASS real Qwen server /health=200
PASS conflicting-lengths status=400 connection=close eof=yes
PASS conflicting-comma-lengths status=400 connection=close eof=yes
PASS chunk-data-junk status=400 connection=close eof=yes
PASS chunk-data-lf status=400 connection=close eof=yes
PASS trailer-eof status=400 connection=close eof=yes
PASS trailer-partial-crlf status=400 connection=close eof=yes
PASS equal-lengths status=200 keep-alive-next=200
PASS equal-comma-lengths status=200 keep-alive-next=200
PASS chunked-precedence status=200 keep-alive-next=200
PASS ordinary-pairs apply-template=200 prompt-roundtrip=yes chat=200 generated=1
PASS special-pairs apply-template=200 prompt-roundtrip=yes chat=200 generated=1
PASS adjacent-run-pairs apply-template=200 prompt-roundtrip=yes chat=200 generated=1
PASS serve-input-card all framing and guard clauses; one server start

In the two special-token cases the guarded prompt_ids hold 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)

Card Driver Model
NVIDIA GB10 595.84 qwen3.8-fp4l (Qwen3.8-Flash-Next-FP4-Local)

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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)

@juliankang4
juliankang4 force-pushed the dgx-spark-q38-sa-q8-serve-input branch from 9737899 to bf821d6 Compare October 29, 2026 18:52
@github-actions github-actions Bot added the tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo label Oct 29, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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)

Comment thread tools/ref/serve-framing.sh Outdated
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fill body reads across short socket reads to avoid IncompleteRead; a one-byte buffer preserves the next response.

Suggested change
return super().makefile(mode, buffering=0, **kwargs)
return super().makefile(mode, buffering=1, **kwargs)

@juliankang4
juliankang4 force-pushed the dgx-spark-q38-sa-q8-serve-input branch from bf821d6 to d3f36e5 Compare October 29, 2026 19:06
github-actions[bot]
github-actions Bot previously approved these changes Oct 29, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the last review:

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.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the last review:

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)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit 777bdef into midagedev:main Oct 29, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

serve The HTTP server: crates/serve tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant