Skip to content

fix(router): eliminate SSE active_inflight leak and c=16..128 batch cliff (#3) - #22

Open
saariuslystoned wants to merge 33 commits into
mainfrom
codex/router-sse-leak-batch-cliff
Open

saariuslystoned wants to merge 33 commits into
mainfrom
codex/router-sse-leak-batch-cliff

Conversation

@saariuslystoned

Copy link
Copy Markdown
Owner

Branched from origin/feat/freetpu-router-v0 (45a2381, PR #13 closed/unowned) to resolve the live Cloud TPU v6e-8 serving throughput cliff and active_inflight counter leak surfaced in #3 / #15.

Root Causes Found & Fixed

  1. SSE active_inflight Counter Leak & Keep-Alive Tail (router/freetpu_router.py):

    • Pre-try: reservation window: try_reserve_backend ran before entering try ... finally, leaving a window where exceptions/cancels could bypass release_backend. Replaced with RAII _BackendSlotLease (reserve_backend_lease) with idempotent release(), immediate try ... finally, rollback on inc_inflight failure, and __del__ GC safety net.
    • Upstream HTTP/1.1 keep-alive tail (latency_ms: 5,604–6,010 ms / active_inflight: 24–26): Upstream POST/GET requests omitted "Connection": "close" despite opening a fresh HTTPConnection per request, causing HTTP/1.1 upstreams (uvicorn/vLLM) to hold sockets open after generation. Added "Connection": "close" on upstream requests and verified immediate [DONE] exit and client disconnect propagation.
  2. c=8 -> c=16..128 SSE Proxy Serialization Cliff (router/freetpu_router.py, router/tpu_telemetry.py, router/config.py):

    • listen(5) TCP SYN backlog overflow: FreeTPURouterServer(ThreadingHTTPServer) inherited request_queue_size = 5, causing SYN backoff stalls (4,089.5 ms wall at c=128) under concurrent load; raised request_queue_size = 1024 and DEFAULT_MAX_CONCURRENT_CONNECTIONS = 512.
    • Nagle / Delayed-ACK stalls: Enabled disable_nagle_algorithm = True (TCP_NODELAY) on _RouterRequestHandler client sockets and set TCP_NODELAY on upstream HTTPConnection sockets.
    • Per-chunk select() / settimeout() / double-JSON / GIL thrash: Added non-blocking DeadlineSocketIO fast-path (settimeout(0.0) once, falling back to select only on BlockingIOError), single-pass SSE event processing (dict checks instead of Mapping ABC, single json.loads from bytes, delta fast-path after TTFT), and a single-thread selectors.DefaultSelector _SSEReactor pumping committed plain-TCP SSE streams (supporting both Connection: close, Content-Length, and Transfer-Encoding: chunked) with zero per-chunk thread context switching.
  3. v6e-8 High-Batch (c=64–128) & W8A8/W8A16 Presets:

Before / After Benchmark Proof (Isolated Mock SSE Upstream)

64-token SSE stream (2 ms inter-token cadence) — Before (45a2381):

Concurrency Direct Wall Router Wall Router ms/step Router chunks/s
c=1 150.4 ms 148.9 ms 2.327 ms 436.5
c=8 150.4 ms 149.8 ms 2.340 ms 3,472.4
c=16 154.2 ms 237.1 ms 3.705 ms 4,386.2
c=64 151.1 ms 374.4 ms 5.850 ms 11,110.5
c=128 146.1 ms 4,089.5 ms 63.898 ms 2,034.5

128-token SSE stream (2 ms inter-token cadence) — After (41c4cf2):

Concurrency Direct Wall Router Wall Overhead / Chunk Router chunks/s active_inflight
c=1 323.5 ms 326.2 ms +0.021 ms 395 0
c=8 328.1 ms 324.5 ms -0.028 ms 3,180 0
c=16 323.7 ms 326.9 ms +0.025 ms 6,313 0
c=64 318.8 ms 326.3 ms +0.059 ms 25,302 0
c=128 302.1 ms 343.8 ms +0.326 ms 48,026 0

Verification

  • python3 router/freetpu_router.py --self-test --verbose → 83/83 tests OK (18.814s), including new regression tests:
    • test_sse_active_inflight_zero_after_all_termination_paths
    • test_sse_concurrency_scaling_c1_to_c128_overhead_and_no_leak
  • python3 router/freetpu_router.py --check-config on all 3 configs in router/examples/ → Config OK
  • Repo clean-room-audit (.github/workflows/ci.yml) across 90 files → PASSED

…y SSE, auto-poll, and guard non-finite telemetry
…uncated SSE, refresh failover candidates, and reject zero-device TPU
…es, bound SSE reads incrementally, and guard non-loopback HTTP credentials
… add post-commit progress deadline, track latest timings, and discard unterminated EOF events
…allow OpenAI SDK CORS headers, finalize on [DONE], per-model RR LRU, and emit terminal failure usage
…pe response-size errors, enforce SSE chunk deadlines, validate /v1/models
…size errors, stop retries on disconnect, allow same-origin POST
…d model IDs, detect fixed-length SSE truncation
…stream, budget SSE buffers, preserve bind hostname
…499 SSE outcomes, and Linux slow-client test
…de, and respect RLIMIT_NOFILE in scaling test
…idate ASCII backend IDs, and clarify INT8 scheme
- Prune speculative Preset C (compressed-tensors W8A8) from Cloud TPU v6e-8
  playbook and router README, keeping verified BF16 Qwen3-32B and Llama-3.3-70B
  launch presets
- Accumulate bounded HTTP response/request/exporter bodies in contiguous
  bytearray() buffers and account for the temporary bytes(buf) copy in the
  shared response memory budget
- Return permanent HTTP 413 payload_too_large when a single request's estimated
  parse memory exceeds max_total_request_memory_bytes, reserving 503 for
  temporary concurrent contention
- Replace non-quote-aware Prometheus label-block regex with a quote-aware
  scanner so '}' and escaped quotes/backslashes inside label values preserve
  TPU health and duty-cycle samples
- Surface JSONL usage-record write failures via JsonlUsageMeterHook.write_errors,
  rate-limited stderr warnings, and the Prometheus counter
  freetpu_router_usage_meter_errors_total without disrupting inference
- Restrict unauthenticated /health probes under bearer auth to a minimal
  status-only payload ({'status': 'ok'|'degraded'}) while returning full
  backend details only when authenticated (or when bearer auth is disabled)
- Reject malformed or non-object JSON in pre-commit SSE data frames as
  retryable upstream protocol errors (502 + failover) instead of committing 200
- Count JSON object/array containers in _validate_json_structure and charge
  240 B/container + 64 B/separator in _estimate_json_parse_memory so dense
  parsed objects stay within the shared request/response memory budget
- Update v6e-8 playbook token bucket description to match vllm/vllm-tpu:v0.33.0
  default power-of-two num_tokens ladder (16..2048)
- Split Prometheus text exposition strictly on LF ('\n') in parse_prometheus_text
  so bare CR and Unicode U+2028/U+2029 inside quoted labels preserve samples
- Charge inbound request upload memory incrementally as bytes arrive in
  _read_request_body (plus temporary bytes(buf) copy budget) and reserve
  extra JSON parse memory only after the complete body arrives, preventing
  stalled uploads from starving concurrent inference requests
- Update Cloud TPU v6e-8 disk-backed XLA cache playbook option to supported
  Hyperdisk Balanced (hyperdisk-balanced) with auto-delete=no retention
- Add independent asyncio.wait_for batch deadline and finally writer cleanup
  to test_sse_concurrency_scaling_c1_to_c128_overhead_and_no_leak
- Recognize streamed choices[].delta.audio (non-empty data or transcript) as
  generated output in _sse_event_should_commit and post-commit progress
  tracking so audio-only streams commit and forward live without hitting the
  pre-commit cap or progress deadline
- Accumulate pre-commit SSE bytes in a single contiguous bytearray() instead of
  retaining per-line bytes objects and list entries so short keepalive lines
  stay strictly within the shared response memory budget
- Track stream_options.include_usage and treat close-delimited SSE EOF missing
  both [DONE] and the final usage chunk as truncated (502 + SSE error event)
- Support CR, LF, and CRLF SSE delimiters (including chunk-split CR/LF)
  consistently across pre-commit and post-commit SSE readers per WHATWG spec
- Validate required callable methods for auth, usage_meter, and scaler hooks
  during config loading (--check-config and startup) via validate_hook_for_role
- Stream-filter TPU exporter scrapes to known TPU metrics and bounded chip/line
  limits in O(1) memory instead of buffering and retaining all PromSample dicts
- Isolate inbound request JSON decoding/validation in
  _parse_inference_request_fields so decoded dicts and stream_options go out of
  scope before releasing the JSON parse memory reservation
- Mount a >=250 GiB Hyperdisk Balanced HF_HUB_CACHE volume in v6e-8 launch
  CONTAINER_FLAGS so 70B BF16 weights never overflow the 100 GiB TPU boot disk
- Count all observed TPU chips (tracked_chips) in total_chips so chips reporting
  HBM/duty-cycle without a health sample fail readiness when discovery is
  missing or undercounts
- Check max_samples <= 0 before parsing/appending in parse_prometheus_text so
  max_samples=0 returns an empty list
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.

1 participant