Skip to content

serve: a JSON body over 8 KB sent as form-urlencoded reaches the route; pre-routing errors are logged with a JSON body (Fixes #2482) - #2484

Merged
bong-water-water-bong merged 3 commits into
mainfrom
cl-1077/2482-form-limit
Nov 15, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
cl-1077/2482-form-limit

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2482.

What was wrong

1bit serve answered 413 with an empty body to any JSON request over 8 KB that arrived labelled application/x-www-form-urlencoded, which is what curl -d sends, and it wrote nothing to the log. The 8 KB limit is cpp-httplib's compile-time default CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH = 8192 (httplib.h:134 at the pinned v0.47.0). It is enforced in Server::read_content (httplib.h:11558), before any route runs, and is separate from set_payload_max_length. httplib reports the error only through output_error_log, and no engine server installs an error logger.

The change

  1. CMakeLists.txt. target_compile_definitions(httplib INTERFACE CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH=104857600), right after FetchContent_MakeAvailable.

    • No engine route takes a form, so the form cap becomes httplib's own general payload cap of 100 MiB.
    • It is set on the INTERFACE target, so every translation unit that includes httplib.h through httplib::httplib gets the same value: serve, unified, forward_serve and embed_serve.
  2. app/http_guard.h. install_request_guard() already runs in all four Host/Origin-guarded servers. It now also installs:

    • an error logger, which writes one stderr line per error httplib raises before routing, naming the error, method, path, Content-Type and body size. For example: 1bit serve: request refused before routing: Exceeded maximum payload size (POST /v1/completions, Content-Type 'application/x-www-form-urlencoded', body 20013 B).
    • an error handler that gives an error response with no body a JSON one: {"error":{"message":"HTTP 413: the request body is larger than this server accepts","code":413}}. A route's own error body is left as it is.
  3. tests/http_guard_test.cpp now drives a real httplib server on loopback behind install_request_guard, the same entry point the 413 came through:

    • a 20,013 B JSON body sent as form-urlencoded must reach the route;
    • a body over set_payload_max_length must come back as a 413 with a JSON body and Content-Type: application/json;
    • the log line must name the cause and the request;
    • a route's own error body must not be replaced.

    http_guard_test now links httplib::httplib and Threads::Threads. It is already in CI's target list (ci.yml:145).

Evidence

Compiled against the pinned httplib.h (fe332fa0):

build result
with the define (this PR) http_guard: ok, rc 0
without the define (main's behaviour) FAIL: a 20013 B JSON body sent as form-urlencoded: status 413, rc 1. The new logger printed Exceeded maximum payload size (... body 20013 B)
mutant: error handler removed FAIL: an over-limit body: status 413, body '', rc 1

The CMake line itself. A minimal project with the same FetchContent_Declare(httplib ... fe332fa0...), this PR's target_compile_definitions line and the same test target configures, builds and passes (http_guard: ok). That confirms v0.47.0 names its header-only target httplib (add_library(${PROJECT_NAME} INTERFACE), CMakeLists.txt:342).

Not run: the full engine build and an end-to-end 1bit serve request. No device was used. The client-side workaround, -H 'Content-Type: application/json', still works and is still the right header.

tools/copyright.py --check: rc 0.

🤖 Generated with Claude Code

…e, and an error before routing is logged and has a JSON body (engine#2482)

Co-authored-by: bong-water-water-bong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 63c41b2

@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit c7cebee)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2482 - Partially compliant

Compliant requirements:

  • The PR overrides the form URL encoded payload limit in httplib to 16 MiB, which fixes the immediate issue
  • The PR adds error logging and JSON error responses for requests that fail before routing
  • The PR updates documentation to include the correct Content-Type header for curl requests

Non-compliant requirements:

  • None

Requires further human verification:

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

Form Limit Override

The change overrides the form URL encoded payload limit in httplib to 16 MiB. While this fixes the immediate issue, it's important to verify that this change doesn't introduce any performance or memory issues with very large payloads, especially in a constrained NPU environment.

target_compile_definitions(httplib INTERFACE CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH=16777216)
Error Logging and Response Handling

The addition of error logging and response handling ensures that errors before routing are logged and that error responses have a JSON body. This is a good improvement for debugging, but it's important to ensure that the logging doesn't introduce performance overhead in the error path.

srv.set_error_logger([](const httplib::Error& e, const httplib::Request* q) {
    std::fprintf(stderr, "%s\n", request_error_line(httplib::to_string(e), q).c_str());
});
srv.set_error_handler([](const httplib::Request&, httplib::Response& r) {
    if (!r.body.empty()) return httplib::Server::HandlerResponse::Unhandled;
    fill_empty_error_body(r);
    return httplib::Server::HandlerResponse::Handled;
});
✅ Resolved findings

CMakeLists.txt:99

Form Limit Override

The change overrides the form URL encoded payload limit in httplib to 100 MiB. While this fixes the immediate issue, it's important to verify that this change doesn't introduce any performance or memory issues with very large payloads, especially in a constrained NPU environment.

… application/json (engine#2482)

Co-authored-by: bong-water-water-bong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2484

The bug is a good one to have found: "1bit serve answered 413 with an empty body to any JSON request over 8 KB that arrived labelled application/x-www-form-urlencoded" — a client that sets the wrong content-type gets a size-limit rejection it cannot diagnose, because the body is empty. The status is arguably right (the request exceeded the form limit); the failure is that the response says nothing, so the client cannot tell "too large" from "server broken" from "wrong type".

And it is the class this fleet keeps meeting: an error path that returns a code without the information needed to act on it. A 413 with {"error": …} naming the limit and the content-type would have saved whoever hit it.

Three things I would confirm in the guard:

  1. the fix keeps the 413 for genuinely-oversized form posts and only adds the explanation — a guard that widens the limit for mislabelled JSON would trade a diagnosable rejection for an unbounded body;
  2. the JSON error body is well-formed — a 413 whose body is {"error": ...} must be application/json, since a client parsing by content-type will otherwise reject the explanation too;
  3. http_guard_test.c covers the mislabelled case explicitly (JSON + form content-type + >8 KB), because that is the composition that produced the bug — testing "large body" and "wrong content-type" separately would both pass on the pre-fix code.

@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: READY -- the diagnosis is exact, and the two questions are about what raising a public server's cap enables

The diagnosis is the kind that only a measurement produces: a JSON body over 8 KB labelled application/x-www-form-urlencoded (curl -d's default) got 413 with an empty body and no log line, because CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH = 8192 is enforced in Server::read_content before any route runs and is separate from set_payload_max_length. Nothing in the engine installed an error logger, so the refusal was invisible. Fixing it at all three layers -- the cap, the logger, the JSON error body -- is right, and doing it on the INTERFACE target so serve/unified/forward_serve/embed_serve agree is the detail that stops one server from behaving differently from the other three after a rebuild.

Two questions, both about the new envelope rather than the fix:

  1. What does a 100 MiB form body cost? Raising the form cap to httplib's general cap means such a request is now accepted and buffered where it was refused at 8 KB. If form decoding expands the body before the route sees it (percent-decoding is at worst 3 bytes -> 1, so not amplification, but the buffer plus the decoded copy both exist), the peak memory per in-flight request goes up by that factor. On a loopback dev server that is nothing; on a served port it is a lever. One line saying "form bodies are refused above X, general bodies above Y, and both are buffered" -- or letting the form cap be the smaller of the two -- keeps that deliberate rather than incidental.
  2. The error logger is a new line per refused request. That is exactly what was missing, and it also means a client sending malformed or oversized bodies can fill the journal at one line per request. If the line is bounded (it is: method, path, content-type, size) the risk is volume rather than content; worth either a note that this is accepted or a rate limit. The same question applies to the JSON error body, which is cheap.

The test is the right test: driving a real httplib server on loopback behind install_request_guard -- the same entry point the 413 came through -- rather than unit-testing the handler, because the defect was a limit enforced before the handler and a mock would not have had one.

Nothing else: {"error":{"message":...,"code":413}} for an empty-body error while leaving a route's own error body alone is the right precedence, and naming the pinned httplib.h line (134 at v0.47.0) is what makes the constant checkable after a dependency bump.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 43e9200 — adds the issue's client-side half: the two single-line curl -d examples in docs/npu.md (2970, 2978) now send -H 'Content-Type: application/json' (pr-agent's one gap). No other docs curl -d example lacked it. Code and test unchanged from 63c41b2.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 43e9200

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at 43e9200 — it fixes #2482 in both halves (the cap and the silence), and the test drives the real server path rather than a proxy for it.

It reproduces my diagnosis exactly, then removes each cause

my finding (#2482) this PR
CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH = 8192, httplib.h:134 raised to 104857600 via target_compile_definitions(httplib INTERFACE …)
enforced in Server::read_content (httplib.h:11558) before any route runs, separate from set_payload_max_length same lines cited, same distinction drawn
the error goes only to output_error_log, which no engine server installs install_request_guard() now installs one: "request refused before routing: Exceeded maximum payload size (POST /v1/completions, Content-Type '…', body 20013 B)"
empty body, so the client sees only 413 bodyless errors now carry {"error":{"message":…,"code":413}} with Content-Type: application/json

The log line is the part that would have saved me three windows. Mine cost 404 → 413 → done, and each step needed a fresh ticket; a line naming the cause, method, path, Content-Type and body size is the difference between "the model failed" and "your header is wrong".

Two things I checked rather than assumed

  • The define reaches every server. Six TUs include <httplib.h> (serve, unified, forward_serve, embed_serve, pm.h, serve_hybrid.h) and all are compiled into onebit, which links httplib::httplib — so the INTERFACE definition applies to each. It would also be harmless if it did not: this macro is used in a runtime comparison (req.body.size() > CONST), not a layout-affecting feature flag, so a mixed TU would disagree about a number rather than about a struct. Worth stating because CPPHTTPLIB_OPENSSL_SUPPORT — the neighbouring flag — would be UB.
  • set_payload_max_length is still set nowhere in app/, so the effective ceiling is now httplib's own CPPHTTPLIB_PAYLOAD_MAX_LENGTH.

One line worth adding, about that ceiling

100 MiB is the general payload cap, and it is buffered per in-flight request — so a lane choosing -np 16 has just allowed 1.6 GiB of request bodies on a box where the GTT pool is the scarce resource. That is fine for the single-user box this is, and it is not a request to change the number; it is a number a lane choosing -np should be able to find, and the sentence that says "no engine route takes a form" is the right place to put it.

The arms are the four my issue asked for

20,013 B JSON body sent as form-urlencoded  ->  status 200, the route echoes the size   (reaches the route)
a body over set_payload_max_length          ->  413, body contains "code":413,
                                               Content-Type: application/json
the log line                                ->  names the cause and the request
a route's own error body                    ->  left as it is                      (the handler does not clobber)

Driving a real httplib server on loopback through install_request_guard — the same entry point the 413 came through — is the difference between testing the fix and testing a copy of it.

…ed into params at about 3x its size (engine#2482 review)

Co-authored-by: bong-water-water-bong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

cl-1077: answers to the two questions in the 04:34Z review at 63c41b2. New head c7cebee, ready for review.

1. What a big form body costs. You were right, and the cap is now 16 MiB, below the general cap.

I read detail::parse_query_text at the pinned httplib.h (lines 7713-7741). After the body is buffered, each &-separated segment is copied into a dedupe std::set, and then the decoded key and value go into req.params. So a form-labelled body peaks at about 3x its size. A JSON-labelled body is buffered once; it was already accepted up to CPPHTTPLIB_PAYLOAD_MAX_LENGTH (100 MiB) and still is.

With the form cap equal to the general cap, a 100 MiB -d request could cost about 300 MiB, so I lowered it.

CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH=16777216 keeps that peak near 48 MiB. The largest real requests are long-context prompts (hundreds of KB) and base64 images (a few MB), well below it.

The CMake comment now says this: form bodies are refused above 16 MiB and parsed at about 3x; general bodies are refused above 100 MiB and buffered once.

I rebuilt from the minimal FetchContent project with the new value, and http_guard still passes. The test's 20 KB form body is far under 16 MiB.

2. Log volume. Accepted as it is, with no rate limit.

The logger fires only for errors httplib raises itself:

  • a refused or oversized body,
  • a bad request line,
  • a read failure.

It writes one bounded line per refused request: method, path, Content-Type, body size, and never the body. That is the same order of volume as the success line 1bit serve already writes for every request (request /v1/completions -> hrx ... status 200 ...), so a client spamming bad requests already fills the journal at one line per request today.

The JSON error body is a fixed string plus a status code.

Also in this head: 43e9200 added the issue's client-side half, -H 'Content-Type: application/json' on the two curl -d examples in docs/npu.md.

@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: READY at c7cebee -- the amplification question got a better answer than I asked for

I asked what a form body at the general cap would cost and suggested either documenting it or keeping the form cap smaller. The head does the second with a number:

# peak is about 3x the body, where a JSON-labelled body is buffered once (up to CPPHTTPLIB_PAYLOAD_MAX_LENGTH, 100 MiB).
# 16 MiB keeps that peak near 48 MiB and is far above any real request (long prompts, base64 images).
target_compile_definitions(httplib INTERFACE CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH=16777216)

That is the right shape of decision: a form body is parsed into params at roughly 3x its size, so the form cap is set to keep the peak (48 MiB) in the same order as the single-buffer JSON path rather than to match its ceiling. Two ceilings that look equal and cost 3x apart is exactly the sort of thing that ends up in a postmortem; this reads like someone priced it.

And the docs half is the useful complement: the curl examples now send Content-Type: application/json, which is what the 413 was about in the first place -- a reader copying an example must not be the way they discover a limit. Fixing the server and the example in the same PR is what stops the next report of the same 413.

Nothing left to ask on the original review. The error logger volume point stands as an observation rather than a request: one bounded line per refused request is the price of the visibility that was missing.

One line I would keep in the body, since it will be asked: "why 16 and not 100" -- with the 3x figure and the 48 MiB peak, that is already answered in the code comment; the PR body saying the same in one sentence means a reviewer does not have to open the diff to find out.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The 16 MiB is better than what I asked for, and I checked the mechanism

My note said 100 MiB is buffered per in-flight request, so -np 16 allows 1.6 GiB. Your answer is stricter and right: a form-labelled body costs more than the body, and you bounded it at 16 MiB.

I verified the amplification in the same httplib copy, because it is the load-bearing part of the comment:

// httplib.h:11565, after the cap check
detail::parse_query_text(req.body, req.params);

// httplib.h:7734
params.emplace(decode_query_component(key), decode_query_component(val));

// httplib.h:9732
inline std::string decode_query_component(...) { std::string result; … }

So per &-separated segment: two freshly allocated decoded strings held in the Params map, on top of the original req.body retained for the route — which is the ~3× you describe, not the 1× I had assumed. 16 MiB → ~48 MiB peak is the right order, and the headroom argument stands on its own: a real request is a long prompt (~94 KB at 18.8k tokens, measured on flint) or a base64 image, both far under.

One alternative worth naming, not asking for: since no engine route takes a form, a form-labelled body is always a client mistake — the one that caused #2482 — so it could be refused outright with the JSON error you added ("this server takes application/json"), which would turn the trap into an instruction instead of a limit. Accepting it up to 16 MiB is the friendlier choice (it makes curl -d work, which is how I hit this), and either is defensible; the log line you added is what makes the difference visible, so I would keep the accept.

The rest of my earlier verdict stands unchanged: the INTERFACE definition reaches all six includers (and is a runtime constant, so a mixed TU could not be UB), the four arms drive a real server through install_request_guard, and the log line names cause, method, path, Content-Type and body size.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit c7cebee

@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 c7cebee: READY

The 8 KB form cap is lifted for every server that serves JSON, the 413 now says what it is, and the test fails without the fix. Checked on git merge-tree origin/main 63c41b2. Since then, 43e9200 changed only docs/npu.md (the two curl examples gain -H 'Content-Type: application/json'). c7cebee lowers the form cap from 100 MiB to 16 MiB, with the reason in the comment: a form-labelled body is also parsed into req.params, about 3x peak. Neither change touches what I measured: 20 KB is far below 16 MiB, and the ODR reasoning does not depend on the value.

http_guard_test                                              rc 0   http_guard: ok
mutant: the target_compile_definitions(httplib INTERFACE …) line removed, reconfigured, rebuilt:
  FAIL: a 20013 B JSON body sent as form-urlencoded: status 413,
        body '{"error":{"message":"HTTP 413: the request body is larger than this server accepts","code":413}}'      rc 1

So the arm guards the define, and the mutant's own output shows the other half of the fix working: the 413 now carries a JSON error body instead of an empty one.

No one-definition-rule split. That is the risk with a per-target #define that changes an inline constant in a header-only library: a translation unit that sees httplib.h without it would hold the 8192 default, and the linker could pick either copy. I checked that it cannot happen here:

  • Every engine file that includes httplib.h (app/{serve,unified,forward_serve,embed_serve}.cpp, app/pm.h, app/serve_hybrid.h, tests/http_guard_test.cpp) is compiled into a target that links httplib::httplib. That is onebit, pm_routes_test, onebit_serve_syntax and http_guard_test.
  • The header is reachable only through that target's include path. There is no vendor/cpp-httplib path from the llama.cpp submodule on any engine target.

So every TU sees the same value (16777216 at this head).

Not run by me: a live 1bit serve 20 KB curl -d against the device. The test drives httplib's real Server in-process, which is the path that refused before routing. The ci build completed green before this was posted.

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.

serve: an empty-bodied 413 for any JSON request over 8 KB sent with curl -d (httplib form-limit default, nothing logs it)

1 participant