Repository navigation
feat(dev): round-robin HA proxy on :8500 in run.py - #1389
Conversation
In HA mode run.py spawns N ncps instances on ports 8501.., but a Nix client can only point at one substituter URL, so exercising HA from a real client meant manually picking a single replica port. Add a stdlib round-robin reverse proxy bound to 127.0.0.1:8500 that is started automatically whenever --replicas > 1. It rotates each incoming request across the launched instances so successive requests (narinfo then NAR) land on different replicas, naturally exercising HA. Request and response bodies are streamed with a bounded buffer so large NAR transfers do not scale proxy memory with payload size; hop-by-hop headers are stripped and Host is pinned to the backend. A dead backend yields a 502 without taking down the proxy thread, and binding failure fails fast after tearing down the just-started instances. The proxy lifecycle is tied to run.py: it is stopped (port released) in cleanup() on SIGINT/SIGTERM, and its endpoint is recorded in var/ncps/state.json so test drivers can discover the single HA entry point. Single-instance runs are unaffected. Covered by dev-scripts/test_run_proxy.py (round-robin, header/body passthrough, PUT streaming, 502, lifecycle, state.json) and a live 2-instance redis+postgres smoke. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
This change is part of the following stack: Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR introduces a Python stdlib-only round-robin HTTP reverse proxy to ChangesHA Round-Robin Reverse Proxy Implementation
Sequence DiagramsequenceDiagram
participant Client
participant Proxy as Reverse Proxy<br/>pick_backend()
participant Backend1 as Instance 1<br/>Port N
participant Backend2 as Instance 2<br/>Port N+1
Client->>Proxy: HTTP GET /path
Proxy->>Proxy: increment counter (thread-safe)
Proxy->>Backend1: forward with Host set
Backend1->>Proxy: 200 OK + body
Proxy->>Client: strip hop-by-hop, return response
Client->>Proxy: HTTP PUT /path
Proxy->>Proxy: increment counter
Proxy->>Backend2: forward body stream
Backend2->>Proxy: 200 OK
Proxy->>Client: return response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces an in-process round-robin reverse proxy on port 8500 in dev-scripts/run.py to front multiple active instances when running in HA mode, allowing clients to target a single stable endpoint. It also adds comprehensive unit tests and design specifications. The review feedback correctly identifies two reliability issues in the proxy implementation: a potential connection leak during client disconnects and a thread crash due to unsafe parsing of the Content-Length header. A robust error-handling structure is suggested to address these issues.
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.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-10-run-py-ha-proxy/design.md (1)
36-36: 💤 Low valueMinor ambiguity: "the user selected round-robin"
This phrasing suggests an external request, but no prior context establishes who made this selection. Consider clarifying whether this refers to the PR author's design choice or an actual stakeholder requirement.
✏️ Suggested clarification
-- *Alternative — random.choice*: also valid but the user selected round-robin for deterministic rotation in tests. +- *Alternative — random.choice*: also valid but round-robin was chosen for deterministic rotation in tests.🤖 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-run-py-ha-proxy/design.md` at line 36, The phrase "the user selected round-robin" in the sentence mentioning "*Alternative — random.choice*: also valid but the user selected round-robin for deterministic rotation in tests." is ambiguous; update the wording to explicitly state who chose round-robin (e.g., "the PR author" or "this design") and why (deterministic rotation for tests). Specifically edit the sentence that references "random.choice" and "round-robin" to read something like "the PR author selected round-robin for deterministic rotation in tests" or "this design uses round-robin for deterministic rotation in tests" to remove ambiguity.
🤖 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 279-294: The code assumes Content-Length is numeric when computing
remaining = int(length_header) and will crash on malformed values; before
converting, validate or safely parse length_header (e.g., check .isdigit() or
wrap int(length_header) in try/except) and on failure handle it by sending a
proper 400 response or closing the request cleanly and logging the error; update
the block around the HTTPConnection creation and the use of
length_header/remaining (refer to variables length_header and remaining and the
surrounding proxy request handling logic) to perform the validation and error
handling so a bad Content-Length cannot raise an uncaught ValueError.
---
Nitpick comments:
In `@openspec/changes/archive/2026-06-10-run-py-ha-proxy/design.md`:
- Line 36: The phrase "the user selected round-robin" in the sentence mentioning
"*Alternative — random.choice*: also valid but the user selected round-robin for
deterministic rotation in tests." is ambiguous; update the wording to explicitly
state who chose round-robin (e.g., "the PR author" or "this design") and why
(deterministic rotation for tests). Specifically edit the sentence that
references "random.choice" and "round-robin" to read something like "the PR
author selected round-robin for deterministic rotation in tests" or "this design
uses round-robin for deterministic rotation in tests" to remove ambiguity.
🪄 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: ca17289b-aca2-4ab5-ad12-361a6cc406a4
📒 Files selected for processing (8)
dev-scripts/run.pydev-scripts/test_run_proxy.pyopenspec/changes/archive/2026-06-10-run-py-ha-proxy/.openspec.yamlopenspec/changes/archive/2026-06-10-run-py-ha-proxy/design.mdopenspec/changes/archive/2026-06-10-run-py-ha-proxy/proposal.mdopenspec/changes/archive/2026-06-10-run-py-ha-proxy/specs/dev-ha-proxy/spec.mdopenspec/changes/archive/2026-06-10-run-py-ha-proxy/tasks.mdopenspec/specs/dev-ha-proxy/spec.md
Address PR #1389 review feedback on the dev HA proxy: - Parse Content-Length defensively (CodeRabbit PRRT_kwDONV6tZs6Iki4g, Gemini PRRT_kwDONV6tZs6IkdrE): a non-numeric Content-Length now returns 400 instead of raising an uncaught ValueError that kills the request thread. - Guarantee backend connection cleanup (Gemini): wrap the request lifecycle in try/finally so conn.close() runs even if response forwarding raises, and swallow client-disconnect OSError during copyfileobj so an aborted client does not leak the backend connection. - Sanitize forwarded headers (CodeQL HTTP Response Splitting PRRT_kwDONV6tZs6Ikc_a / PRRT_kwDONV6tZs6Ikc_s): drop any request or response header whose name or value embeds CR/LF, closing the header-injection vector. Covered by a new raw-socket test asserting a malformed Content-Length yields 400. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
dev-scripts/test_run_proxy.py (1)
94-170: ⚡ Quick winConsider adding test coverage for header sanitization.
The commit messages mention CRLF header sanitization to prevent injection/response-splitting. While the implementation in
run.pyincludes_is_safe_header()checks, no test currently validates that headers containing\ror\nare dropped. Adding a test case (e.g., a stub backend that returns a header with embedded CRLF, asserting it's stripped from the client-visible response) would improve confidence in this security hardening.🤖 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/test_run_proxy.py` around lines 94 - 170, Add a new unit test in TestProxyForwarding that verifies CRLF-containing headers are dropped: create a stub via _start_stub that responds with a header value containing "\r\n" (e.g., "X-Inject: good\r\nInjected: yes"), register it with self._proxy([...]) and issue a request with _request(proxy, "GET", "/"); then assert the client-visible headers do NOT contain the injected header or any CR/LF sequences (and optionally assert the legitimate headers/body are still present). Reference _start_stub, _proxy, and _request to locate where to add this test.
🤖 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.
Nitpick comments:
In `@dev-scripts/test_run_proxy.py`:
- Around line 94-170: Add a new unit test in TestProxyForwarding that verifies
CRLF-containing headers are dropped: create a stub via _start_stub that responds
with a header value containing "\r\n" (e.g., "X-Inject: good\r\nInjected: yes"),
register it with self._proxy([...]) and issue a request with _request(proxy,
"GET", "/"); then assert the client-visible headers do NOT contain the injected
header or any CR/LF sequences (and optionally assert the legitimate headers/body
are still present). Reference _start_stub, _proxy, and _request to locate where
to add this test.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c1871e9b-4c62-47ef-a96b-6fee6b6b469f
📒 Files selected for processing (2)
dev-scripts/run.pydev-scripts/test_run_proxy.py
🚧 Files skipped from review as they are similar to previous changes (1)
- dev-scripts/run.py
## 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 - [x] 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). - [x] 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). - [x] `task fmt` clean · `task lint` 0 issues · `task test` all Go packages pass. --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Summary
dev-scripts/run.pyspawns N ncps instances on ports8501.., but a Nix client can only point at a single substituter URL. This adds a stdlib round-robin reverse proxy on127.0.0.1:8500that fronts all active instances so HA can be exercised from a real Nix client against one stable endpoint.--replicas > 1; single-instance runs are unaffected.Hostto the backend.502without killing the proxy thread; a bind failure on:8500fails fast after tearing down the just-started instances.run.py: stopped (port released) incleanup()on SIGINT/SIGTERM; endpoint recorded invar/ncps/state.jsonfor test-driver discovery.dev-ha-proxy(proposal/design/specs/tasks archived underopenspec/changes/archive/2026-06-10-run-py-ha-proxy/).Test plan
task fmtclean,task lint0 issues,task testall passdev-scripts/test_run_proxy.py(8 tests): round-robin + wrap-around, status/header/body passthrough, rotation across two backends, PUT body streaming, dead-backend 502, lifecycle port release, state.json proxy field present/absentnix-cache-info200, requests split 4/3 across:8501/:8502,state.jsonadvertised the proxy, SIGTERM cleanup released:8500and removedstate.json