Skip to content

feat(dev): round-robin HA proxy on :8500 in run.py - #1389

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/run-proxy
Jun 10, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/run-proxy

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

  • In HA mode dev-scripts/run.py spawns N ncps instances on ports 8501.., but a Nix client can only point at a single substituter URL. This adds a stdlib round-robin reverse proxy on 127.0.0.1:8500 that fronts all active instances so HA can be exercised from a real Nix client against one stable endpoint.
  • Auto-started only when --replicas > 1; single-instance runs are unaffected.
  • Rotates each request across instances (narinfo → NAR land on different replicas), streams request/response bodies with a bounded buffer (large NARs don't scale proxy memory), strips hop-by-hop headers and pins Host to the backend.
  • A dead backend yields 502 without killing the proxy thread; a bind failure on :8500 fails fast after tearing down the just-started instances.
  • Lifecycle tied to run.py: stopped (port released) in cleanup() on SIGINT/SIGTERM; endpoint recorded in var/ncps/state.json for test-driver discovery.
  • New capability spec dev-ha-proxy (proposal/design/specs/tasks archived under openspec/changes/archive/2026-06-10-run-py-ha-proxy/).

Test plan

  • task fmt clean, task lint 0 issues, task test all pass
  • dev-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/absent
  • Live 2-instance smoke (redis locker + postgres): proxy served nix-cache-info 200, requests split 4/3 across :8501/:8502, state.json advertised the proxy, SIGTERM cleanup released :8500 and removed state.json

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]>
@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.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added HA-mode round-robin reverse proxy on localhost:8500 for --replicas > 1, streaming requests/responses and recording the proxy endpoint in state.
  • Tests

    • Added comprehensive tests for backend rotation, request/response preservation, body forwarding, lifecycle (port release), and state-file behavior.
  • Bug Fixes / Reliability

    • Proxy returns 502 for unreachable backends and 400 for malformed requests; strips unsafe hop-by-hop headers.

Walkthrough

This PR introduces a Python stdlib-only round-robin HTTP reverse proxy to dev-scripts/run.py for HA-mode runs. When launched with --replicas > 1, the proxy listens on port 8500, routes requests across instance backends using thread-safe counter-based selection, streams bodies without buffering, strips hop-by-hop headers, and shuts down cleanly. The implementation includes comprehensive tests validating backend rotation, request/response forwarding, error handling, and state file integration.

Changes

HA Round-Robin Reverse Proxy Implementation

Layer / File(s) Summary
Core proxy implementation
dev-scripts/run.py
Introduces PROXY_PORT, proxy_servers list, and proxy handler functions (pick_backend, make_proxy_handler, _forwardable_request_headers, start_proxy) using only http.client, http.server, and threading to select backends round-robin per request, filter hop-by-hop headers, set the Host header, stream request/response bodies with bounded buffer, and return 502 on backend connection failures.
Proxy lifecycle integration
dev-scripts/run.py
Extends cleanup() to shut down and close tracked proxy servers; integrates proxy startup into main() when --replicas > 1 by building backend list, starting the proxy, and handling bind failures with instance/tmux cleanup; records the proxy endpoint into state.json under proxy field when successfully started.
Comprehensive test suite
dev-scripts/test_run_proxy.py
Validates backend round-robin selection with wraparound, request/response forwarding with status/headers/body preservation, PUT request body handling, 502 responses for unreachable backends, proxy port release on shutdown, and conditional proxy field presence in state files via stub backends and in-process test servers.
Specification and design documentation
openspec/changes/archive/2026-06-10-run-py-ha-proxy/, openspec/specs/dev-ha-proxy/spec.md
Documents proxy behavior (round-robin selection, streaming, lifecycle coupling, state discovery), design decisions (stdlib-only, in-process, daemon thread), non-goals (no TLS, no production load balancing), and task completion checklist.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

enhancement, size:L, merge-stack

Poem

🐰 Hop! Hop! The proxy springs to life,
Round-robin routing without strife,
Multiple replicas dance in grace,
Each request finds its destined place. 🔄

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.92% 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 PR title 'feat(dev): round-robin HA proxy on :8500 in run.py' is fully related to the main change. It clearly summarizes the primary feature addition—a round-robin HA proxy—and specifies where it operates (:8500 in run.py).
Description check ✅ Passed The PR description is comprehensive and directly related to the changeset. It explains the motivation (single stable endpoint for HA mode), key behaviors (round-robin routing, streaming, header handling, lifecycle integration), and test coverage.
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 dev-scripts/run.py Dismissed
Comment thread dev-scripts/run.py Dismissed
Comment thread dev-scripts/run.py Dismissed
Comment thread dev-scripts/run.py Dismissed
Comment thread dev-scripts/test_run_proxy.py Dismissed
Comment thread dev-scripts/test_run_proxy.py Dismissed
Comment thread dev-scripts/test_run_proxy.py Dismissed
Comment thread dev-scripts/test_run_proxy.py Dismissed
Comment thread dev-scripts/test_run_proxy.py Dismissed
Comment thread dev-scripts/test_run_proxy.py Dismissed
Comment thread dev-scripts/run.py Fixed
Comment thread dev-scripts/run.py Fixed

@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 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.

Comment thread dev-scripts/run.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: 1

🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-10-run-py-ha-proxy/design.md (1)

36-36: 💤 Low value

Minor 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f03901 and 1ffaac1.

📒 Files selected for processing (8)
  • dev-scripts/run.py
  • dev-scripts/test_run_proxy.py
  • openspec/changes/archive/2026-06-10-run-py-ha-proxy/.openspec.yaml
  • openspec/changes/archive/2026-06-10-run-py-ha-proxy/design.md
  • openspec/changes/archive/2026-06-10-run-py-ha-proxy/proposal.md
  • openspec/changes/archive/2026-06-10-run-py-ha-proxy/specs/dev-ha-proxy/spec.md
  • openspec/changes/archive/2026-06-10-run-py-ha-proxy/tasks.md
  • openspec/specs/dev-ha-proxy/spec.md

Comment thread dev-scripts/run.py Resolved
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]>
Comment thread dev-scripts/test_run_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.

🧹 Nitpick comments (1)
dev-scripts/test_run_proxy.py (1)

94-170: ⚡ Quick win

Consider adding test coverage for header sanitization.

The commit messages mention CRLF header sanitization to prevent injection/response-splitting. While the implementation in run.py includes _is_safe_header() checks, no test currently validates that headers containing \r or \n are 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ffaac1 and 2d3f76c.

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

@kalbasit
kalbasit merged commit 4673374 into main Jun 10, 2026
45 of 57 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/run-proxy branch June 10, 2026 18:23
kalbasit added a commit that referenced this pull request Jun 10, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants