Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

docs: record the body-structure bounds, the wait kind and the lock order

Alfredo Lopezdd2506e0031a
diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.md
index 16fb4304f..25510dce0 100644
--- a/docs/architecture/codex-subscription-transport-contract.md
+++ b/docs/architecture/codex-subscription-transport-contract.md
@@ -79,7 +79,8 @@ Admin and unauthenticated requests retain the ordinary configured body limit.
`CODEX_LLM_PROXY_MAX_BODY_BYTES` continues to control ordinary requests; the
manifest leaves it unset so the proxy derives it from the contract cap plus the
envelope allowance.
-The internal authorization gateway also permits 24 MiB only at the exact
+The internal authorization gateway also permits 36700160 bytes (35 MiB, the
+larger of the Codex and Grok visual caps) only at the exact
`/api/v1/mcp-host/llm/provider-attempts/authorize` POST location. That single
`client_max_body_size` also covers the V1 cap plus the authorize envelope
allowance, which is smaller. Other locations
@@ -213,8 +214,9 @@ silently truncating tools or changing presentation.
image (#731). It covers a 1M-token window serialized as escaped JSON. The
proxy's body limit is that cap plus a 16 KiB envelope allowance. The
workflow-approval-gateway authorize location sets `client_max_body_size` to
-25165824, the visual cap, which is larger and therefore covers it. The proxy
-admits bodies against an in-flight byte budget before parsing them.
+36700160, the larger of the Codex and Grok visual caps, which covers it. The
+proxy admits bodies against an in-flight byte budget before parsing them, and
+bounds their structure before parsing them (below).
The Host starts compaction at 80% of the model's context window, so the window
decides how much of that cap a conversation can use. The proxy keeps the
@@ -228,6 +230,62 @@ stored, the Host uses 256000 for `codex-subscription`. It logs
`context_window_resolved` once per task with the provider, the model, the
window and its source (`catalog` or `default`).
+### Body structure before parse (#806)
+
+`JSON.parse` allocates one heap object per container before any contract
+check runs, so a body within the byte limit can exhaust a heap capped at
+384 MiB. A 25165824-byte body of `[],` padding aborted `codex-llm-proxy`, and
+the contracts accepted 4117647 containers in an 8 MiB request. Both contracts
+therefore bound the structure as well as the bytes, and every parser checks the
+raw body before parsing it.
+
+- `LIMITS.maxRequestContainers` is 262144 objects and arrays per request, the
+ same in both contracts. `checkStructure` refuses one more with
+ `request exceeds maxRequestContainers` (`kind: 'size'`).
+- `bodyStructure.cjs`, byte-identical in both contract packages, scans the raw
+ bytes in one pass and tracks string and escape state. `BODY_STRUCTURE_LIMITS`
+ derives its bounds from `LIMITS`: 8404992 structural bytes
+ (`maxRequestBodyBytes` plus the 16 KiB envelope allowance; bytes inside
+ strings and whitespace are not counted), 262160 containers
+ (`maxRequestContainers` plus 16 for the envelope) and depth 70
+ (`maxNestingDepth + 6`, the control-api formula). A contract test runs the
+ deepest and the largest request the contract accepts through the scan.
+- The scan is the `verify` hook of every JSON parser in both proxies
+ (ordinary, visual and admin) and of the control-api authorize route, so it
+ runs after the body is read and before `JSON.parse`. A body that is too
+ dense or has too many containers is answered 413 `payload_too_large`, a body
+ that is too deep 400 `invalid_request`, and a charset other than UTF-8 415
+ `unsupported_media_type`. A refused visual body frees its slot.
+- body-parser attaches the raw body to these errors, so the proxies' error
+ handlers log only the error type and status, and the control-api authorize
+ route answers every parser error itself instead of passing it to the global
+ error handler.
+- The control-api authorize route parses with `inflate: false`, so an encoded
+ body is refused 415 before it is read. Before, 35750 bytes of gzip inflated
+ to 35 MiB.
+
+The value was measured in this proxy, which holds the most bodies at once:
+three ordinary bodies at the 8404992-byte cap plus two visual bodies, tsc
+build, `--max-old-space-size=384`, upstream held open, every body exactly
+262144 containers, two shapes (`{}` and a depth-61 chain), two runs each.
+Every run exited 0 and admitted all five. The heap after a full GC was
+154.4-163.4 MiB and the sampled peak 205.6-238.4 MiB. At 524288 containers one
+run peaked at 319.6 MiB, and at 1048576 the process aborted. A new value must
+keep every run at exit 0 with five of five admitted, at most 200 MiB after GC
+and at most 280 MiB sampled peak. These figures are lower bounds: the
+serializations made while forwarding are not included.
+
+The bound does not refuse realistic requests. Tool results and message
+content are strings, which count only as structural bytes for their quotes; a
+2 MiB tool catalog is about 100000 containers. Realistic JSON reaches about
+420000 containers only at 8 MiB, and a request that large is already over any
+model's context window. The Host
+refuses a history over the bound before authorize as `payload_too_large`, and
+classifies it as `ContextLengthExceeded`, not retryable.
+
+Follow-up: a refusal metric by type (`body.structure.*`) and a histogram of
+container counts per request, to check the bound against real use.
+
### Compatibility and deployment order
The V1 wire fields and canonical hash projection are unchanged. Previously
@@ -361,7 +419,17 @@ behavior changes:
margin. A request still queued then is answered 503
`provider_unavailable` without a redeem, and the proxy logs
`codex_proxy_admission_refused` with `reason: ticket_life`,
- `providerAttemptId` and `hostRef`.
+ `providerAttemptId` and `hostRef`. The refusal applies only when the
+ wait ended on its own deadline (`RequestLimitError.kind` is
+ `'deadline'`), that deadline was the ticket's `exp`, and the client had
+ not aborted. The proxy does not compare the current time with `exp`,
+ because the timer can fire a millisecond before `Date.now()` reaches it. A full queue, a
+ queue-wait timeout and a client abort keep their own answers.
+ - A request that declared a length above the ordinary cap but whose
+ envelope fits the ordinary cap is demoted to the ordinary path. It takes
+ the in-flight byte budget before it releases its visual slot, so every
+ request acquires in the order visual slot, byte budget, stream slot, and
+ no two requests can wait on each other.
- It requires the redeem response to carry `maxStreamDurationMs` greater
than 0. An absent value is a contract violation, not a default.
- It logs one `codex_proxy_attempt_finished` event per completion attempt,
@@ -434,8 +502,9 @@ code the proxy constructs, and every code it refuses a request with
parsed within the proxy's read deadline; the upstream never saw it.
- `length_required`: HTTP 411. The request carried `Transfer-Encoding` instead
of a `Content-Length`, so its size cannot be admitted before reading.
-- `unsupported_media_type`: HTTP 415. The body is not `application/json`, or it
- carries a `Content-Encoding` (the parsers never inflate).
+- `unsupported_media_type`: HTTP 415. The body is not `application/json`, it
+ carries a `Content-Encoding` (the parsers never inflate), or it declares a
+ charset other than UTF-8.
- `length_required` and `unsupported_media_type` stay in the Host's generic
non-retryable bucket (`LLM_API_CALL_FAILED`): the Host sends a string body,
so its client always sets `Content-Length`, never sets `Content-Encoding` and
diff --git a/docs/architecture/grok-subscription-transport-contract.md b/docs/architecture/grok-subscription-transport-contract.md
index 5a2391b3f..7a24a2880 100644
--- a/docs/architecture/grok-subscription-transport-contract.md
+++ b/docs/architecture/grok-subscription-transport-contract.md
@@ -57,9 +57,11 @@ data blanked in a temporary projection.
The contract checks a V2 request in this order:
1. the structure, before any byte is measured: nesting depth, refused as
- `request exceeds maximum nesting depth 64`, and an element count bounded by
+ `request exceeds maximum nesting depth 64`, an element count bounded by
`maxRequestBodyBytes`, refused as
- `request exceeds maxRequestBodyBytes element bound` (`kind: 'size'`);
+ `request exceeds maxRequestBodyBytes element bound` (`kind: 'size'`), and
+ the container count, refused as `request exceeds maxRequestContainers`
+ (`kind: 'size'`, see "Body structure before parse" below);
2. the non-image share against `maxRequestBodyBytes`, refused as
`request exceeds maxRequestBodyBytes outside image data`;
3. the whole request against 35 MiB, refused as
@@ -82,7 +84,9 @@ Where the envelope is enforced:
it streams, and its authorizer bounds the authorize body by the Grok
contract, not the Codex one;
- the control-api authorize route parses up to 36700160 bytes (the larger of
- the Codex and Grok visual caps), and the authorizer builds the exact V2
+ the Codex and Grok visual caps), without inflating and after the structure
+ scan described under "Body structure before parse", and the authorizer
+ builds the exact V2
proxy envelope inside its transaction after signing and before commit, so
an envelope over the cap rolls back the attempt, the ticket and the
reservation;
@@ -101,10 +105,14 @@ Proxy admission. A request whose declared `Content-Length` is above the
ordinary cap needs a valid platform identity, then takes a slot in a visual
stream gate of 1 running and 4 queued (`VISUAL_STREAM_LIMITS`) before the body
is read, so queued visual bodies are not held in memory. Visual bodies do not
-take the ordinary in-flight byte budget. A body sent with `Transfer-Encoding`
-is refused 411 `length_required` before any gate (#731), so it never queues
-behind a visual stream, and a declared length above the visual cap is refused
-413 before reading. Anonymous, wrong-scope and admin requests keep the
+take the ordinary in-flight byte budget. A request that declared a length
+above the ordinary cap but whose envelope fits the ordinary cap is demoted to
+the ordinary path: it takes the in-flight byte budget before it releases its
+visual slot, so every request acquires in the order visual slot, byte budget,
+stream slot, and no two requests can wait on each other. A body sent with
+`Transfer-Encoding` is refused 411 `length_required` before any gate (#731),
+so it never queues behind a visual stream, and a declared length above the
+visual cap is refused 413 before reading. Anonymous, wrong-scope and admin requests keep the
ordinary limit.
The visual wait uses the request's single admission clock (arrival +
@@ -343,8 +351,9 @@ the proxy both surface a size refusal (`kind: 'size'`) as HTTP 413
(#784; the control-api authorizer answered `invalid_request` for size too
before it), while the Host raises `request_limit_exceeded` before it
authorizes at all — for the five size refusals listed under that code below —
-`attachment_too_large` for the image budget refusals, and `invalid_request`
-for the rest, which no amount of compaction would fix.
+`attachment_too_large` for the image budget refusals, `payload_too_large` for
+the container bound (both classify as `ContextLengthExceeded`), and
+`invalid_request` for the rest, which no amount of compaction would fix.
That symmetry holds for a request and not for a response, which is why the
rollout order below is not interchangeable. A proxy carrying the new bound in
@@ -400,7 +409,13 @@ Proxy robustness (both proxies):
- The stream-gate wait also ends at the execution ticket's `exp`, with no
margin. A request still queued then is answered 503 `provider_unavailable`
without a redeem, and the proxy logs `grok_proxy_admission_refused` with
- `reason: ticket_life`, `providerAttemptId` and `hostRef`.
+ `reason: ticket_life`, `providerAttemptId` and `hostRef`. The refusal
+ applies only when the wait ended on its own deadline
+ (`RequestLimitError.kind` is `'deadline'`), that deadline was the ticket's
+ `exp`, and the client had not aborted. The proxy does not compare the
+ current time with `exp`, because the timer can fire a millisecond before
+ `Date.now()` reaches it. A full queue, a queue-wait timeout and a client
+ abort keep their own answers.
- A single attempt streams for at most `maxStreamDurationMs`: the minimum of the proxy configuration, `STREAM_LIMITS`, the contract
`maxDeadlineMs` and the value control-api returns on redeem.
- The proxy fails at startup when `GROK_LLM_PROXY_CONTROL_API_URL` or
@@ -409,6 +424,34 @@ Proxy robustness (both proxies):
The redeem response must carry `maxStreamDurationMs` greater than 0; an
absent value is a contract violation, not a default.
+### Body structure before parse (#806)
+
+`JSON.parse` allocates one heap object per container before any contract
+check runs, so a body within the byte limit can exhaust the proxy's 384 MiB
+heap. A 36700158-byte body of `[],` padding aborted `grok-llm-proxy`, and so
+did three ordinary 8 MiB bodies of 4117647 empty containers each, which the
+contract accepted. The fix is the same in both proxies and both contracts, and
+is described in full, with the measurement, under "Body structure before
+parse" in `codex-subscription-transport-contract.md`. In short:
+
+- `LIMITS.maxRequestContainers` is 262144 objects and arrays per request;
+ `checkStructure` refuses one more with `request exceeds maxRequestContainers`
+ (`kind: 'size'`). Like `maxVisualRequestBodyBytes`, it is a runtime limit and
+ is not published in the fixture (`RUNTIME_ONLY_LIMIT_KEYS`).
+- The ordinary, visual and admin parsers run the contract's raw-body scan
+ (`bodyStructure.cjs`, `BODY_STRUCTURE_LIMITS`: 8404992 structural bytes,
+ 262160 containers, depth 70) as their `verify` hook, before `JSON.parse`.
+ Too dense or too many containers is answered 413 `payload_too_large`, too
+ deep 400 `invalid_request`, a charset other than UTF-8 415
+ `unsupported_media_type`; a refused visual body frees its slot, and the
+ error handler logs only the error type and status because the error carries
+ the raw body.
+
+The value was measured on the Codex proxy, which holds five bodies at once
+against this proxy's four. This proxy was measured at 524288 containers
+(three ordinary bodies and one visual body): 196.8 MiB resident. It has not
+been measured at 262144.
+
## Identity headers
Stamped in `grok-llm-proxy`, never taken from mcp-host or the hashed request:
@@ -486,8 +529,9 @@ code the proxy constructs, and every code it refuses a request with
parsed within the proxy's read deadline; the upstream never saw it.
- `length_required`: HTTP 411. The request carried `Transfer-Encoding` instead
of a `Content-Length`, so its size cannot be admitted before reading.
-- `unsupported_media_type`: HTTP 415. The body is not `application/json`, or it
- carries a `Content-Encoding` (the parsers never inflate).
+- `unsupported_media_type`: HTTP 415. The body is not `application/json`, it
+ carries a `Content-Encoding` (the parsers never inflate), or it declares a
+ charset other than UTF-8.
- `length_required` and `unsupported_media_type` stay in the Host's generic
non-retryable bucket (`LLM_API_CALL_FAILED`): the Host sends a string body,
so its client always sets `Content-Length`, never sets `Content-Encoding` and
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 55768918c..47fc2a5b8 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.452",
+ "version": "0.1.453",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.452",
+ "version": "0.1.453",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 6e0a406d8..272844c3e 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.452",
+ "version": "0.1.453",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/llm/codexSubscription.ts b/mcp-host/src/llm/codexSubscription.ts
index 43a049640..eda4b966d 100644
--- a/mcp-host/src/llm/codexSubscription.ts
+++ b/mcp-host/src/llm/codexSubscription.ts
@@ -69,7 +69,10 @@ export type CodexAttemptContext = {
* `subscriptionRequestHash.test.ts` pins for the over-deep schema.
* The image budgets belong to the attachments, not the conversation: a `size`
* one is `attachment_too_large` (see `ATTACHMENT_BUDGET_REFUSALS`), the
- * `maxImages` `count` one stays `invalid_request`.
+ * `maxImages` `count` one stays `invalid_request`. The container bound
+ * (`maxRequestContainers`, `checkStructure`) is volume too, but it is not
+ * listed: it carries `kind: 'size'`, so it reaches the user as
+ * `payload_too_large`, which classifies the same way (T-C3b).
*
* `hashCanonicalCodexRequest` also returns a `kind`, but it cannot replace the
* message here: `size` covers the conversation bytes and the image byte and
diff --git a/mcp-host/src/llm/grokSubscription.ts b/mcp-host/src/llm/grokSubscription.ts
index f235406d4..a846881cb 100644
--- a/mcp-host/src/llm/grokSubscription.ts
+++ b/mcp-host/src/llm/grokSubscription.ts
@@ -79,7 +79,10 @@ export type GrokAttemptContext = {
* providers. The image budgets belong to the attachments, not the
* conversation: a `size` one is `attachment_too_large` (see
* `ATTACHMENT_BUDGET_REFUSALS`), the `maxImages` `count` one stays
- * `invalid_request`.
+ * `invalid_request`. The container bound (`maxRequestContainers`,
+ * `checkStructure`) is volume too, but it is not listed: it carries
+ * `kind: 'size'`, so it reaches the user as `payload_too_large`, which
+ * classifies the same way (T-C3b-grok).
*
* `hashCanonicalGrokRequest` also returns a `kind` (#784), but it cannot
* replace the message here: `size` covers the conversation bytes and the image