Correctness and contracts report · NVIDIA/hyperflare-inference #645

Raw Markdown for agents: https://autobot.eidonix.com/p/fc9aaa29-5788-4d3c-b918-8b28bfcb297d.md

Correctness, Contracts & System-Level Consequences — PR #645

PR: NVIDIA/hyperflare-inference#645 — "Overhaul Helios prefill scheduling, cost modeling, and two-frame pipelining", lukealonso, head 05cccb6, closes #485. 20 files, +1417/−127, single commit, CI green, no reviews yet.

I inspected the whole diff plus the direct callers/contracts in context (scheduler.rs, policy.rs, cost.rs, checkpoints.rs, service.rs, utility.rs, model.rs, execution/{transport,threaded,parallel}.rs, threaded/protocol*.rs, server/runtime/phase_tests.rs, engram.rs, rounds.rs, scripts/scheduling_sim/*, tests/test_scheduling_utility.py, docs/scheduling-runtime-design.md) and re-checked every citation below against the head tree.

Key findings

  1. Major — the O(1) checkpoint stride fast path is silently lost as soon as any partial-fill prefill sample exists (checkpoints.rs:222-232 × cost.rs:298-302). The regime #485 is about is precisely the one that disables it, contradicting the PR text and regressing #459/#550's budget.
  2. Major — the "conservative upward bound" is uncapped and the PR's own test encodes a 5.4× over-estimate of a full chunk (cost.rs:113-114; test asserts ≥ 42.3 s where the same test measures 7.81 s). Inflation feeds ValueRate::new, expected_finish_ns, window_remaining() and resize_prefill.
  3. Major — the new prefill durations collide with a hard submission-window gate, so the cost model can refuse the second frame of the very pipeline it was meant to enable (policy.rs:416-438 vs scheduler.rs:1132-1143, 2431-2434; magnitude documented by phase_tests.rs:1311-1318: 600 → ~200 ns for a 13-token tail).
  4. Major — coalescing_horizon_tokens (default 64.0) is a new always-on admission-ordering coefficient with no CLI flag, no server-config key and no row in the documented defaults table (policy.rs:26,42,228; docs/scheduling-runtime-design.md:651-661 verified to stop at adaptive_verification_alpha; flare-cli/src/cli.rs (not opened) and helios/src/server/config.rs (not opened) expose every sibling coefficient but not this one).
  5. Minor — value-side first_output now uses scheduled_consumed while service_rates still uses consumed_tokens, so the +1 token and the new coalescing bonus land on different chunks on the two sides of the price/value comparison (policy.rs:749-752 vs service.rs:168-187).
  6. Minor — an undeclared behaviour change in the Mixed decode branch (else if r.consumed_tokens >= r.prompt_tokens as u64 && r.generated_tokens > 0) removes Mixed decode candidates from partially-prefilled lanes that already hold generated tokens.
  7. Minor — the meaning of the exported prefill retained_ns silently changes to a fitted full-fill/zero-context extrapolation derived from only step.lanes.first() (cost.rs:693-724 → scheduler.rs:1145-1150, 2388-2391).
  8. Minor — the headline 8×8,192 burst result (+12.8%, TTFT 1492→1056 ms) has no checked-in workload; workloads.py:50-53 adds 4096-token bursts only.
  9. Minor — two-frame prefill widens the per-request failure blast radius: a failed chunk's error is only observed at completion (scheduler.rs:2746-2747), while the next chunk can already be in flight.
  10. Sound (no finding): the model.rs completion-input guard widening, four-layer executor parity plus prefill_step_requires_feedback, Engram staging double buffering, the learning::optimistic_tokens fix, and per-lane page reservation/counter validation under two in-flight frames.

F1 — Major: checkpoint O(1) stride fast path lost whenever any partial-fill sample exists

helios/src/scheduler/checkpoints.rs:222-232 (line 225 is a changed line):

        let stride = catalog
            .iter()
            .try_fold(None, |best, entry| {
                let nanos = entry.non_terminal?.constant_ns()?;

helios/src/scheduler/cost.rs:99-101:

    pub fn constant_ns(&self) -> Option<u64> {
        self.constant_nanos
    }

helios/src/scheduler/cost.rs:298-302:

        let constant_nanos = (best_theta[1] == 0.0 && best_theta[2] == 0.0 && u_max >= 0.75)
            .then_some(best_theta[0].round().clamp(1.0, u64::MAX as f64) as u64);

constant_nanos is Some only when the NNLS fit collapses to a pure constant term and the widest observed fill is at least 0.75 of capacity. One observation with u <= 0.5 (a short tail — the #485 workload) either makes theta1/theta2 nonzero or leaves u_max < 0.75; constant_ns() returns None; try_fold short-circuits to None; stride is disabled for that graph until the 30 s estimate_ttl_ns reset clears the strata (cost.rs:198-201).

Impact. Every checkpoint-interval pricing then falls back to the per-position walk at checkpoints.rs:270-339, which loops over the entire catalog for every chunk of every interval, called 2–3× per selection. This is the O(1) budget #459 introduced and #550 re-used, and the PR description says "Constant predictors retain exact u64 values (preserving checkpoints.rs's O(1) stride path and single-lookup budget)" — true only in the constant case, and false exactly in the tail-heavy regime this PR targets. The existing budget tests (checkpoints.rs:1305-1312, 2375-2378, 3485-3488, STRIDE_RUNS/ENTRY_LOOKUPS) only cover the all-constant case, so nothing catches it.

Fix. Don't gate the stride on a global constant. Keep an O(1) hoisted choice whenever the predictor is fill/context-invariant in the leading term, or hoist the cheapest capacity by evaluating predict() at the interval's boundary fills when it is monotone in u; then add a budget test asserting STRIDE_RUNS > 0 in a mixed fill/context regime.


F2 — Major: the "conservative upward bound" is uncapped; the checked-in test requires a 5.4× over-estimate

helios/src/scheduler/cost.rs:103-123:

    pub fn predict(&self, work: usize, start_position: u64) -> u64 {
        if let Some(nanos) = self.constant_nanos {
            return nanos;
        }
        let cap = self.capacity.max(1);
        let u = work.clamp(1, cap) as f64 / cap as f64;
        let h = u * (start_position as f64 / PREFILL_CTX_SCALE);
        let mut pred = self.theta[0] + self.theta[1] * u + self.theta[2] * h;
        // Conservative constant-throughput upward bound when only a narrow partial-fill
        // regime has been observed, preventing short tails from poisoning full-chunk cost.
        if self.u_max < 0.75 && (self.u_max - self.u_min) < 0.15 && u > self.u_max && self.u_max > 0.0 {
            pred = pred.max(self.t_at_umax * (u / self.u_max));
        }

The PR's test prefill_cost_model_prevents_tail_poisoning_and_tracks_fill_and_context:

        // Post-TTL reset with ONLY a single 128-token tail at 1.51 s: conservative upward
        // extrapolation must prevent 3584 full-chunk from looking cheaper than 4096 at 1.76 s.
        costs.advance_to(1_000_000_000 + ttl + 1, ttl);
        costs.observe(&step_for(3584, 128, 0), timing(1_510_000_000));
        assert_eq!(costs.prefill_duration(GraphKind::Prefill, 3584, 128, 0), Some(1_510_000_000));
        let guarded_full_3584 = costs.prefill_duration(GraphKind::Prefill, 3584, 3584, 0).unwrap();
        assert!(
            guarded_full_3584 >= 1_510_000_000 * 28 - 10_000_000,
            "single tail must not undercut full chunk: guarded={guarded_full_3584}"
        );

1.51 s × 28 = 42.3 s, while the same test earlier establishes the true full-chunk cost as 7.81 s. The bound is a pure token-linear extrapolation from a sample dominated by fixed overhead, is not capped, and stays in force until nine full-fill samples displace the stratum medians (PrefillBucket is 9-deep, cost.rs:139-171).

Impact. After any 30 s TTL expiry in a tail-heavy workload, the large prefill graph's duration is inflated ~5×. That duration is the denominator of ValueRate::new (utility.rs:124-134), so large-chunk prefill becomes unattractive and the scheduler prefers many short chunks — the round-robin thrashing change 1 exists to remove, now reintroduced by change 2. It also inflates expected_finish_ns (scheduler.rs:2431-2434) → window_remaining() → the queue window, and flows into resize_prefill/materialize, so reported plan durations are ~5× off.

Fix. Cap the extrapolation (a max_slowdown multiple, or bound by the best measured median of any stratum scaled by u/u_max); require a minimum sample count before the bound overrides the fit; and assert an upper bound in the test, not only a lower one.


F3 — Major: re-priced prefill durations can make the new two-frame prefill pipeline drain itself

helios/src/scheduler/policy.rs:416-438:

    pub fn submission_window_available(&self, duration_ns: u64) -> bool {
        self.submissions.len() < 2
            && !self.submissions.values().any(|s| s.requires_feedback)
            && (self.submissions.is_empty() || duration_ns > 0)
            && self.window_remaining().is_some()
    }

    pub(super) fn window_remaining(&self) -> Option<u64> {
        let Some((_, first)) = self.submissions.first_key_value() else {
            return Some(0);
        };
        if self.now_ns >= first.expected_finish_ns {
            return None;
        }

expected_finish_ns is the plan-time prediction (scheduler.rs:2431-2434), and this PR changes what that prediction is for prefill — its own phase test records a 3× shift (helios/src/server/runtime/phase_tests.rs:1311-1318):

        if kind == GraphKind::Prefill {
            // The 13-token tail (200 ns) inside capacity 64 (seeded 1000 ns at full fill)
            // fits its own fill-ratio regime instead of averaging into the full-chunk cost.
            let est = worker.scheduler.estimated_duration_ns(&step).unwrap();
            assert!((195..=210).contains(&est), "partial prefill estimate={est}");
        } else {
            assert_eq!(worker.scheduler.estimated_duration_ns(&step), Some(600));
        }

ActionCosts::get now routes every single-lane prefill step through prefill_duration (cost.rs:679-691), so this repeats for every short chunk.

Impact. Frame N+1 must be submitted before frame N completes (scheduler.rs:1132-1143, policy.rs:311-322). Under-estimated tails expire expected_finish_ns early, window_remaining() returns None (a hard refusal, not a soft signal), and both submission_window_available and commit (scheduler.rs:2348-2350, "in-flight execution requires completion feedback") refuse the second frame — a forced drain exactly on the short-tail chunks the PR wants to pipeline, i.e. a pipeline bubble sourced from the cost model, and head-of-line blocking for the plan loop under contention.

Fix. Separate the two uses of duration_ns: make window expiry soft (return Some(0) and let the executor's frame accounting be the only gate), or refresh expected_finish_ns from the last observed completion instead of the plan-time prediction, or floor the pipelining gate. Add an integration test that pipelines two short-tail chunks and asserts both submit without a feedback drain.


F4 — Major: new always-on coefficient with no flag, no config key and no defaults-table row

helios/src/scheduler/policy.rs:24-42:

    pub adaptive_verification_alpha: f64,
    ...
    pub coalescing_horizon_tokens: f64,
...
            adaptive_verification_alpha: 1.0,
            coalescing_horizon_tokens: 64.0,

Validated alongside the other prices at policy.rs:225-230 and consumed by coalescing_prefill_log_bonus (policy.rs:444-448, short-circuits on <= 0.0) via value.prefill_finish (policy.rs:610, utility.rs:88-95).

Verified: search_code for coalescing_horizon finds only policy.rs, policy_tests.rs (not opened), scripts/scheduling_sim/utility.py and one prose reference in docs/scheduling-runtime-design.md:202. There is no --scheduler-coalescing-horizon in flare-cli/src/cli.rs (not opened) and no scheduler_coalescing_horizon_tokens in helios/src/server/config.rs (not opened), while every sibling coefficient has one (cli.rs:647 (not opened),689,694, config.rs:321-326 (not opened), mtp_adaptive_verification_alpha). The canonical defaults table (docs/scheduling-runtime-design.md:651-661) lists ten fields and stops at adaptive_verification_alpha — the new field is absent, and helios/README.md (not opened) is untouched.

Impact. A global utility bonus that changes admission ordering for every prefill-capable core by default, with no opt-out and no operator-visible knob. This is the charter's "be explicit, pin everything, no magic defaults" requirement, and it makes a suspected scheduling regression non-bisectable without a rebuild. It is also a doc contract gap: the only place 64.0 appears is prose.

Fix. Add --scheduler-coalescing-horizon (cli) and scheduler_coalescing_horizon_tokens (server config) alongside the existing keys, and add the row to the PolicyConfig table plus helios/README.md (not opened).


F5 — Minor: two cursors across the value / service-price split for the first-output token

helios/src/scheduler/policy.rs:749-752 (changed):

                        value.prefill(
                            work,
                            r.scheduled_consumed + work as u64 == r.prompt_tokens as u64,
                        ),

also policy.rs:1225-1228, while the rate normalizer still uses the committed cursor (helios/src/scheduler/service.rs:168-187):

            let start = request.consumed_tokens as usize;
            ...
                let first_output = start + work == request.prompt_tokens;
            ...
                if let Some(ns) = self
                    .costs
                    .prefill_duration(kind, capacity, work, request.consumed_tokens)

Impact. With a second prefill frame in flight, scheduled_consumed > consumed_tokens, so the first-output token and now the whole prefill_finish bonus are credited on a different chunk on the value side than on the normalization side, while token_rate feeds ServicePrice::initial/rebase (utility.rs:29-35, policy.rs:670-681). Small in magnitude, but it is a silent inconsistency introduced by the cursor change. Fix. Thread Self::prefill_cursor(request)/scheduled_consumed through service_rates too, or keep the policy side on consumed_tokens.

F6 — Minor: undeclared narrowing of the Mixed decode branch

helios/src/scheduler/policy.rs (diff, next_progress mixed loop):

-            } else if r.generated_tokens > 0 {
+            } else if r.consumed_tokens >= r.prompt_tokens as u64 && r.generated_tokens > 0 {

A lane that already holds generated tokens but has not finished consuming its prompt (windowed/conditioned prefill resumption, resumed requests whose prompt extends past the reused prefix) no longer gets a Mixed decode continuation candidate at all. The description lists only the !prefill guard and the powered_curve/forecast_tokens switch. Probably correct, but unattributable for anyone bisecting a Mixed-graph regression. Fix. State it in the description and add a test that a partially-prefilled lane with generated tokens gets no Mixed decode candidate.

F7 — Minor: prefill retained_ns silently changes meaning

helios/src/scheduler/cost.rs:693-724:

            if let Some(model) = estimate.prefill.as_mut() {
                let (work, start_position) = step
                    .lanes
                    .first()
                    .map_or((step.token_capacity, 0), |lane| (lane.tokens, lane.start_position));
                estimate.nanos = model.observe(sample, work, start_position, fresh);

PrefillCostModel::observe ends with predictor.predict(self.capacity, 0) (cost.rs:215-217) — a fitted full-fill, zero-context value, not the sample or the median. That number is what observation()/selected_cost() export (scheduler.rs:1145-1150) into SubmittedTiming.retained_ns (scheduler.rs:2388-2391). Impact. Metrics/dashboards and #540-style staleness accounting now see, for prefill, a synthetic extrapolation that in the F2 regime is ~5× measured and, for a multi-lane prefill step, derives from only lanes.first(). Field meaning changed with no rename or doc change. Fix. Keep replays populated and export the raw median for prefill, or rename/annotate the field as predicted_full_fill_ns and document it.

F8 — Minor: an unreproducible headline number

Description: "8 × 8,192-token multi-chunk burst: 737.2 → 831.2 tok/s (+12.8%), max TTFT 1492.0 → 1056.0 ms (−29.2%)". scripts/scheduling_sim/workloads.py:50-53 adds only 4096-token bursts:

        "burst_four": [Request(f"b{i}", 4096, 256) for i in range(4)],
        "burst_eight": [Request(f"b{i}", 4096, 256) for i in range(8)],

Only the 4096 numbers are pinned (tests/test_scheduling_utility.py, assert max_ttft <= 528.0 + 1e-9, all(batch == 8 …)). Fix. Add an 8×8192 workload and assert it, or drop the row from the evidence table.

F9 — Minor: two-frame prefill widens per-lane failure blast radius

helios/src/execution/transport.rs:1018-1021 admits Prefill into the second frame (with the grammar/non-pipelinable guard at 1028-1040); scheduler.rs:2342-2350 admits two submissions for a non-feedback prefill plan. But a lane failure is only surfaced at completion (scheduler.rs:2746-2747, if record.status == 3 { request.error_code = … }), while completions are strictly ordered (scheduler.rs:2516-2518, "completion fence must match the oldest submitted step") and counters are validated against the planned cursor (scheduler.rs:2618-2651). Impact. A failed prefill chunk no longer prevents the next chunk of the same request from being enqueued and executed against a KV range the failed chunk never produced: wasted GPU work, plus a second frame that must still satisfy counter validation. This failure-ordering property did not exist for decode pipelining. Fix. In eligible() require error_code.is_none() and no earlier in-flight frame for the same handle, or document and test the drain-on-error behaviour with a two-frame prefill error fixture.


Verified sound (explicitly no finding)

Open questions / could not verify