Skip to content

fix(dev): forward chunked request bodies in HA proxy - #1390

Merged
kalbasit merged 3 commits into
mainfrom
user/wnasreddine/fix-proxy
Jun 10, 2026
Merged

kalbasit merged 3 commits into
mainfrom
user/wnasreddine/fix-proxy

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

The dev HA round-robin reverse proxy in dev-scripts/run.py (PR #1389) silently dropped the body of any request sent with Transfer-Encoding: chunked. It only streamed the request body when a Content-Length header was present; chunked uploads (no Content-Length, and Transfer-Encoding stripped as hop-by-hop) skipped the body loop entirely, so the backend received a bodiless PUT and the unconsumed client body reset the connection — surfacing as curl error 56: Connection reset by peer and aborting the whole nix copy closure upload.

nix copy uploads NARs with chunked encoding because the on-the-fly-compressed .nar.zst size is unknown ahead of time, so large closures (e.g. a nixos-system) failed while small Content-Length NARs succeeded.

Diagnosis (proven)

Driving the real run.py proxy against a capture backend:

Framing Client sent Backend received
Content-Length 200000 200000 ✅
Transfer-Encoding: chunked 200000 0 ❌

Fix (dev-scripts/run.py only — ncps server untouched)

  • Detect chunked framing before the header is dropped; decode the client's chunked body and re-encode it chunked to the backend in bounded PROXY_BUFFER units (no whole-body buffering — proxy memory still does not scale with payload size).
  • Harden the error path: on backend failure, drain the unconsumed body and force the connection closed so the client gets a real 502 instead of a TCP reset.
  • Surface backend connect/forward failures via the log (previously log_message was a no-op), so dev upload failures are diagnosable.
  • Sync the dev-ha-proxy spec (chunked + Content-Length forwarding, 502-not-reset, error visibility) and archive the OpenSpec change.

Test plan

  • New regression test drives the real run.py proxy with both Content-Length and Transfer-Encoding: chunked PUTs; asserts full body reaches the backend in both, and unreachable backend → 502 (not reset).
  • Wired dev-scripts/run.py into the e2e-harness-unit flake check so the test runs in CI (nix build .#checks.x86_64-linux.e2e-harness-unit → 43 passed).
  • task fmt clean · task lint 0 issues · task test all Go packages pass.

The dev HA round-robin proxy in dev-scripts/run.py only streamed the
request body when a Content-Length header was present. A client using
Transfer-Encoding: chunked (e.g. nix copy uploading a NAR whose
on-the-fly-compressed .nar.zst size is unknown) had its body silently
dropped: Transfer-Encoding is hop-by-hop and was stripped, so the body
loop was skipped and the backend received a bodiless PUT. The unconsumed
client body then reset the connection, surfacing as curl error 56
(Connection reset by peer) and aborting the whole closure upload.

Detect chunked framing before the header is dropped, decode the chunked
body from the client and re-encode it chunked to the backend in bounded
PROXY_BUFFER units (no whole-body buffering, so proxy memory still does
not scale with payload size). Harden the error path so a backend failure
drains the unconsumed body and forces the connection closed, yielding a
real 502 instead of a reset. Surface backend connect/forward failures via
the log so dev upload failures are diagnosable.

Add a regression test that drives the real run.py proxy with both a
Content-Length and a Transfer-Encoding: chunked PUT, asserting the
backend receives the full body in both cases, and wire dev-scripts/run.py
into the e2e-harness-unit flake check so it runs in CI.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit

kalbasit commented Jun 10, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. bug Something isn't working labels Jun 10, 2026
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 52bcb2c2-c887-4099-baf2-4fd1ce7b50bc

📥 Commits

Reviewing files that changed from the base of the PR and between b44861f and 61f6f67.

📒 Files selected for processing (2)
  • dev-scripts/run.py
  • nix/e2e-tests/tests/test_dev_proxy.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • dev-scripts/run.py

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Proxy reliably forwards chunked request bodies end‑to‑end and tolerates malformed/truncated framing.
    • On backend/connect or forward failures the proxy drains/aborts remaining client body and returns HTTP 502 (clients no longer hang or see TCP resets).
  • Tests

    • Added regression tests covering fixed-length, chunked, and truncated uploads and unreachable-backend 502 behavior.
    • Test harness updated to run against the real proxy implementation.
  • Documentation

    • Added spec/design docs detailing streaming and error‑handling requirements.

Walkthrough

Fixes the dev HA reverse proxy to stream and forward client request bodies framed with Transfer-Encoding: chunked, adds bounded chunk parsing and drain-on-error to avoid client resets, includes regression tests for chunked and Content-Length uploads, and updates specs/docs and CI wiring.

Changes

Dev HA Proxy Chunked Body Forwarding and Tests

Layer / File(s) Summary
Chunked streaming exception and decoder
dev-scripts/run.py
ProxyBodyError exception and _stream_chunked_body(rfile, send) parse client chunk framing, validate hex sizes/CRLF, re-emit framed chunks to backend via bounded buffer, consume trailers, and raise on malformed/truncated input.
Error response and body drain helper
dev-scripts/run.py
Adds _drain_request_body and _fail helpers: mark connection for close, best-effort drain remaining fixed-length or chunked request body up to a cap, then send the intended HTTP error while tolerating I/O errors.
Chunked detection and forwarding implementation
dev-scripts/run.py
Detect Transfer-Encoding: chunked (take precedence over Content-Length), omit client Content-Length when forwarding, add Transfer-Encoding: chunked to backend headers, stream fixed-length or chunked bodies to backend, and convert parse/backend OSErrors into 502 via _fail.
Test backend and helpers
nix/e2e-tests/tests/test_dev_proxy.py
Module utilities: dynamic loader for dev-scripts/run.py, free-port helper, autouse fixture clearing capture state, _CaptureHandler that accepts Content-Length and chunked PUTs, threaded capture server starter, _put request helper, and PAYLOAD.
Regression tests for body forwarding and error handling
nix/e2e-tests/tests/test_dev_proxy.py
Tests: test_content_length_put_forwards_full_body, test_chunked_put_forwards_full_body, parametrized test_unreachable_backend_returns_502_not_reset, and test_truncated_content_length_body_returns_502_not_hang.
Test harness integration
nix/e2e-tests/flake-module.nix
e2e-harness-unit derivation copies real dev-scripts/run.py into the test working directory and sets NCPS_RUN_PY so regression tests run against the actual proxy implementation.
Specification and change documentation
openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/..., openspec/specs/...
Openspec metadata, design/proposal/tasks, and updated dev-ha-proxy spec requiring end-to-end streaming for both Content-Length and chunked request bodies, 502 on backend failures (no client resets), and logging of forwarding failures.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ProxyHandler
  participant _stream_chunked_body
  participant Backend
  Client->>ProxyHandler: PUT /upload ... Transfer-Encoding: chunked
  ProxyHandler->>_stream_chunked_body: read chunk-size line
  _stream_chunked_body->>_stream_chunked_body: parse hex size, validate CRLF
  _stream_chunked_body->>ProxyHandler: emit framed chunk bytes
  ProxyHandler->>Backend: forward chunked bytes (with Transfer-Encoding: chunked)
  alt backend connect/forward OK
    Backend-->>ProxyHandler: response (e.g., 204)
    ProxyHandler-->>Client: backend response
  else backend error / parse error
    ProxyHandler->>ProxyHandler: _fail -> drain remaining body, send 502
    ProxyHandler-->>Client: 502 Bad Gateway
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1389: Prior PR touching the HA reverse-proxy request-forwarding path; related to streaming and error-mapping logic.

Suggested labels

size:M

"A rabbit hops where bytes once bled,
Chunks now pass where fear had tread.
Trailers tucked and drains held tight,
No reset dawns — just HTTP right.
Gnaw on tests, and dance — all's sped."

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(dev): forward chunked request bodies in HA proxy' directly and accurately summarizes the main change: enabling the dev HA proxy to forward request bodies that use Transfer-Encoding: chunked, which was the core issue being fixed.
Description check ✅ Passed The description thoroughly explains the problem (chunked bodies being dropped), diagnosis (proven via test table), implementation details, and test plan—all directly related to the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request adds support for forwarding chunked request bodies in the development HA reverse proxy (dev-scripts/run.py) and introduces regression tests to verify full-body delivery and clean error handling. The review feedback suggests extending the _fail error path to also drain chunked request bodies to prevent connection resets, prioritizing chunked encoding over Content-Length when both headers are present to comply with RFC 7230, and parameterizing the unreachable backend test to cover both chunked and non-chunked request paths.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread dev-scripts/run.py Resolved
Comment thread dev-scripts/run.py Resolved
Comment thread dev-scripts/run.py Resolved
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.md (1)

12-12: 💤 Low value

Minor documentation discrepancy: task 2.2 vs. implementation structure.

Task 2.2 mentions extracting a _forward_request_body(conn) helper, but the implementation (dev-scripts/run.py lines 395-410) keeps the body-forwarding logic inline within _proxy() as two conditional branches (one for Content-Length, one for chunked). The logic is clear and well-organized, so this is a documentation variance rather than a defect. If future refactoring introduces more body-forwarding modes, extracting a dedicated helper would reduce complexity in _proxy().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.md` at
line 12, The tasks doc mentions extracting a `_forward_request_body(conn)`
helper but the code keeps body-forwarding inline inside `_proxy()` with two
branches; reconcile by either (A) updating the task entry to state that
`_proxy()` currently handles both `Content-Length` and `Transfer-Encoding:
chunked` inline, removing the expectation of a separate helper, or (B) implement
the helper `_forward_request_body(conn)` and move the two conditional branches
from `_proxy()` into that function (retain the existing behavior for
`Content-Length` loop and chunked handling). Reference the existing `_proxy()`
function and the intended `_forward_request_body(conn)` symbol when making the
change.
nix/e2e-tests/tests/test_dev_proxy.py (1)

72-82: ⚡ Quick win

Chunked decoder doesn't handle optional trailers.

After the zero-length terminator chunk, HTTP/1.1 allows optional trailer headers before the final CRLF. Line 79 reads only one line, assuming no trailers. The upstream proxy decoder (context snippet 1) loops until it finds a blank line. While current tests don't send trailers (_put line 104 sends 0\r\n\r\n), a future test or external client that does will cause the backend to mis-parse the body.

♻️ Align with upstream trailer handling
                 size = int(line.split(b";", 1)[0], 16)
                 if size == 0:
-                    self.rfile.readline()  # trailing CRLF after terminator
+                    # Consume optional trailers until blank line.
+                    while True:
+                        trailer = self.rfile.readline()
+                        if trailer in (b"\r\n", b"\n", b""):
+                            break
                     break
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nix/e2e-tests/tests/test_dev_proxy.py` around lines 72 - 82, The chunked
decoder in the block starting with "elif te and 'chunked' in te.lower()"
incorrectly reads a single line after the zero-length terminator and thus
ignores optional trailer headers; update the handling so that after detecting
size == 0 you loop reading lines from self.rfile until you encounter a blank
line (i.e., keep calling self.rfile.readline() and break only on an empty line),
ensuring any trailers are consumed before breaking and before returning/using
body.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@dev-scripts/run.py`:
- Around line 267-281: The chunked-body reader currently discards terminators
without validating them, allowing malformed data to slip through; update the
loop that consumes trailers and the per-chunk CRLF check to validate exact CRLF
sequences and raise ProxyBodyError on framing errors: when handling the
zero-sized chunk, require the following line(s) to be proper trailers terminated
by b"\r\n" (do not treat EOF as a valid blank line) and when consuming the CRLF
after each chunk (the rfile.readline() at the end of the per-chunk loop), verify
it equals b"\r\n" (or raise ProxyBodyError) instead of ignoring it; use the
existing variables rfile, send, PROXY_BUFFER and the ProxyBodyError exception to
implement these checks.
- Around line 326-347: ProxyHandler._fail currently reconstructs remaining from
self.headers["Content-Length"], which can over-drain because ProxyHandler._proxy
already decrements a local remaining while streaming; change the code so _proxy
passes the current unread byte count into _fail (e.g., call self._fail(code,
message, unread) or set self._unread_bytes before calling _fail) and then in
_fail use that unread value (falling back to Content-Length only if unread is
None) to bound the drain loop against self.rfile using PROXY_BUFFER; ensure the
drain loop decrements that unread counter and stops when it reaches zero to
avoid blocking or over-draining.

In `@nix/e2e-tests/tests/test_dev_proxy.py`:
- Line 61: The class-level mutable dict _CaptureHandler.received is causing test
state to leak across runs; convert it to an instance attribute by initializing
self.received in _CaptureHandler.__init__ (and update any references from
_CaptureHandler.received to instance.received), or alternatively add an autouse
pytest fixture that clears _CaptureHandler.received before each test (e.g., a
fixture named clear_capture_state that calls _CaptureHandler.received.clear());
choose one approach and update tests/handlers consistently to avoid shared
mutable state.

---

Nitpick comments:
In `@nix/e2e-tests/tests/test_dev_proxy.py`:
- Around line 72-82: The chunked decoder in the block starting with "elif te and
'chunked' in te.lower()" incorrectly reads a single line after the zero-length
terminator and thus ignores optional trailer headers; update the handling so
that after detecting size == 0 you loop reading lines from self.rfile until you
encounter a blank line (i.e., keep calling self.rfile.readline() and break only
on an empty line), ensuring any trailers are consumed before breaking and before
returning/using body.

In `@openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.md`:
- Line 12: The tasks doc mentions extracting a `_forward_request_body(conn)`
helper but the code keeps body-forwarding inline inside `_proxy()` with two
branches; reconcile by either (A) updating the task entry to state that
`_proxy()` currently handles both `Content-Length` and `Transfer-Encoding:
chunked` inline, removing the expectation of a separate helper, or (B) implement
the helper `_forward_request_body(conn)` and move the two conditional branches
from `_proxy()` into that function (retain the existing behavior for
`Content-Length` loop and chunked handling). Reference the existing `_proxy()`
function and the intended `_forward_request_body(conn)` symbol when making the
change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b5ae01d1-2835-4079-8990-e8fc4a9b9b92

📥 Commits

Reviewing files that changed from the base of the PR and between 4673374 and a40a2bc.

📒 Files selected for processing (9)
  • dev-scripts/run.py
  • nix/e2e-tests/flake-module.nix
  • nix/e2e-tests/tests/test_dev_proxy.py
  • openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/.openspec.yaml
  • openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/design.md
  • openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/proposal.md
  • openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/specs/dev-ha-proxy/spec.md
  • openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.md
  • openspec/specs/dev-ha-proxy/spec.md

Comment thread dev-scripts/run.py Resolved
Comment thread dev-scripts/run.py Resolved
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Resolved
Address review feedback on the HA-proxy chunked-body fix:

- RFC 7230 §3.3.3: when both Transfer-Encoding: chunked and
  Content-Length are present, chunked wins — ignore Content-Length and
  do not forward it to the backend (closes a request-smuggling vector).
- _fail() now drains the *unconsumed* body for both framings: thread the
  remaining fixed-length count from _proxy() (no over-drain/block when a
  failure happens mid-forward) and best-effort drain a chunked body so a
  backend failure on a chunked upload yields a clean 502 instead of a
  TCP reset (threads Ilh7H, Ilh7L, Ilh7W, Ill89).
- _stream_chunked_body() validates chunk terminators: raise
  ProxyBodyError on a truncated terminator or a missing per-chunk CRLF
  instead of silently accepting malformed framing (thread Ill8v).
- Test: parameterize the unreachable-backend 502 test over both
  Content-Length and chunked, and fix the capture backend's mutable
  class-attr state leak with an autouse reset fixture + ClassVar
  (threads Ilh7f, Ill9E).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
dev-scripts/run.py (1)

257-275: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Bound the chunk-size and trailer lines too.

_stream_chunked_body() is still using unbounded readline(), so a client can send a multi-megabyte chunk-size or trailer line and make the proxy buffer it in memory before any PROXY_BUFFER chunking kicks in. That breaks the bounded-streaming guarantee this change is trying to add. Please cap these line reads and reject overlong framing; the same guard should be mirrored in the chunked branch of _drain_request_body() too.

Suggested direction
+MAX_CHUNK_LINE = 8 * 1024
+
 def _stream_chunked_body(rfile, send):
     while True:
-        size_line = rfile.readline()
+        size_line = rfile.readline(MAX_CHUNK_LINE + 1)
         if not size_line:
             raise ProxyBodyError("client closed before chunked terminator")
+        if len(size_line) > MAX_CHUNK_LINE and not size_line.endswith(b"\n"):
+            raise ProxyBodyError("chunk header too long")
         token = size_line.split(b";", 1)[0].strip()
         ...
         if size == 0:
             while True:
-                trailer = rfile.readline()
+                trailer = rfile.readline(MAX_CHUNK_LINE + 1)
                 if trailer == b"":
                     raise ProxyBodyError("truncated chunked terminator")
+                if len(trailer) > MAX_CHUNK_LINE and not trailer.endswith(b"\n"):
+                    raise ProxyBodyError("chunk trailer too long")
                 if trailer in (b"\r\n", b"\n"):
                     break
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@dev-scripts/run.py` around lines 257 - 275, _stream_chunked_body() (and the
chunked branch in _drain_request_body()) currently calls rfile.readline()
without a limit, allowing a client to send arbitrarily long chunk-size or
trailer lines and break the bounded-streaming guarantee; fix by calling
rfile.readline(max_line_len) with a defined max (e.g. PROXY_MAX_LINE or
PROXY_MAX_CHUNK_HEADER) for the chunk-size and trailer reads, detect when the
returned line does not end with a newline or exceeds the limit and raise
ProxyBodyError (with an appropriate message like "chunk size line too long" or
"truncated chunked terminator") to reject overlong framing, and apply the same
limited-read logic to the chunked branch inside _drain_request_body() so both
places enforce the same bounds.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@dev-scripts/run.py`:
- Around line 341-380: The current drain logic (drain_fixed, drain_cap, and the
chunked-loop using self.rfile.read()/readline()) can block indefinitely; wrap
the whole draining phase in a short temporary timeout so _fail() can proceed to
send_error() on timeout—e.g. set a small socket timeout on the underlying socket
(or use select/poll) before running drain_fixed/loop and restore the original
timeout afterwards, and break out of all draining loops when a timeout occurs;
ensure the timeout handling catches the timeout exception and stops further
reads so send_error() is invoked.
- Around line 451-457: The read loop that forwards a known Content-Length can
silently break on an empty read, causing the backend to hang; modify the loop in
the request handler where content_length/cl_remaining are used so that if
self.rfile.read(...) returns b"" you raise ProxyBodyError (or the existing
ProxyBodyError exception type) instead of break; ensure this happens inside the
loop before decrementing cl_remaining and that the exception propagates to the
existing 502 error path used by conn.getresponse().

---

Outside diff comments:
In `@dev-scripts/run.py`:
- Around line 257-275: _stream_chunked_body() (and the chunked branch in
_drain_request_body()) currently calls rfile.readline() without a limit,
allowing a client to send arbitrarily long chunk-size or trailer lines and break
the bounded-streaming guarantee; fix by calling rfile.readline(max_line_len)
with a defined max (e.g. PROXY_MAX_LINE or PROXY_MAX_CHUNK_HEADER) for the
chunk-size and trailer reads, detect when the returned line does not end with a
newline or exceeds the limit and raise ProxyBodyError (with an appropriate
message like "chunk size line too long" or "truncated chunked terminator") to
reject overlong framing, and apply the same limited-read logic to the chunked
branch inside _drain_request_body() so both places enforce the same bounds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9df03199-8e0a-4a4c-888d-e6e60c5e1ff6

📥 Commits

Reviewing files that changed from the base of the PR and between a40a2bc and b44861f.

📒 Files selected for processing (2)
  • dev-scripts/run.py
  • nix/e2e-tests/tests/test_dev_proxy.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • nix/e2e-tests/tests/test_dev_proxy.py

Comment thread dev-scripts/run.py Resolved
Comment thread dev-scripts/run.py Resolved
Address CodeRabbit incremental-review findings:

- _fail() now wraps the body drain in a short (0.25s) socket timeout and
  restores the prior timeout afterward, so a client that stalls mid-upload
  cannot block in rfile.read()/readline() and starve the 502 (thread
  IlzlS).
- The fixed-length forward loop raises ProxyBodyError on a short read
  instead of breaking: the backend was already told to expect the full
  Content-Length, so breaking would hang conn.getresponse(); routing to
  the 502 path avoids the hang (thread IlzlY).
- Add a regression test: a client that declares a Content-Length but
  closes early gets a 502 (asserted via raw socket, with a client-side
  timeout so a regression fails fast instead of hanging).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
Comment thread nix/e2e-tests/tests/test_dev_proxy.py Dismissed
@kalbasit
kalbasit merged commit e192674 into main Jun 10, 2026
45 of 57 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-proxy branch June 10, 2026 19:23
kalbasit added a commit that referenced this pull request Jun 10, 2026
## Summary

A **second, distinct** dev-harness bug from the chunked-body fix in
#1390 (which is necessary and stays). After #1390, `nix copy` of a large
closure (e.g. a ~9.35 GB `nixos-system`) to the `:8500` HA proxy
**still** intermittently fails with `curl error 56: Connection reset by
peer`, aborting the whole copy on the first reset.

**Root cause:** the proxy's `ProxyHandler` left `protocol_version` at
the stdlib `BaseHTTPRequestHandler` default of **HTTP/1.0**, so it
force-closed every client connection after one request. `nix copy`
pushes hundreds of objects over a small pool of HTTP/1.1 keep-alive
connections; because the proxy refused keep-alive, nix was forced to
open a brand-new TCP connection per object — thousands for a multi-GB
closure. Under that churn (amplified by the default listen backlog of 5
and a ~1 s-per-PUT stall from unanswered `Expect: 100-continue`), the
accept loop stalls and intermittently nix's upload connection is reset
**before the proxy ever handles it** (`curl error 56`).

**Reproduced & fix-validated** on a clean isolated ncps behind the real
proxy: the unpatched proxy dies at PUT #2; the patched proxy completes
**3,488 PUTs with 0 resets**. `curl -v` confirms `HTTP/1.1 200` +
"Connection left intact" (reuse).

## What changed (`dev-scripts/run.py` proxy only; ncps unchanged)

- `ProxyHandler.protocol_version = "HTTP/1.1"` — persistent, reused
client connections; also makes `BaseHTTPRequestHandler` auto-answer
`Expect: 100-continue`, removing the per-PUT stall.
- Response framing for safe reuse: preserve `Content-Length`; treat
`204`/`304`/`HEAD`/`1xx` as bodiless; send `Connection: close` when the
body length is unknown (e.g. backend chunked, stripped as hop-by-hop) so
the client reads to EOF instead of mis-framing the next response.
- Raise the listener backlog (`request_queue_size`) above the stdlib
default of 5, set before the socket is activated.
- All #1390 hardening preserved (chunked request-body forwarding, RFC
7230 §3.3.3, bounded `_fail` drain, error logging).

## Test plan

- [x] `task fmt` (0 changed), `task lint` (0 issues), `task test` (all
Go packages ok)
- [x] New keep-alive / framing / `Expect: 100-continue` regression tests
drive the real `run.py` proxy via `NCPS_RUN_PY`; confirmed RED on
HTTP/1.0, GREEN after the fix
- [x] `e2e-harness-unit` nix check green (52 passed; +4 new tests)
- [x] End-to-end: full `nix copy` of the 9.35 GB closure through the
patched proxy — 3,488 PUTs, 0 resets

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants