Repository navigation
fix(router): eliminate SSE active_inflight leak and c=16..128 batch cliff (#3) - #22
Open
saariuslystoned wants to merge 33 commits into
Open
saariuslystoned wants to merge 33 commits into
saariuslystoned wants to merge 33 commits into
Conversation
…ty, failover, and metrics
…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
…config timeouts and telemetry parsing
… verbose logs, preserve stream flag
…lines, validate URL ports
…pe response-size errors, enforce SSE chunk deadlines, validate /v1/models
…size errors, stop retries on disconnect, allow same-origin POST
…ommit boundary, validate 2xx JSON bodies
…d model IDs, detect fixed-length SSE truncation
…stream, budget SSE buffers, preserve bind hostname
…-batch-cliff # Conflicts: # README.md
…across concurrency
…499 SSE outcomes, and Linux slow-client test
…loat parsing, and W8A8/mount docs
… playbook with exporter and dense presets
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Branched from
origin/feat/freetpu-router-v0(45a2381, PR #13 closed/unowned) to resolve the live Cloud TPUv6e-8serving throughput cliff andactive_inflightcounter leak surfaced in #3 / #15.Root Causes Found & Fixed
SSE
active_inflightCounter Leak & Keep-Alive Tail (router/freetpu_router.py):try:reservation window:try_reserve_backendran before enteringtry ... finally, leaving a window where exceptions/cancels could bypassrelease_backend. Replaced with RAII_BackendSlotLease(reserve_backend_lease) with idempotentrelease(), immediatetry ... finally, rollback oninc_inflightfailure, and__del__GC safety net.latency_ms: 5,604–6,010 ms/active_inflight: 24–26): UpstreamPOST/GETrequests omitted"Connection": "close"despite opening a freshHTTPConnectionper 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.c=8 -> c=16..128SSE Proxy Serialization Cliff (router/freetpu_router.py,router/tpu_telemetry.py,router/config.py):listen(5)TCP SYN backlog overflow:FreeTPURouterServer(ThreadingHTTPServer)inheritedrequest_queue_size = 5, causing SYN backoff stalls (4,089.5 mswall atc=128) under concurrent load; raisedrequest_queue_size = 1024andDEFAULT_MAX_CONCURRENT_CONNECTIONS = 512.disable_nagle_algorithm = True(TCP_NODELAY) on_RouterRequestHandlerclient sockets and setTCP_NODELAYon upstreamHTTPConnectionsockets.select()/settimeout()/ double-JSON / GIL thrash: Added non-blockingDeadlineSocketIOfast-path (settimeout(0.0)once, falling back toselectonly onBlockingIOError), single-pass SSE event processing (dictchecks instead ofMappingABC, singlejson.loadsfrombytes, delta fast-path after TTFT), and a single-threadselectors.DefaultSelector_SSEReactorpumping committed plain-TCP SSE streams (supporting bothConnection: close,Content-Length, andTransfer-Encoding: chunked) with zero per-chunk thread context switching.v6e-8High-Batch (c=64–128) & W8A8/W8A16 Presets:router/examples/cloud-tpu-v6e8-high-batch.json(max_concurrent_connections=512,queue_pressure_threshold=128,max_inflight=128).docs/router/vllm-tpu-v6e8-batch-scaling.mdand linked fromdocs/router/README.mdwith 256-aligned 2D static bucket matrix, persistent XLA cache setup, async scheduling (Qwen3-32B,Llama-3.3-70B), and native INT8 (W8A8/W8A16+gpt-oss-120bMOE_TC_PERMUTE=1) launch commands for the next owner-approvedv6e-8run.Before / After Benchmark Proof (Isolated Mock SSE Upstream)
64-token SSE stream (
2 msinter-token cadence) — Before (45a2381):ms/stepchunks/sc=1150.4 ms148.9 ms2.327 ms436.5c=8150.4 ms149.8 ms2.340 ms3,472.4c=16154.2 ms237.1 ms3.705 ms4,386.2c=64151.1 ms374.4 ms5.850 ms11,110.5c=128146.1 ms4,089.5 ms63.898 ms2,034.5128-token SSE stream (
2 msinter-token cadence) — After (41c4cf2):chunks/sactive_inflightc=1323.5 ms326.2 ms+0.021 ms3950c=8328.1 ms324.5 ms-0.028 ms3,1800c=16323.7 ms326.9 ms+0.025 ms6,3130c=64318.8 ms326.3 ms+0.059 ms25,3020c=128302.1 ms343.8 ms+0.326 ms48,0260Verification
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_pathstest_sse_concurrency_scaling_c1_to_c128_overhead_and_no_leakpython3 router/freetpu_router.py --check-configon all 3 configs inrouter/examples/→ Config OKclean-room-audit(.github/workflows/ci.yml) across 90 files → PASSED