Review: PR #634 "Measure streaming latency after scheduler idle periods" — Correctness, Contracts & System-Level Consequences
Reviewed at head a0467e2 (base main, branched at 0a8c20f). Single file changed: scripts/benchmark_scheduler.py (+21/−4). Nothing in the diff touches Rust, the scheduler, caches, locks, or wire contracts.
Key findings
- Blocker-class relevance gap (reported as Major, because it is a tool and not a runtime defect): the burst cannot reach the funded-refresh episode it exists to observe. The wakeup the PR targets requires (a) a cost stale beyond
estimate_ttl_ns = 30_000_000_000and (b) a differing, previously-executed stale cost key. The PR's own evidence run (">= 100 ms") is ~300× below the TTL, and a homogeneous burst only ever executes the ordinary shape, which the selection filter explicitly excludes. The flag therefore silently measures ordinary service while the PR text frames it as the #540 qualification case. - The headline new field measures the client's own sleep, not latency.
idle_seconds_before_burstis a lower-bound assertion ontime.sleep; it cannot fail by construction and contains no response time. The genuine post-pause first-token number already exists asttft_median_seconds. - The pause is neither gated on nor measured from server quiescence, and the recorded window is contaminated by two blocking
/metricsscrapes that occur before the sleep starts. - The counter that would prove an episode occurred is fetched twice per trial and never parsed, so no row distinguishes a post-idle wakeup from ordinary service.
- Client-side correctness is otherwise sound: no runtime behavior change, continuous mode is behavior-identical, validation fails loudly, no new dependency, no platform parity gap. The gaps are claim accuracy and evidence, not safety.
1. Correctness, Safety & Platform Parity
Finding 1.1 — idle_seconds_before_burst is a pause self-check that cannot fail (Major)
scripts/benchmark_scheduler.py:223-228
pause_started = time.perf_counter()
time.sleep(args.idle_seconds)
result = trial(args.base_url, bodies[:concurrency], None,
requests_per_lane=args.requests_per_lane or 1)
result['idle_seconds_before_burst'] = min(
row['started'] for row in result['rows']) - pause_started
row['started'] is captured inside request() before the POST is issued, at scripts/benchmark_scheduler.py:25-29:
def request(url, body, stream=False, path="/v1/chat/completions"):
client = connection(url)
start = time.perf_counter()
try:
client.request('POST', path, json.dumps(body),
Impact. Because pause_started precedes time.sleep(args.idle_seconds), the field is always >= --idle-seconds and grows only with client-side stalls (thread-pool start, barrier release, DNS/connect). It contains no server time and no response time; for a local server it reads ≈ the flag value. It cannot detect a slow wakeup, a still-busy server, or a failed pause — there is no failure mode it can report. Meanwhile the metric that actually answers "first-token latency after a pause" already exists in the same row: ttft_median_seconds (:162, :169, built from row['groups'][0]['seconds'], measured from start at :40). The PR never names it, so an operator reading the description will attribute the latency claim to the wrong key.
Fix. Either rename the field to something that states what it is (e.g. pause_duration_observed_seconds), or keep it and add the real number — the data is already in rows: first_token_after_idle_seconds = min(row['groups'][0]['seconds'] for row in rows) - pause_started. Then name ttft_median_seconds in the description as the idle-latency metric. This is also the metric/rate span check for the new field: the sampled span is sleep + client dispatch, not pause → first token.
Finding 1.2 — Idle mode silently changes the span and type of two existing JSONL keys (Minor)
The burst call passes duration=None (:225), which flows into trial()'s emission at scripts/benchmark_scheduler.py:164-165:
return {'concurrency': len(bodies), 'issue_duration_seconds': duration, 'elapsed_seconds': elapsed,
'requests': len(rows), 'generated_tokens': tokens, 'tokens_per_second': tokens / elapsed,
Impact. Under --idle-seconds: issue_duration_seconds is always JSON null (on main it was always a float), and tokens_per_second divides by burst length rather than the --seconds window — with default --output-tokens 256 and one request per lane it reports roughly 256 / burst_seconds instead of a steady-state decode rate. Same key names, different quantities across modes, undocumented in the PR description. No in-repo consumer parses these keys (searching the repo finds them only here), so this is a latent schema trap for anyone joining a continuous run and a burst run on tokens_per_second.
Fix. Emit the burst rate under a distinct key (burst_tokens_per_second) or set tokens_per_second to None in burst mode, and either omit or rename issue_duration_seconds when duration is None.
Finding 1.3 — --requests-per-lane is a sequential count, not a concurrent burst (Minor)
scripts/benchmark_scheduler.py:147-151
while (len(results) < requests_per_lane if requests_per_lane is not None
else time.perf_counter() < deadline[0]):
row = request(url, body, stream=True)
row['lane'] = lane
results.append(row)
request() is fully synchronous per lane, so request k+1 starts only after request k's stream ends. With --requests-per-lane 3 the driver issues one concurrent round of len(bodies) requests and then two serialized follow-ups per lane. Only round one is "traffic returning after an idle period"; rounds 2..N are continuous same-lane traffic. elapsed/tokens_per_second (:159, :165) span all rounds. The help text at :189-190 ("Requests per lane in each idle-mode burst (default: 1)") reads as a concurrent burst.
Fix. State the sequential-round semantics in the help text, or make the count per round so operators can separate round 1 (post-idle) from steady state.
Areas verified sound (no findings)
- No runtime interaction. The diff is client-only; no scheduler, cache, memory, lock, or allocation path changes, so no new contention, buffering, or failure-propagation surface.
- Continuous mode is behavior-identical.
--idle-secondsdefaults toNone(:187); theif args.idle_seconds is Nonebranch (:220-221) is the original call;deadline[0] = start + (duration or 0)(:156) is unchanged for any positive--seconds(default 120 at:184). An explicit--seconds 0also behaves as onmain(0 or 0 == 0), so theor 0is aNoneguard, not a defect. - Validation is loud and correct:
:198-199rejects non-finite or<= 0idle;:200-201rejects--requests-per-lanewithout--idle-secondsand values< 1.mathwas already imported (:11), so no new dependency. - No empty-sequence hazard:
min(row['started'] for row in result['rows'])(:227-228) runs on non-emptyrowsbecause each lane issues at least one request (requests_per_lane or 1at:226, validated>= 1) andrequest()raises on an incomplete stream (:60-64). --reuse-requestsstill works: it reads only the first JSONL line'srequests(:204-205), unaffected by the new key, and the configuration dump at:214uses**vars(args), soidle_seconds/requests_per_laneare recorded automatically and old files stay readable.- No cross-platform parity gap:
time.perf_counter()andtime.sleeponly; no Unix-specific API.
2. Unintended System-Level Consequences (and the concurrency the tool claims to model)
Finding 2.1 — The burst cannot reach the funded-refresh episode the PR exists to observe (Major; symptom is silent false confidence)
The PR's own justification is the post-idle wakeup retained by #540, described in docs/scheduling-runtime-design.md:460-466:
The allowance bounds aggregate expense with one nonpreemptible episode overrun;
it does not cap individual decode stalls. Funding the first refresh requires
2,495 ms of cumulative credited ordinary execution, accumulated across
idle-separated requests because idle intervals add neither credit nor ordinary
duration. When full credit carries across an idle gap longer than the freshness
lifetime, the first waking request can execute one refresh episode before
negative debt suppresses further probes.
Traced preconditions in the runtime:
- Staleness threshold is 30 s.
helios/src/scheduler/policy.rs:38estimate_ttl_ns: 30_000_000_000,with the test athelios/src/scheduler/cost.rs:100-101:fn fresh(&self, now_ns: u64, ttl_ns: u64) -> bool { self.nanos != 0 && now_ns.saturating_sub(self.observed_at_ns) < ttl_ns - The refresh target must be a different, previously observed, now-stale key.
helios/src/scheduler/policy.rs:1238-1240:
andif self.refresh_ready() { let mut targets: Vec<_> = self.costs.stale_keys().filter(|key| *key != ordinary.cost_key()) .map(|key| (self.costs.refresh_order(key), key)).collect();stale_keysyields only keys with a real observation,helios/src/scheduler/cost.rs:271-274:pub fn stale_keys(&self) -> impl Iterator<Item = Key> + '_ { self.entries.iter().filter(|(_, estimate)| estimate.nanos != 0 && !estimate.fresh(self.now_ns, self.ttl_ns)).map(|(key, _)| *key) - Credit is the cheap prerequisite, not the blocker.
helios/src/scheduler/refresh.rs:9-10(CREDIT_CAP_NS = 5_000_000.0,INCOME_RATE = 0.002 / 0.998) fills 5 ms of credit after ~2,495 ms of ordinary execution, which the default--warmup-seconds 30(:185) per concurrency already supplies.
Impact. Two independent reasons the tool cannot see what it claims to:
- The PR's evidence run — "The second burst began at least 100 ms after the preceding streams drained" — is 300× below
estimate_ttl_ns, so no cost is stale and no episode is possible in that configuration. Nothing in the CLI help (:187-190), the validation (:198-201), or the description says--idle-secondsmust exceed the core's freshness lifetime. - Even with a very long pause, a homogeneous run (identical bodies, one
--prompt-tokens, samemax_tokens) only ever executes the ordinary winner shape;stale_keys()then yields that single key, whichpolicy.rs:1239filters out, leavingtargetsempty. The in-repo analogue sets up a second shape first —helios/src/scheduler/policy_tests.rs:6253-6284poisons a stalePrefill(8192)and says to serve sequential 64,000-token prompts separated by idle gaps — exactly what this driver has no flag for.
Fix. Document the reachability contract in the CLI help and the PR description: --idle-seconds must exceed estimate_ttl_ns (30 s) for any staleness to occur, and the run must first serve a different shape (e.g. a different --prompt-tokens/--concurrency pass) so a differing stale key exists. Better: add an explicit precondition note plus a warning when --idle-seconds <= 30, and re-run the Evidence section in that regime so the claim "isolates streaming behavior when traffic returns after an idle period" is backed by a row that actually could contain a refresh.
Finding 2.2 — The pause is not gated on, nor measured from, server quiescence; the window is contaminated by two blocking /metrics scrapes (Major)
scripts/benchmark_scheduler.py:222-228
else:
pause_started = time.perf_counter()
time.sleep(args.idle_seconds)
result = trial(args.base_url, bodies[:concurrency], None,
requests_per_lane=args.requests_per_lane or 1)
result['idle_seconds_before_burst'] = min(
row['started'] for row in result['rows']) - pause_started
The pause begins after the previous trial() returns, and trial() performs a blocking scrape on entry (:141 before_metrics = metrics(url)) and again inside the returned dict (:174 'metrics_before': before_metrics, 'metrics_after': metrics(url),). So the server-visible idle window is --idle-seconds + two HTTP scrapes + thread-pool teardown/join (:153-158), i.e. strictly longer than the flag, and the recorded idle_seconds_before_burst describes neither the server gap nor the stimulus that produced the latency.
Nothing verifies the server is actually parked. The runtime parks only when nothing is outstanding — helios/src/server/runtime.rs:1236-1251:
if !progress {
if executor.outstanding() > 0 {
if !executor.park() { std::hint::spin_loop(); }
thread::yield_now();
} else {
self.scheduler.assert_idle()?;
let wait = self.idle_wait();
match self.receiver.recv_timeout(wait) {
and idle_wait() returns 50 µs while inbound_in_flight > 0 or inbound_waiting > 0 (:1257-1265), 100 µs when requests await the pool (:1267-1276). Because the client returns as soon as [DONE] arrives (:42-44, :57-58), the server may still be retiring or snapshotting when the sleep starts.
Impact. The stimulus is unverified and the recorded value cannot be correlated with the observed latency: a "post-idle" row may be a burst against a server that never parked, and a run cannot prove the opposite. The tool has the data it needs available and unused: the same /metrics text already fetched carries flare_active_requests and flare_pending_requests (helios/src/server/metrics.rs:1255 "Physical model slots with a live request", :1300 "Requests waiting inside the model scheduler, excluding its ingress channel").
Fix. Before the measured sleep, poll /metrics (bounded by a timeout that errors loudly) until pending == 0 && active == 0, record the dwell time from that confirmed quiescence as the idle duration, and record the polled quiescence point in the row. Also move both scrapes out of the window (or record their timestamps) so idle_seconds_before_burst describes the real gap.
Finding 2.3 — The probe-episode counter is fetched and never parsed, so no row can prove a refresh happened (Major; evidence/claim accuracy)
helios/src/server/metrics.rs:931-938 exposes exactly the counter that would prove the case was reached:
for (name, help, counts) in [
("execution_nanoseconds_total", "Raw execution time by scheduler selection reason, including readiness stalls and isolated host handoff.", &self.scheduler_trace.execution_ns),
("executions_total", "Completed physical executions by scheduler selection reason; each generation round counts once.", &self.scheduler_trace.executions),
] {
let _ = writeln!(text, "# HELP flare_scheduler_{name} {help}\n# TYPE flare_scheduler_{name} counter");
for (reason, count) in ["ordinary", "discovery", "timing_refresh", "acceptance_learning"].into_iter().zip(counts) {
timing_refresh corresponds to PlanOrigin::RefreshStart (the probe episode) at helios/src/scheduler/refresh.rs:13-23.
The script fetches this text twice per trial and stores it as an opaque string (:141, :174), emits it verbatim in the JSONL row (:233), and never parses or asserts on it.
Impact. A reviewer or operator must hand-diff two Prometheus blobs to know whether the burst contained a post-idle wakeup. Without that, the PR's central claim — that this mode measures the post-idle funded-refresh case — cannot be distinguished from a burst that measured ordinary service, which is precisely the ambiguity that makes Findings 2.1 and 2.2 harmful rather than merely incomplete.
Fix. Parse flare_scheduler_executions_total{reason="timing_refresh"} and {reason="acceptance_learning"} (plus the matching execution_nanoseconds_total) from metrics_before/metrics_after, emit the per-trial delta as a row field, and fail or warn when a run intended to observe the post-idle episode records zero refreshes.
3. Architecture, Contracts & Charter Compliance
Finding 3.1 — The only maintainer-side authorization (docs/TODO.txt:110-114) is neither referenced nor advanced, and the layer is in tension with AGENTS.md (Minor)
docs/TODO.txt:110-114
[ ] Qualify retained graph costs and funded remeasurement in live Helios:
idle/resume, concurrent decode latency, cost-change recovery, and queued
generation transitions. Use per-fence scheduler traces and request
latency measurements; measure GPU replay, queueing, and host planning separately.
See scheduling-runtime-design.md#funded-timing-refresh.
The entry names four cases; the burst mode addresses only the first, and only its client-observed half — it does not touch "per-fence scheduler traces", and its elapsed_seconds/tokens_per_second cannot "measure GPU replay, queueing, and host planning separately". Leaving the box unchecked is correct (no measurement was produced), but neither the PR text nor docs/ points a future reader at the new flags, so the tool is undiscoverable from the TODO that justifies it.
Layer tension, AGENTS.md:9-13:
operator-tuning fixtures, numerical references, qualification drivers, and
model test suites live in
[local-inference-lab/hyperflare-recipes](https://github.com/local-inference-lab/hyperflare-recipes),
A live-server qualification capability is being added to core Flare's scripts/. Mitigating: AGENTS.md:24-25 describes scripts/ as holding "scheduling simulator and utility scripts", and the TODO being served is itself a core-Flare TODO — so the placement is defensible. The decision should hinge on that TODO linkage, which the PR should state explicitly.
Positive on contracts: no wire/proto/captured-graph/CLI-default change; --idle-seconds is opt-in with default None (:187), so no global behavior change and no owner-sign-off gate under AGENTS.md captured-graph rules is triggered. The only externally visible contract is the JSONL key set (Finding 1.2).
Charter: the PR claims no speedup, so "performance PRs need benchmarks showing an actual speedup over main" is not triggered, and the Evidence section correctly separates what ran from what did not ("Native GPU serving, scheduler idle transitions, and latency gains were not measured."). The fit problem is the "What gets merged" bar — no issue, roadmap item, bug, or doc; the TODO is the whole case, and the PR's own evidence leaves the TODO's substance unmeasured.
Finding 3.2 — Test coverage: the new branches are exercised by no automated check (Minor)
Nothing imports this script (repo-wide search for benchmark_scheduler returns no matches outside the file itself), and CI runs pytest tests/ only, so the --idle-seconds path, the new validation, and idle_seconds_before_burst have no ordering or regression test. The pattern for testing a script in-repo already exists (tests/preparation/test_setup_preparation.py:15-18 loads and calls scripts/setup_preparation.py (not opened)). A ~20-line test asserting that (a) --requests-per-lane without --idle-seconds errors, (b) non-finite/negative --idle-seconds errors, and (c) a burst row carries idle_seconds_before_burst >= idle_seconds against a stub server would lock the contract cheaply.
4. Claim accuracy against the diff
| PR text | Verdict |
|---|---|
| "the driver waits after previous streams drain" | Not established. The pause starts after trial() returns, which includes two blocking /metrics scrapes (:141, :174), and no client or server check verifies drain/parking (helios/src/server/runtime.rs:1236-1251). |
| "issues a fixed number of requests per concurrency lane" | Partly. It counts completed synchronous requests per lane (:147-151); only round one is post-idle concurrent traffic. |
| "Each JSONL trial records the observed interval from the start of the pause to the first request" | Literally true, but it is a self-check on the client's own sleep, always >= --idle-seconds (Finding 1.1). |
| "continuous mode remains the default" | Verified (:187, :220-221). |
| "compare first-token latency and SSE delivery gaps after a pause" | Achievable, via the pre-existing ttft_median_seconds (:169) and burst_gap_median/p99_seconds (:170-171) — neither named in the description, and the new field is presented under a latency-sounding name. |
| "The second burst began at least 100 ms after the preceding streams drained" | Verified as written, but 100 ms is ~300× below estimate_ttl_ns (30 s), the threshold for the episode the PR exists to observe (Finding 2.1). |
| "Native GPU serving, scheduler idle transitions, and latency gains were not measured." | Accurate and appropriate. |
| Silent differences not disclosed | issue_duration_seconds → null and tokens_per_second span change (Finding 1.2). |
Open questions / could not verify
- The stub SSE server and any sample JSONL rows are not attached, so the new field's realized values (and its
>= --idle-secondsbehavior in practice) are unverified even in the author's smoke test. - Whether
a0467e2carries aSigned-off-bytrailer (CONTRIBUTING.md:19(not opened)) could not be confirmed — the commit body is not viewable with the available tools. - Nothing in the repository states whether
scripts/benchmark_scheduler.pyis currently pointed at real deployments, so the practical reach of the two new flags is unknown. - No behavior was checked for combined edge cases (
--trials 0,--warmup-seconds 0,--concurrency 1with a small--requests-per-lane); the code paths look benign (warmup stays deadline-mode even under--idle-seconds,:217-218) but are untested.
Bottom line
The client-side code is safe: no runtime change, no lock or allocation surface, continuous mode untouched, validation loud, no new dependency, no platform gap. What does not hold up is the purpose: idle_seconds_before_burst measures the client's sleep rather than the server's wakeup, the pause is neither gated on nor measured from quiescence, no row proves a timing_refresh episode occurred, and by construction — estimate_ttl_ns = 30 s plus the stale_keys().filter(|key| *key != ordinary.cost_key()) requirement — the documented burst configuration cannot reach the #540 case it cites. The fix is small and keeps the PR useful: parse the existing /metrics scrapes for flare_active_requests/flare_pending_requests and flare_scheduler_executions_total{reason="timing_refresh"}, emit the true first_token_after_idle_seconds from row['groups'][0]['seconds'], document that a qualifying run needs an idle longer than 30 s plus a second previously-served shape, and reference docs/TODO.txt:110-114.