Skip to content

helios/scheduler: price first-output waiting age on incumbent decode rounds - #663

Merged
lukealonso merged 1 commit into
NVIDIA:mainfrom
yatesdr:feat/knob-free-first-output-scheduling
Dec 1, 2026
Merged

lukealonso merged 1 commit into
NVIDIA:mainfrom
yatesdr:feat/knob-free-first-output-scheduling

Conversation

@yatesdr

@yatesdr yatesdr commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Under --scheduler-policy balanced (decode_age_price = 0.1), active decoding streams accumulate waiting-age utility scaled by their batch-feasible excluded wait while prompts waiting for their first output accumulate none. On models without mixed prefill-decode graphs, a newly arrived or returning prompt competing against 8–16 active decoders stalls for multiple seconds until its token-service fairness price climbs high enough to displace a full-batch decode round. When an interior conversation-anchor checkpoint splits a single-chunk prompt into a main chunk, boundary snapshot, and short tail, progress resets waiting state and service price drops on the first chunk, forcing the short tail to wait a second time.

This PR derives from and consolidates the returning-prompt investigation in #654 (co-authored with @logprobz) into a zero-knob formulation inside Helios's shared scheduler.

What changed

Before: Waiting prompts competed only through useful token progress, token-service fairness price, and zero-age coalescing surplus; they carried no first-output waiting-age credit, and progress on a forced interior anchor split always reset waiting state.

After (zero new CLI flags, config fields, model branches, graph kinds, Protobuf changes, or ServicePrice exemptions):

  • helios/src/scheduler/service.rs: Extended delivery-reference selection with delivery_references_and_decode_batch, returning the fastest pure incumbent Decode or Speculative round's work-time b_served * T_dec (excluding Mixed graphs; 0.0 when no measured decoder is active). For fixed-width packed speculative rounds (--mtp-adaptive-verification), each measured packed shape's token budget is evaluated directly so feasible batch capacity and per-slot delivery references are exact and slot-order invariant under heterogeneous verification lengths.
  • helios/src/scheduler/utility.rs, helios/src/scheduler/policy.rs: Added LaneValue::first_output_value and LaneValue::prefill_within. When decode_age_price > 0.0 and b_served * T_dec > 0.0, each waiting prompt with max_new_tokens > 0 receives:
    first_output_credit = decode_age_price * (b_served * T_dec) * A_first * frac
    
    where frac = 1.0 on prompt completion and frac = work / initial_prefill on non-finishing chunks. decode_age_price * unit is applied after computing the shared log-scale to prevent premature overflow or inf * 0 = NaN under large finite prices. Waiting prompts are omitted from the common -T/2 * sum c_j penalty sum, and the credit flows through prerequisite and two-stage continuation scoring (Init, Restore, Vision, Snapshot).
  • helios/src/scheduler.rs, helios/src/server/runtime.rs: Tracked RequestAccounting::first_output_wait_ns. Preserved it across a prefill stopped at an armed interior RetentionRole::Anchor cut when the prompt otherwise fit in one eligible prefill graph (including when the anchor coincides with the chosen chunk capacity or when a TerminalPrefill chunk clears deferred_prefill while landing on an interior anchor), while continuing to charge all measured token service truthfully in observe_service. Folded readmitted_output_ns: Option<u64> into set_arrival so admission timestamp assignment has no call-order hazard. Carried Carried::last_output_ns across preemption and forced-reasoning readmission, recording host-published forced-close timestamps when close_reasoning advances publications and taking the latest of graph and host publication timestamps.
  • scripts/scheduling_sim/utility.py, tests, docs: Mirrored the pure-decode formula in UtilityScheduler, added Rust and Python unit tests covering inertness, b_served * T_dec scaling, Mixed exclusion, packed speculative feasibility and slot-order invariance, large finite decode_age_price overflow/NaN safety, anchor-vs-message cut boundaries, multi-chunk TerminalPrefill deferred-state anchor preservation, pipelined prefill projection, forced-reasoning-close readmission (with and without prior graph publication), balanced burst coalescing, and oversubscribed/small-batch stress bounds, and reconciled docs/scheduling-theory.md, docs/scheduling-utility.md, and docs/scheduling-runtime-design.md.

Claimed benefit

Eliminates multi-second returning-prompt and prefill stalls behind active decode cohorts under --scheduler-policy balanced with zero configuration knobs, exact parity on standalone prefill/decode and --scheduler-policy throughput, and bounded behavior under oversubscribed (K > B) and small-batch (B = 1) bursts.

Policy trade-off for maintainer sign-off: Enabling this default-ON under --scheduler-policy balanced (decode_age_price = 0.1) trades higher background decode p99 gaps under heavy returning-prompt bursts (see tables below) for 3–6× lower returning-prompt TTFT and +65% to +136% higher closed-loop agent throughput (with --scheduler-policy throughput remaining 100% inert).

Supporting evidence & limitations

1. Paired zero-re-export SM121 flare run A/B — DeepSeek-V4.1-Flash-1017 TP4 (4× DGX Spark GB10, 0 errors)

Workload (policy, extra_work) Metric Base (a3c80e19) PR #663 Delta
Returning agent + K=8 bg (balanced, 0.05) Ret. TTFT p50 ∥ p95/max 2,812 ∥ 3,392 ms 1,025 ∥ 1,197 ms -63.5% ∥ -64.7%
Closed-loop turns/min ∥ bg gap p95/p99 13.21 ∥ 168.1 / 334.1 ms 21.77 ∥ 151.0 / 328.3 ms +64.8% ∥ improved
Returning agent + K=16 bg (balanced, 0.05) Ret. TTFT p50 ∥ p95/max 5,265 ∥ 5,667 ms 894 ∥ 1,117 ms -83.0% (5.9×) ∥ -80.3%
Closed-loop turns/min ∥ bg gap p95/p99 8.75 ∥ 211.1 / 368.4 ms 18.00 ∥ 184.0 / 463.5 ms +105.7% ∥ -12.8% / +25.8%
C=12 simultaneous burst (balanced, 0.05) TTFT p50 ∥ max ∥ wall ∥ gap p99 5,524 ∥ 7,177 ms ∥ 14.77 s ∥ 183.9 ms 5,018 ∥ 5,416 ms ∥ 14.43 s ∥ 158.3 ms -9.2% ∥ -24.5% ∥ -2.3% ∥ -13.9%
Returning agent + K=16 unsplit (balanced, 0.0) Ret. TTFT p50 ∥ turns/min 4,656 ms ∥ 10.12 3,427 ms ∥ 11.72 -26.4% ∥ +15.8%
K=16 throughput control (throughput, 0.05) Ret. TTFT p50 ∥ turns/min ∥ gap p99 3,659 ms ∥ 10.01 ∥ 385.9 ms 3,540 ms ∥ 9.82 ∥ 378.1 ms Parity

2. Paired 4-visit ABAB returning-agent suite from #654 (DeepSeek-V4.1-Flash-1017 TP4, 4× DGX Spark GB10, balanced, 0 invalid steps)

Workload (K) Metric Base (stock1+2) PR #663 (treat1+2) Notes
closed (K=16, 8×8 agents, 60 s) Valid turns (turns/min) ∥ TTFT p50 ∥ step_cost 73 (36.5/m) ∥ 6,493 ms ∥ 0.840 127 (63.5/m, +74%) ∥ 1,933 ms ∥ 0.611 6/6 gates passed (matched_p95: 9.24 → 5.48 s, -27% bg cost/step)
cold (K=0, 5 prompts) Finish ∥ TTFT p95 7.23 s ∥ 6.86 s 6.92 s ∥ 6.55 s 4/4 gates passed
single (K=16, 1 return) TTFT p50 ∥ p95 3,301 ∥ 3,467 ms 590 ∥ 602 ms (-82%) Visit 1: 5/5 gates (9,885 vs 10,062 inc tok, gaps 177/266/383 vs 175/265/368 ms); visit 2 hit a global ~16% ring slowdown across all workloads
sustained (K=16, 12 short + 1× 28K) Valid ∥ matched comp p95 24/26 ∥ 12.33 s 26/26 ∥ 7.64 s (-38%) Base timed out the 28K return on both visits (24/26); #663 completed all 26/26 (short return TTFTs 7.3–11.3 s → 1.6–3.9 s, visit 1 inc tok 6,426 → 6,832)
burst (K=16, 5 simultaneous returns) TTFT p50 ∥ gap p95 ∥ p99 ∥ max 6,381 ∥ 252 ∥ 376 ∥ 426 ms 1,668 ∥ 233 ∥ 493 ∥ 995 ms Real trade-off: 5 lockstep returning prompts clear together (-74% TTFT, improved gap_p95, visit 1 inc tok 9,043 → 9,429), raising p99/max single gap

3. Paired zero-re-export SM121 flare run A/B — Qwen3.8-Flash-Next TP2 (2× DGX Spark GB10, hybrid Mamba/GatedDeltaNet + Attention, 0 errors)

Workload (policy) Metric Base (a3c80e19) PR #663 Delta
Standalone prefill 8K / 32K (balanced) Prompt tok/s 3,635–3,687 / 3,731–3,736 3,641–3,690 / 3,737–3,739 +0.1% (parity)
Batched decode C=1..32 (256 tok, balanced) Agg wall tok/s (C=1 / 4 / 8 / 16 / 32) 55.6 / 127.7 / 186.0 / 254.0 / 331.0 54.3 / 129.6 / 198.1 / 256.3 / 345.0 Parity to +6.5%
45 s fixed-window return + K=16 bg (balanced) Ret. TTFT p50 ∥ turns (turns/min) 4,324 ms ∥ 9 (11.99/m) 868 ms ∥ 22 (28.30/m) -79.9% (5.0×) ∥ +136%
Streamed BG throughput ∥ gap p99 237.1 ch/s ∥ 334.5 ms 234.1 ch/s ∥ 410.5 ms -1.3% (parity) ∥ +76 ms
Long cold (3× ~14K) + K=12 bg (balanced) Max cold TTFT ∥ bg throughput ∥ gap p99 37.4 s ∥ 150.4 ch/s ∥ 1,192.8 ms 35.9 s ∥ 147.4 ch/s ∥ 1,190.7 ms -4.2% ∥ parity ∥ parity
35 s throughput control (K=16) Ret. TTFT p50 ∥ turns ∥ bg throughput 2,540 ms ∥ 10 ∥ 263.1 ch/s 2,539 ms ∥ 10 ∥ 266.4 ch/s Exact parity
GPU A/B reproduction commands and workload parameters
  1. Build binaries (a3c80e19 base vs PR branch):
    cargo build --locked --release --manifest-path flare-cli/Cargo.toml --features roce
  2. DeepSeek-V4.1-Flash-1017 TP4 (4× DGX Spark GB10, RoCE ring, zero re-export):
    # Rank 0..3 launch (same core on both arms; --scheduler-policy balanced or throughput):
    flare run <deepseek-v4.1-flash-1017-tp4.core> \
      --gpus 0 --ranks <4-node-roce-ring> --rank <r> \
      --scheduler-policy balanced --max-concurrency 32 --mtp-draft-tokens 7 \
      --embedding-table-storage ram --port 8000
    • Table 1 workloads: OpenAI /v1/chat/completions streaming client (temperature=0.0, seed 42): K ∈ {8, 16} continuous background decoders (max_tokens=1024, ~300-token unique prompts) paired with a sequential 12-turn returning agent (~2.2K cached prefix + ~204 new tokens per turn, max_tokens=64, 0.25s inter-turn pause); plus C=12 simultaneous burst (~1K prompt, max_tokens=128). Unsplit run sets [scheduler] checkpoint_extra_work_fraction = 0.0 in config.
    • Table 2 workloads: Exact Add opt-in first-output age pricing and returning-agent benchmark #654 scripts (benchmark_ready_prefill.py + analyze_ready_prefill.py) in alternating ABAB order (stock1 -> treat1 -> stock2 -> treat2):
      python3 benchmark_ready_prefill.py --base-url http://127.0.0.1:8000 --corpus <corpus.json> \
        --pattern <single|burst|sustained|closed|cold> --decoders <16|0> \
        --horizon <30|60> [--agents 8 --chain 8 --tool-delay 0.5] --out <visit>/<pattern>.jsonl
      python3 analyze_ready_prefill.py --baseline stock1 stock2 --variant treat1 treat2
  3. Qwen3.8-Flash-Next TP2 (2× DGX Spark GB10, RoCE ring, zero re-export):
    flare run <qwen3.8-flash-next-tp2.core> \
      --gpus 0 --ranks <2-node-roce-ring> --rank <r> \
      --scheduler-policy <balanced|throughput> --max-concurrency 32 \
      --mtp-draft-tokens 5 --embedding-table-storage ram --port 8000
    • Table 3 workloads: OpenAI /v1/chat/completions streaming (temperature=0.0): standalone prefill (8K, 32K, max_tokens=1, 2 reps), batched decode (C ∈ {1, 4, 8, 16, 32}, max_tokens=256), 45 s fixed-window returning agent (~2.5K base + ~200 tok/turn, max_tokens=64) beside K=16 continuous background decoders counting streamed chunks live inside [t0, t0+45s], 3× ~14K cold prompts beside K=12 decoders, and 35 s throughput control at K=16.

4. Automated verification (5bf90854)

  • Rust (--release, Linux): helios (runtime-core,server lib: 1,783 passed), flare (253 passed), flare-cli (241 passed, --test-threads=1), heliopause cargo check (0 new warnings).
  • Python & simulator: pytest tests/test_scheduling*.py (830 passed). At age_price = 0.0, scheduling_sim produces 21/21 identical traces vs baseline. Under balanced (age_price = 0.1), max TTFT and makespan improve on burst_eight, burst_eight_8k, and sixteen_prefills, with expected increases in max_output_gap_ms (374 → 440, 300 → 440, 440 → 572 ms) and decode_age_area_ms2 (+16% to +94%) relative to baseline.
  • TLA+ lifecycle conformance (verification/helios-lifecycle/check.py, TLA+ 1.7.4): 10/10 TLC models, 8/8 observed Rust trace checks (594,065 transitions), 12/12 auxiliary conformance tests passed.
  • Unrun / external checks: Gated template tests requiring FLARE_TEST_TEMPLATE_DIR (blocked locally by HTTP 401 on gated Hugging Face repo in prepare_templates.py), native-serving.yml, lifecycle --mutations, and kani proofs were not run locally. Independent SM120 (4× RTX PRO 6000 Blackwell, --mtp-adaptive-verification) results solo and stacked with #660 + #661 were reported by @FujitsuPolycom in the comments below.

Discord: D-Rock

@flare-autobot flare-autobot added area:scheduling Request scheduling, fairness, batching, and speculative-width selection. enhancement New feature or request performance Performance, latency, throughput, or memory-efficiency investigation or improvement. labels Dec 1, 2026
@yatesdr
yatesdr force-pushed the feat/knob-free-first-output-scheduling branch 2 times, most recently from e29725b to a5c3697 Compare December 1, 2026 20:55
@yatesdr
yatesdr marked this pull request as ready for review December 1, 2026 21:07
@yatesdr

yatesdr commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Additional served GPU A/B: Qwen3.8-Flash-Next TP2 (2× DGX Spark GB10, hybrid Mamba/GatedDeltaNet + Attention)

Paired zero-re-export flare run A/B (--max-concurrency 32 --mtp-draft-tokens 5 --embedding-table-storage ram, 0 errors, 0 new flags) comparing origin/main (a3c80e19) vs a5c36978 to verify no regression on regular prefill/decode work, unbiased fixed-window streamed background decode throughput, and long cold prompt contention on a second model architecture:

1. Regular standalone prefill & batched decode (--scheduler-policy balanced)

Workload Metric Base (a3c80e19) Treatment (a5c36978) Delta
Standalone prefill 8K (2 reps) prompt tok/s (ttft) 3,634.7 / 3,687.2 (2.32 / 2.17 s) 3,641.0 / 3,690.4 (2.32 / 2.17 s) +0.1% (parity)
Standalone prefill 32K (2 reps) prompt tok/s (ttft) 3,736.3 / 3,731.2 (8.78 / 8.79 s) 3,738.6 / 3,737.4 (8.77 / 8.78 s) +0.1% (parity)
Batched decode C=1 (256 tok) agg wall tok/s (wall) 55.6 (4.61 s) 54.3 (4.72 s) -2.3% (noise)
Batched decode C=4 (256 tok) agg wall tok/s (wall) 127.7 (8.02 s) 129.6 (7.90 s) +1.5%
Batched decode C=8 (256 tok) agg wall tok/s (wall) 186.0 (11.01 s) 198.1 (10.34 s) +6.5%
Batched decode C=16 (256 tok) agg wall tok/s (wall) 254.0 (16.13 s) 256.3 (15.98 s) +0.9%
Batched decode C=32 (256 tok) agg wall tok/s (wall) 331.0 (24.75 s) 345.0 (23.74 s) +4.2%

2. Fixed-window mixed contention & throughput control

All streamed background chunks are counted in real time inside an identical wall-clock window (no end-of-window cancellation truncation):

Workload (policy) Metric Base (a3c80e19) Treatment (a5c36978) Delta
45 s fixed-window returning agent + K=16 bg decoders (balanced) Ret. TTFT p50 ∥ mean ∥ p95 4,324 ∥ 4,440 ∥ 4,789 ms 868 ∥ 1,011 ∥ 1,576 ms -79.9% (5.0×) ∥ -77.2% ∥ -67.1%
Cold Turn-0 TTFT (~2.5K tok) 10,048 ms 5,032 ms -49.9% (2.0×)
Agent turns completed (turns/min) 9 (11.99) 22 (28.30) +136.0% (2.36×)
Streamed BG decode throughput 237.1 chunks/s 234.1 chunks/s -1.3% (parity)
BG decode gap p99 ∥ max 334.5 ∥ 511.6 ms 410.5 ∥ 662.6 ms +76 ms ∥ +151 ms
Long cold prompts (3× ~14K) + K=12 bg decoders (balanced) Cold TTFTs (max) [37.4, 29.1, 35.9 s] (37.4 s) [35.9, 25.2, 34.0 s] (35.9 s) -4.2% max (-13.5% min)
Streamed BG decode throughput 150.4 chunks/s 147.4 chunks/s -2.0% (parity)
BG decode gap p99 ∥ max 1,192.8 ∥ 1,906.7 ms 1,190.7 ∥ 2,004.5 ms -0.2% p99 (parity)
35 s fixed-window returning agent + K=16 bg decoders (throughput) Ret. TTFT p50 ∥ turns 2,540 ms ∥ 10 (15.93/m) 2,539 ms ∥ 10 (15.83/m) -0.05% (exact parity)
Streamed BG throughput ∥ gap p99 263.1 ch/s ∥ 345.4 ms 266.4 ch/s ∥ 355.1 ms Parity

Discord: D-Rock

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 663.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added duplicate This issue or pull request already exists triage:design-review Needs a maintainer scope, architecture, or contract decision before implementation or integration. labels Dec 1, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The core formulation (decode_age_price * (b_served * T_dec) * age_ms * frac) is clean, well-bounded and single-threaded, with strong paired GPU A/B evidence on two architectures — but it ships a behavior change into the default --scheduler-policy balanced while explicitly contradicting unchanged normative text and without maintainer sign-off resolving #663 vs competing opt-in #654.

  • Blockers: 1 · Should fix: 3 · Subtract/Simplify: 5 · Nits: 2
Walkthrough
  • helios/src/scheduler/service.rs: Extended delivery_references into delivery_references_and_decode_batch (:69-183), keeping delivery_references as a .0 wrapper (:59-64) and returning the fastest decode cohort work-time b_served * T_dec in stream-ms (0.0 when no measured decoder is active).
  • helios/src/scheduler/utility.rs & policy.rs: Added RequestAccounting::first_output_wait_ns (policy.rs:59), set_first_output_wait (:271-281), fits_single_prefill_from (:442-464), and LaneValue::first_output_value / prefill_within (utility.rs:90-111). In lane_values (:729-752), waiting prompts with consumed_tokens < prompt_tokens, max_new_tokens > 0, decode_age_price > 0.0 and incumbent_decode_batch_ms > 0.0 earn scaled decode_age_price * incumbent_decode_batch_ms * age_ms (projected across queued prefill submissions, excluded from the common -T/2 * sum(age_price) sum, threaded through next_progress and lane_value_for_tokens_within).
  • helios/src/scheduler.rs & helios/src/server/runtime.rs: Extracted LiveRequest::initial_prefill_tokens() (:351-355); preserved first_output_wait_ns across forced interior RetentionRole::Anchor splits on single-graph-fitting prompts (:2681-2702, :2791-2793) while still charging ServicePrice truthfully; carried Carried::last_output_ns across parking and readmission (runtime.rs:429, :1575-1577, :2456-2498).
  • scripts/scheduling_sim/utility.py, tests & docs: Added the credit formula to UtilityScheduler (utility.py:158-162, :251-270), four Rust unit tests (policy_tests.rs:6957-7138) and one Python test (tests/test_scheduling_utility.py:404-424), reworked burst-coalescing isolation tests (policy_tests.rs:6794-6860, test_scheduling_utility.py:363-401), documented the term in docs/scheduling-utility.md:287-318 and docs/scheduling-runtime-design.md:266-284.
Merge Risk: Medium · up to a5c3697
Pre-merge checks: ✅ 1 passed · ⚠️ 3 warnings
Findings · 1 blocker · 3 should fix · 5 subtract/simplify · 2 nits

Blockers

  1. Unresolved normative contract contradiction on a shipped default policy (docs/scheduling-theory.md:850-853, docs/scheduling-runtime-design.md:234, helios/src/scheduler/policy.rs:35). scheduling-theory.md:850-851 (untouched) states "First-token waiting has no independent age penalty: prompt work competes by its useful progress and token-service price", and scheduling-runtime-design.md:234 (34 lines above this PR's own edit at :268) still states "Only decoding requests have a delivery coordinate or output-age cost." Because the credit activates via PolicyConfig::default().decode_age_price = 0.1 — the default balanced policy (docs/cli-design.md:683) — this changes scheduling for every user (including the disclosed +76 ms to +95 ms background decode p99 trade-off at K=16) while docs contradict the runtime and opt-in Add opt-in first-output age pricing and returning-agent benchmark #654 remains open.

Should Fix

  1. b_served * T_dec can be sourced from GraphKind::Mixed (service.rs:150-181, utility.py:153-162). When kind is Decode | Speculative, all measured mixed_catalog shapes feed the same per-slot best[] promoted into best_decode at :168-173; utility.py:153-162 does the same (unlike :200, which filters not g.prefill_capacity). Both docs (scheduling-runtime-design.md:272-274, scheduling-utility.md:292-295) specify a pure decode/speculative graph, so on mixed-capture cores (qwen3.8-flash with --mixed-prefill) a mixed shape winning T / served inflates the credit with prefill time.
  2. Existing balanced burst-coalescing regression guarantees were dropped (test_scheduling_utility.py:363-402, policy_tests.rs:6840-6860). Relative guarantees (coal_ttft < base_ttft * 0.85, end_ms < base * 0.95, coal_sub <= base_sub // 2, burst_eight_low comparisons) were replaced with loose absolute ceilings (coal_ttft <= 600.0, coal_sub <= 2), and policy_tests.rs:6855-6859 dropped the simultaneous-arrival base comparison — nothing now verifies coalescing + the new credit does not regress TTFT/makespan.
    • Fix: Restore a coalescing-on vs coalescing-off non-regression comparison on burst_eight/burst_eight_low under balanced, and keep the stronger margins on the age_price = 0.0 isolation case.
  3. Commit simulator tests for the claimed formula properties and adversarial bounds (tests/test_scheduling_utility.py:404-425). The PR reports exact b_served * T_dec scaling, partial-chunk work / initial_prefill linearity, output_budget == 0 inertness and two adversarial checks, but the test only asserts ret_row["ttft_ms"] < 400.0 and tp_sched._first_output_value == {}.
    • Fix: Add deterministic pytest coverage for those properties and the adversarial invariants, and note whether the oracle reference (scripts/scheduling_sim/oracle_sweep.py (not opened) --prefill-wait-price, per docs/design-review.md:195-208) was run or why it is N/A.

Subtract / Simplify

  1. Deduplicate preserve_first_output_wait and drop dead checks (scheduler.rs:2681-2702, :2742-2789): record.status != 3 && !finished is redundant with finished's first disjunct, .saturating_sub(request.consumed_tokens) is unnecessary past the :2624 check, and record/finished/prefill/output are computed twice — ~10 lines removable via a small is_forced_anchor_cut helper.
  2. Track best_decode directly inside consider (service.rs:111-181): best_decode.1 * best_decode.1 * best_decode.0 (:178) re-squares served to undo the division at :116; a (cost, served, nanos) triple removes ~8 lines, per-slot redundant comparisons, and fixes Should Fix Congratulations! #1.
  3. Collapse fits_single_prefill_from onto a _from variant of natural_fit_prefill_capacity/prefill_catalog (policy.rs:357-363, :413-464): verified in cost.rs:639-670/:761-771 that prefill_entry(...).is_some() and duration(...).is_some() are identical; ~20 lines of parallel logic removable in the area helios/scheduler: budget interior conversation-anchor splits against checkpoint_extra_work_fraction #660 also touches.
  4. Fold set_first_output_wait into set_arrival (policy.rs:259-281, runtime.rs:1574-1577): single caller, always immediately after set_arrival, duplicating the validation guard/slot lookup and adding an implicit call-order trap.
  5. Trim duplicated contract prose in docs/scheduling-runtime-design.md:272-284: the 13-line explanation repeats scheduling-utility.md:287-318 (and already diverges); keep the formula at :268, fix :234, and link out.

Nits

  • utility.rs:94-110: delete the #[cfg(test)] pub fn prefill shim (only caller at :410-412; use prefill_within(64, 64, true)) and the redundant outer .min(1.0) at :106.
  • metrics/scheduler.rs:55-64 & runtime.rs:1231-1240: consider exposing first_output_wait_ns in RequestDetail alongside last_progress_ns/last_output_ns if operators need to inspect anchor-cut wait-clock preservation.

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

@logprobz

logprobz commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review: comparing #663 against #654 and recommended fixes

Recommendation: Use #663 as the basis for first-output wait pricing in Helios, address the fixes below before merge, and split the returning-agent benchmark and paired-visit analyzer from #654 into a separate PR so fixed-work evaluation against main can be reused independently.

Why #663 is the stronger scheduler approach compared to #654

  1. Incumbent-based scaling and monotonic chunk valuation:

    • helios/scheduler: price first-output waiting age on incumbent decode rounds #663 adds decode_age_price * (b_served * T_dec) * A_first * frac / T, where T is candidate duration, A_first is elapsed wait for first output, and (T_dec, b_served) comes from the measured Decode, Speculative, or decode-only Mixed candidate minimizing T_dec / b_served (breaking ties toward larger b_served = min(batch_capacity, eligible_lane_count)). Waiting prompt count does not enter this multiplier; for a fixed winning decode shape, b_served * T_dec saturates once eligible decoders fill that shape (including when K > B or B = 1).
    • Using elapsed wait A_first (without + T) keeps zero-age arrivals undistorted. On non-finishing chunks, frac = work / initial_prefill divides by T to (work / T) / initial_prefill, so partial-chunk urgency tracks chunk token throughput rather than favoring slower or smaller inefficient shapes. On prompt-completing steps (frac = 1), equal-age prompts at positive age favor shorter T, all else equal.
    • By contrast, Add opt-in first-output age pricing and returning-agent benchmark #654 scores waiting prompts with first_output_age_price * sigma * (A + T) / (T + F), where A is elapsed wait, T is candidate duration, and F is estimated exclusive work time remaining after the candidate. Holding A, F, and sigma fixed, the derivative with respect to T is first_output_age_price * sigma * (F - A) / (T + F)^2, so the age component rewards slower graphs whenever F > A. At A = 0, the component still contributes first_output_age_price * sigma * T / (T + F) (reaching first_output_age_price * sigma on a finishing step where F = 0). Its reference is sigma = (D + W) * min_graph(T_graph / min(B_feasible, G + W)) over measured eligible shapes, where D counts nonterminal streams with measured delivery references, G counts the generating subset, and W counts waiting prefills. For a fixed winning shape, sigma reduces to T_graph while D = G and G + W <= B_feasible, and grows with waiter count W once G + W > B_feasible.
  2. Simulator comparison across decoder counts and burst workloads:
    Running scripts/scheduling_sim (Value(64), token_fairness=16, delivery_fairness=4, adaptation_ms=100, age_price=0.1, rate_history="service", 15 s horizon, seed 0) locally against baseline origin/main (e85019b9, balanced, decode_age_price=0.1, no first-output term):

  3. Lower complexity and cleaner invariants:


Recommended fixes before merging #663

  1. Scale decode_age_price before multiplying by batch-time and age (helios/src/scheduler/policy.rs:750-768):
    values[slot].first_output_value computes self.policy.decode_age_price * incumbent_decode_batch_ms * age_ms and multiplies by unit afterwards. A large finite decode_age_price (accepted by validation) can overflow to +inf before normalization. Store the unscaled incumbent_decode_batch_ms * age_ms product first and multiply by self.policy.decode_age_price * unit once scale and unit are computed, and add a unit test covering a large finite decode_age_price at both positive and zero age.

  2. Check packed speculative batch feasibility in delivery_references_and_decode_batch (helios/src/scheduler/service.rs:123-142 and :168-182):
    By reusing the baseline delivery_references scan for GraphKind::Speculative (service.rs:123-142), helios/scheduler: price first-output waiting age on incumbent decode rounds #663 inherits a per-slot approximation and exposes it to waiting prompts (:168-182): the loop checks each lane individually with speculative_duration, overwrites nanos = Some(ns) with the last matching slot's duration, and passes min(batch, eligible_count) to consider. Under heterogeneous fixed-width verification lengths, a packed graph that fits each lane individually can lack total target positions to fit all eligible lanes together, and the retained duration can depend on slot order. Align the feasible batch calculation with packed dispatch rules (if changing the shared delivery_references scan, verify existing decoder reference scores too) and add tests covering heterogeneous lengths, a smaller measured packed shape, and slot-order invariance.

  3. Preserve host-published forced-reasoning-close timestamps on readmission (helios/src/server/runtime.rs:2456-2463):
    When forced reasoning-budget closure (close_reasoning) publishes tokens on the host without a graph completion before parking, live.accounting().last_output_ns does not advance. Record the host publication timestamp when publications advances during forced close (as Add opt-in first-output age pricing and returning-agent benchmark #654 does in runtime.rs) and take the later of that timestamp and live.accounting().last_output_ns when parking. Add readmission tests covering both with and without a prior graph publication, plus a two-frame pipelined prefill projection test.

  4. Test and clarify checkpoint wait-preservation boundary cases (helios/src/scheduler.rs:2681-2701, helios/src/scheduler/policy.rs:442):
    fits_single_prefill_from(request, start) confirms that a single fitting graph existed, not that the anchor actually shortened the chosen graph (for example, if decode pressure selects a smaller prefill capacity whose endpoint equals the anchor). Decide whether that case should preserve or reset first_output_wait_ns, and add unit tests for an anchor equal to the selected chunk capacity and for a non-anchor RetentionRole::Message cut.

  5. Reconcile documentation and qualify balanced simulator trade-offs:

    • Update docs/scheduling-theory.md (line 850 at e85019b9 still states that first-token waiting has no independent age penalty).
    • Tighten the phrasing added to docs/scheduling-utility.md and docs/scheduling-runtime-design.md: note that decode-only Mixed graphs also participate in the incumbent decode reference selection, and replace the unconditional "never shortens prefill or decode chunks" claim with the exact property (waiting prompts are omitted from the common -T/2 * sum c_j penalty sum).
    • Qualify the PR description's "zero regressions" wording across the 21 balanced workloads: on the default synthetic catalog above, max TTFT and makespan improve on burst_eight, burst_eight_8k, and sixteen_prefills, while max_output_gap_ms and decode_age_area_ms2 increase relative to baseline.
  6. Validate default-on balanced acceptance bounds and remaining checks:
    Because helios/scheduler: price first-output waiting age on incumbent decode rounds #663 activates by default under --scheduler-policy balanced and the reported SM121 GPU A/B runs show background decode p99 gap increases (DeepSeek K = 16, 12 returning turns, checkpoint_extra_work_fraction = 0.05: 368.4 -> 463.5 ms; Qwen K = 16, 45-second fixed window: 334.5 -> 410.5 ms), run a matched fixed-work returning-agent comparison against main (for example, using Add opt-in first-output age pricing and returning-agent benchmark #654's benchmark harness before splitting it into a separate PR) against explicit limits on TTFT, background token throughput, and p95/p99 decode gaps. Run the full Rust crate tests with FLARE_TEST_TEMPLATE_DIR set on the final merge revision.

(Verification scope: inspected PR #663 and PR #654 diffs, PR comments, and origin/main (e85019b9) files, and ran the Python simulator comparisons reported above locally. GPU results cited for #663 and #654 are taken from those PR descriptions; native Rust tests, GPU runs, TLA+, and Kani were not re-executed here.)

@FujitsuPolycom

Copy link
Copy Markdown
Contributor

SM120 TP4 (4× RTX PRO 6000 Blackwell) paired zero-knob flare run A/B for PR #663 (solo & stacked on #660 + #661)

Setup: Tested PR #663 (e29725bd / live HEAD a5c36978, verified identical Git tree 1f045d6c1335 and 0 diff lines) both standalone and stacked with #660 (22cac916) + #661 (fdb10bb5) against NVIDIA/hyperflare-inference:main at a3c80e19, using a single signed DeepSeek-V4.1-Flash-1017 TP4 core (zero re-export), stock --scheduler-policy balanced flags (--gpus 0,1,2,3 --max-concurrency 32 --mtp-draft-tokens 7 --mtp-adaptive-verification --mtp-max-verification-token-budget 128 --mtp-adaptive-verification-alpha 1.0 --embedding-table-storage disk --embedding-table-cache-size 84GiB --embedding-table-workers 1 --embedding-table-resident-scales --kv-cache-limit memory --prefix-cache-memory 0), 0 extra CLI flags (0-byte flare run --help diff), 0 compiler warnings, and single-boot-per-arm sequencing (stack663 -> pr663 -> base_a3c80e19).

Results (0 server failures, 0/35 container log errors, 35/35 finite logprobs on every boot):

Workload (C=32, seed 42, T=0.0) Metric base (a3c80e19) #663 solo (a5c36978) #660 + #661 + #663
mixed-c32 (15s warm / 60s meas / 30s drain) SLO goodput 8.3% 83.9% (+75.6 pp) 97.8% (+89.5 pp)
Output (tok/s) 1,055.7 1,234.7 (+17.0%) 1,354.9 (+28.3%)
Prefill (tok/s) 20,126 24,056 (+19.5%) 25,695 (+27.7%)
TTFT p50 ∥ p99 (ms) 4,559.6 ∥ 10,328.0 1,712.5 (-62.4%) ∥ 10,634.1 1,005.8 (-77.9%) ∥ 10,164.3
batch/step 9.14 18.71 (2.05×) 21.77 (2.38×)
Gap p99 (ms) 227.3 286.0 (+25.9%) 203.1 (-10.6%)
Stalls >250ms ∥ >1s 206 ∥ 0 431 ∥ 0 91 (-55.8%) ∥ 0
150K-250K cold + multi-turn mix (16× 150K–250K cold + 16× multi-turn agents, 90s meas / 45s drain) Overall ∥ Agentic SLO 0.0% ∥ 0.0% 71.4% ∥ 77.6% 82.2% ∥ 87.4%
Output (tok/s) 420.0 519.1 (+23.6%) 560.0 (+33.3%)
Prefill (tok/s) 50,453 54,567 (+8.2%) 47,472 (-5.9%)
Agentic TTFT p50 ∥ p99 (ms) 5,320.6 ∥ 7,789.5 1,862.0 (-65.0%) ∥ 5,344.7 1,338.3 (-74.8%) ∥ 4,953.0
Gap p99 (ms) 392.7 285.2 (-27.4%) 344.0 (-12.4%)
Stalls >250ms ∥ >1s 1,235 ∥ 14 2,018 ∥ 6 (-57.1%) 523 (-57.7%) ∥ 6 (-57.1%)
D3_c16_decode (C=16 cold) Agg decode (tok/s) 1,134.6 1,426.5 (+25.7%) 1,342.6 (+18.3%)
T_48B (4 decoders + burst-8) Makespan (s) ∥ Burst TTFT max (ms) 2.700 ∥ 1,441.4 2.321 (-14.0%) ∥ 1,111.3 2.119 (-21.5%) ∥ 865.9
T_49A (4×6-turn) TTFT p50 (ms) ∥ Prefill launches 306.9 ∥ 48.0 276.4 (-9.9%) ∥ 48.0 149.1 (-51.4%) ∥ 34.0

Notes & caveats:

  • Why solo #663 >250ms stalls rise (206 -> 431 / 1,235 -> 2,018) and how #661 resolves them: >250ms stalls are counted per active decoding stream whenever an unchunked prefill step pauses decode past 250ms. Solo #663 raises mean active decode concurrency 2.05× on mixed-c32 (9.14 -> 18.71) and 1.62× on 150K-250K cold + multi-turn mix (6.75 -> 10.95), scaling total >250ms stall events almost 1:1 (2.09× and 1.63×) even as >1s stalls drop 14 -> 6 (-57.1%) and heavy-mix gap p99 drops -27.4%. Stacking #661 shrinks prefill chunks under active decode below 250ms, cutting >250ms stalls to 91 (-78.9% vs solo #663, -55.8% below base) on mixed-c32 and 523 (-74.1% vs solo #663, -57.7% below base) on heavy mix while lowering mixed-c32 gap p99 to 203.1 ms (-10.6% below base).
  • Clean composition with #660 + #661: Zero semantic production conflicts (1 adjacent-function insertion in policy.rs and 2 test-fixture adjustments in policy_tests.rs; 424/424 scheduler:: tests pass).
  • Caveats: (1) On 150K-250K cold + multi-turn mix, all arms hit 100% KV saturation with 0 server failures and 0 agentic errors, while 11–13 cold 150K–250K lanes hit client shutdown/drain cutoffs (base: 4 heavy ok / 12 cutoffs; #663: 2 ok / 13 cutoffs; stack: 1 ok / 11 cutoffs; heavy TTFT p50 67.3 -> 68.4 / 68.8 s). (2) Single-trial D2 (27.5K solo) on #663 saw transient ~209 ms host/disk jitter (747.6 ms vs 538.9 ms base and 534.7 ms stack; #663 is inert with 0 active decoders, confirmed by 13,773t calibration 329.31 vs 329.25 ms). (3) A low-priority --cpus=4 nice 19 Rust build overlapped part of Boot 1/early Boot 2 on this 48-core host; base_a3c80e19 reproduced our prior 5d53040e baseline within 0.03%–1.6%.

@yatesdr
yatesdr force-pushed the feat/knob-free-first-output-scheduling branch from a5c3697 to 8aa79e3 Compare December 1, 2026 22:35
@yatesdr

yatesdr commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @logprobz for the thorough comparison and review (and @FujitsuPolycom for the independent SM120 TP4 + #660/#661 composition validation). I've credited @logprobz with Co-authored-by: in 8aa79e31 and addressed the review items:

  1. Overflow / NaN safety (helios/src/scheduler/policy.rs): Store unscaled incumbent_decode_batch_ms * age_ms (gated on age_ms > 0.0) in the slot loop and multiply by self.policy.decode_age_price * unit after scale and unit are computed. Added first_output_wait_large_finite_decode_age_price_avoids_overflow_and_nan covering both zero age and positive age at decode_age_price = 1e305.
  2. Pure-decode reference & packed speculative batch feasibility (helios/src/scheduler/service.rs, scripts/scheduling_sim/utility.py):
    • Computed best_decode strictly over pure Decode / Speculative shapes (excluding GraphKind::Mixed, and filtering not graph.prefill_capacity in utility.py) using (cost, served, nanos).
    • For speculative_fixed_width.is_some(), replaced the per-slot speculative_duration overwrite loop with a direct scan over packed_round_shapes() that greedily packs lane lengths within (shape.batch, shape.tokens) for both best_decode and each eligible slot's DeliveryReference. Added first_output_wait_excludes_mixed_graphs_and_respects_packed_speculative_feasibility testing Mixed exclusion, constrained packed token budgets, and slot-order invariance ([8, 2, 3] vs [3, 2, 8]).
  3. Host-published forced-reasoning-close timestamps (helios/src/server/runtime.rs): Recorded published_ns when close_reasoning advances incoming.publications and took max(live_last_output_ns, carried.last_output_ns) when parking. Added forced_reasoning_close_readmission_anchors_first_output_wait_with_and_without_prior_publication plus first_output_wait_projects_across_pipelined_prefill_submission.
  4. Anchor wait-preservation boundary (helios/src/scheduler/policy.rs, helios/src/scheduler.rs): Kept the existing RetentionRole::Anchor && endpoint == consumed && fits_single_prefill_from boundary and extracted preserves_first_output_wait with a comment explaining why prefill == step.token_capacity must still preserve the wait clock (once an anchor caps every larger capacity to the anchor endpoint, the scheduler always chooses the smallest covering bucket). Added anchor_wait_preservation_at_bucket_capacity_and_reset_on_message_cut testing both an anchor at the chosen bucket (128) and a non-anchor RetentionRole::Message cut.
  5. Docs & simulator qualification: Updated docs/scheduling-theory.md, docs/scheduling-utility.md, and docs/scheduling-runtime-design.md, tightened the "never shortens" wording, restored balanced burst-coalescing non-regression assertions and added scaling/linearity/stress pytest coverage, and qualified the balanced simulator max_output_gap_ms / decode_age_area_ms2 trade-off in the PR description.
  6. Paired 4-visit ABAB returning-agent suite & full checks: Ran Add opt-in first-output age pricing and returning-agent benchmark #654's benchmark_ready_prefill.py + analyze_ready_prefill.py across 4 alternating visits (stock1 -> treat1 -> stock2 -> treat2) on DeepSeek-V4.1-Flash-1017 TP4 (4× DGX Spark GB10, balanced) and added the full table to the PR body (closed 6/6 gates with +74% valid turns and -27% step_cost, cold 4/4, single -82% TTFT and 5/5 on visit 1, sustained 26/26 completing the 28K prompt that main timed out on both visits, and burst -74% TTFT with improved gap_p95 and higher gap_p99/longest_gap when 5 lockstep prompts burst simultaneously—which @FujitsuPolycom's SM120 run shows #661 resolves orthogonally). Re-ran pytest tests/test_scheduling*.py (830 passed), Linux --release Rust suites (helios 1,782, flare 253, flare-cli 241, heliopause cargo check clean), and TLA+ 1.7.4 (10/10 TLC models, 8/8 trace checks / 594,065 transitions, 12/12 auxiliary tests). Note: tests/frontend/prepare_templates.py failed locally with HTTP 401 on the gated meta-models/Muse-Spark-Open-816B-A42B-NVFP4 repo, so the 7 FLARE_TEST_TEMPLATE_DIR-dependent tests remain unrun locally.

Discord: D-Rock

@lukealonso

Copy link
Copy Markdown
Collaborator

Verdict: Changes Requested (reviewed at head a5c36978).

This design is cleaner than adding a separate prefill-age knob or dividing by (T + F): it introduces no new CLI/config flags, prices pure waiting age A_first rather than (A + T)/(T + F) (avoiding the slower-graph inversion), scales by the bounded incumbent decode round b_served * T_dec, omits waiting prompts from the common -T/2 * sum c_j penalty sum, and brings paired SM121 GPU A/B measurements on two distinct model architectures.

However, the implementation has four concrete bugs, three normative documentation contradictions, a weakened test suite, and an unapproved default-ON policy trade-off that block merging as written.


1. Bugs and Correctness Issues

1.1 preserve_first_output_wait fails on multi-chunk TerminalPrefill landing on an interior Anchor

  • Location: helios/src/scheduler.rs:2681-2701 (specifically line 2695: && !request.deferred_prefill), executing before helios/src/scheduler.rs:2796 (if kind == GraphKind::TerminalPrefill && record.status != 3 { request.deferred_prefill = false; }).
  • Defect: On a TerminalPrefill core (such as DeepSeek-V4.1-Flash), a multi-chunk prompt whose earlier non-terminal Prefill chunk set request.deferred_prefill = true and whose subsequent TerminalPrefill chunk stops at an armed interior RetentionRole::Anchor still has request.deferred_prefill == true when preserve_first_output_wait is evaluated at line 2695. That forces preserve_first_output_wait = false and resets first_output_wait_ns right before the Snapshot and short tail, even though complete_inner clears deferred_prefill and arms that exact Anchor boundary capture later in the same loop iteration.
  • Required fix: Replace !request.deferred_prefill with !(request.deferred_prefill && kind != GraphKind::TerminalPrefill) while still calling fits_single_prefill_from(request, request.consumed_tokens as usize) against the pre-completion deferred_prefill state so it inspects terminal_prefill_catalog. Also eliminate the duplicate record / finished / prefill / output computation in complete_inner by computing preserve_first_output_wait cleanly once per lane instead of re-deriving those four fields twice. Add a unit test exercising a TerminalPrefill chunk clearing deferred_prefill at an interior Anchor.

1.2 Float overflow to +inf before normalization for large finite decode_age_price

  • Location: helios/src/scheduler/policy.rs:750-751 and 768.
  • Defect: values[slot].first_output_value computes self.policy.decode_age_price * incumbent_decode_batch_ms * age_ms in unscaled f64 and only multiplies by unit = (-scale).exp() later at line 768. configure_policy accepts any finite non-negative decode_age_price, so a large finite value (for example 1e305) overflows decode_age_price * incumbent_decode_batch_ms * age_ms to +inf before normalization and turns into NaN when unit == 0.0 (or stays +inf and corrupts candidate comparisons).
  • Required fix: Store incumbent_decode_batch_ms * age_ms (or multiply self.policy.decode_age_price * unit first, since scale already includes self.policy.decode_age_price.ln() so decode_age_price * unit <= 1.0), and add a unit test covering large finite decode_age_price to verify finite scores.

1.3 Mixed graphs leak into incumbent_decode_batch_ms, and fixed-width Speculative is slot-order dependent

  • Location: helios/src/scheduler/service.rs:123-182 and scripts/scheduling_sim/utility.py:153-162.
  • Defect 1 (Mixed leak): Both docs/scheduling-runtime-design.md:272 and docs/scheduling-utility.md:292-295 specify that b_served * T_dec comes from the fastest incumbent Decode or Speculative round. In service.rs:151-159, self.mixed_catalog writes directly into the same best[slot] array that service.rs:168-173 promotes into best_decode. Likewise, scripts/scheduling_sim/utility.py:155 filters if decoding and graph.decode_capacity without and not graph.prefill_capacity, so a Mixed graph can become incumbent_decode_batch_ms in both Rust and Python whenever its decode duration beats pure Decode/Speculative.
  • Defect 2 (Speculative slot-order dependence and batch sizing): In service.rs:123-139, the inner loop sets nanos = Some(ns) on every eligible slot (overwriting with whichever slot has the highest bit index) and passes raw batch to consider(ns, batch, eligible) rather than a packed feasible batch capacity. Under heterogeneous fixed-width ragged speculative rounds, best_decode therefore depends on slot ordering and can misreport served and T_dec.
  • Defect 3 (avoidable round-trip arithmetic): service.rs:178 reconstructs b_served * T_dec via best_decode.1 * best_decode.1 * best_decode.0 (served * served * (T_dec / served)).
  • Required fix: Track best_decode directly inside the pure Decode and Speculative loops as (per_delivery_ms, served, duration_ms) so Mixed cannot enter and b_served * T_dec is served * duration_ms directly; filter and not graph.prefill_capacity in scripts/scheduling_sim/utility.py:155; make the fixed-width Speculative duration/batch accounting slot-order invariant with accurate feasible batch sizing.

1.4 Forced reasoning-budget close misses host-published tokens on readmission, and set_first_output_wait has a call-order trap

  • Location: helios/src/server/runtime.rs:1574-1576, helios/src/server/runtime.rs:2456-2463, and helios/src/scheduler/policy.rs:271-281.
  • Defect 1 (stale last_output_ns after forced reasoning close): In runtime.rs, close_reasoning publishes closing tokens on the host path before calling self.park(...) without updating live.accounting().last_output_ns. When park computes live_last_output_ns.or(active.carried.last_output_ns) at line 2463, those host-published tokens are invisible: a request whose previous device tokens were stop-buffered has live_last_output_ns == None and inherits stale arrival_ns upon readmission instead of the forced-close publication timestamp.
  • Defect 2 (silent clobber in set_first_output_wait): set_arrival overwrites first_output_wait_ns = arrival_ns, while set_first_output_wait clamps wait_ns.max(arrival_ns). Calling set_first_output_wait before set_arrival silently drops wait_ns with no error.
  • Required fix: Record the host publication timestamp when publications advances during forced reasoning close and combine it with live_last_output_ns and active.carried.last_output_ns via .max(...). Fold readmitted_output_ns: Option<u64> into set_arrival (or a single admission timestamp setter) so the call-order hazard cannot exist, and add a runtime test covering forced-reasoning-close readmission.

1.5 Anchor-cut preservation checks catalog existence rather than whether the anchor actually shortened the chunk

  • Location: helios/src/scheduler.rs:2700 and helios/src/scheduler/policy.rs:442-464.
  • Detail: fits_single_prefill_from(request, start) returns true whenever a single eligible prefill graph could have covered [start, prompt_tokens), even if decode pressure caused the scheduler to select a smaller capacity whose chunk size equaled the anchor endpoint anyway (selected_capacity == anchor_work). In addition, fits_single_prefill_from duplicates the catalog-selection and resolve_prefill_kind_from logic already present in policy.rs.
  • Required fix: Either tighten the condition (or explicitly document and test both selected_capacity == anchor_work and non-anchor RetentionRole::Message cuts), and reuse the existing prefill catalog selection helper rather than duplicating it.

2. Normative Documentation Contradictions and Default-ON Policy Sign-Off

2.1 Three normative specifications directly contradict the new behavior

  1. docs/scheduling-theory.md:850-851 (untouched in this PR):

    "First-token waiting has no independent age penalty: prompt work competes by its useful progress and token-service price."

    This is now false under balanced. Update docs/scheduling-theory.md to state the exact first-output waiting-age term, why it is scaled by b_served * T_dec, and why it is omitted from the common -T/2 * sum c_j penalty sum.

  2. docs/scheduling-runtime-design.md:234 (untouched in this PR):

    "Only decoding requests have a delivery coordinate or output-age cost."

    This directly contradicts the new formula 30 lines below it. Rewrite line 234 to distinguish decoding requests' delivery coordinate and common -T/2 * sum c_j waiting cost from waiting prompts' first_output_credit.

  3. docs/scheduling-runtime-design.md:331-334 (untouched in this PR):

    "Apart from the natural-fit restriction on unmeasured pure prefill graphs described below, candidate scoring has no smallest-fitting-shape filter, duration ceiling, forced oldest-request filter, or per-chunk prefill lateness cost."

    A non-finishing prefill chunk now receives decode_age_price * (b_served * T_dec) * A_first * (work / initial_prefill), which is a per-chunk waiting-age credit. Clarify what is excluded (no per-chunk deadline/lateness penalty in the -T/2 * sum c_j term) rather than leaving an outright contradiction.

2.2 Default-ON policy trade-off requires explicit maintainer sign-off

Enabling this term under --scheduler-policy balanced (decode_age_price = 0.1) ships a background decode tail-latency trade-off (+76 ms to +95 ms decode p99 at K = 16, and +151 ms decode max on Qwen3.8) to every default launch, with no opt-out short of --scheduler-policy throughput (which also disables decode delivery_fairness and decode_age_price). That is an intentional policy trade-off, not a free win; it needs explicit maintainer sign-off on shipping it default-ON under balanced (and on superseding or closing competing PR #654, which addresses the same first-output waiting-age problem through an opt-in prefill-age parameter).


3. Weakened Tests and Missing Verification

3.1 Burst-coalescing tests were weakened instead of preserving relative non-regression checks

  • tests/test_scheduling_utility.py:363-402: The PR removed the relative balanced comparison (coal_ttft < base_ttft * 0.85, coal_end < base_end * 0.95, coal_sub <= base_sub // 2, and the low-acceptance relative checks) and replaced them with loose absolute ceilings (coal_ttft <= 600.0, coal_sub <= 2, low_coal_sub == 0). Under those ceilings, coalescing could regress balanced relative to coalescing_horizon_tokens = 0.0 without failing the test.
  • helios/src/scheduler/policy_tests.rs:6845-6859: Similarly dropped the simultaneous-arrival baseline (coalescing_horizon_tokens = 0.0) comparison and kept only sim_coal_sub == 0 and sim_coal_full >= 120.
  • Required fix: Keep the new throughput/staggered isolation tests, AND restore relative non-regression assertions under balanced (asserting coalescing does not regress ttft, makespan, or sub-batch rounds relative to coalescing_horizon_tokens = 0.0).

3.2 Missing committed unit tests for key code paths

  • Python (tests/test_scheduling_utility.py:404-425): test_first_output_waiting_age_reduces_returning_prompt_stall_without_throughput_drift checks only ret_row["ttft_ms"] < 400.0 and age_price == 0.0 inertness. It does not assert the exact Python b_served * T_dec scaling, Mixed exclusion, partial-chunk work / initial_prefill linearity, output_budget == 0 inertness, or the adversarial oversubscribed/B = 1 stress invariants claimed in the PR description.
  • Rust (helios/src/scheduler/policy_tests.rs and helios/src/server/runtime/phase_tests.rs): No test covers:
    1. Two-frame pipelined prefill wait projection (policy.rs:734-744, where an in-flight prefill submission advances wait_start to expected_finish_ns).
    2. Multi-chunk TerminalPrefill clearing deferred_prefill at an interior Anchor (Section 1.1).
    3. Large finite decode_age_price overflow protection (Section 1.2).
    4. Forced-reasoning-close readmission preserving host-published last_output_ns (Section 1.4).
    5. Mixed graph exclusion from incumbent_decode_batch_ms (Section 1.3).

3.3 Remaining unrun checks

CI ran lifecycle (without --mutations), pytest, and kani. Full helios template tests (FLARE_TEST_TEMPLATE_DIR), native-serving.yml, and SM120 GPU A/B runs remain unrun and must either be executed before merge or kept explicitly listed as unrun checks.


4. Prose Inaccuracies, Duplication, and Cleanup

  1. PR description overstates the 21-workload simulator result:

    "across all 21 reference workloads: zero regressions"

    The simulator numbers show max_output_gap_ms increases (374 -> 440 ms, 300 -> 440 ms, 440 -> 572 ms) and decode_age_area_ms2 increases (+16% to +94%) on burst_eight, burst_eight_8k, and sixteen_prefills. Replace "zero regressions" with the exact metrics that improved, held steady, and increased (making the TTFT-vs-decode-gap trade-off explicit).

  2. docs/scheduling-utility.md:310 overstates chunk-size invariance:

    "Because the credit uses pure waiting age A_first and is omitted from the common -T/2 * sum c_j penalty sum, it vanishes at A_first = 0, never shortens prefill or decode chunks..."

    Omitting waiting prompts from -T/2 * sum c_j prevents adding a duration-shortening penalty, while linear work / initial_prefill keeps partial prefill credit proportional to work (not favoring smaller inefficient capacities). However, the positive numerator credit first_output_value * frac divided by T still changes the relative rate between prefill shapes (and between prefill and decode) when A_first > 0 — for instance, a finishing chunk receives frac = 1 whereas a non-finishing chunk receives work / initial_prefill, and a smaller capacity with higher work / T receives higher first_output_value * frac / T. State the actual algebraic property (no duration-shortening penalty in -T/2 * sum c_j, and linear amortization work / initial_prefill on non-finishing chunks) rather than claiming "never shortens prefill or decode chunks".

  3. GPU A/B tables omit reproduction commands: The PR description reports SM121 GPU A/B results for Qwen3.8 and DeepSeek-V4.1-Flash without the exact invocation commands, benchmark scripts, or core/workload parameters needed to reproduce them. Add the exact commands and inputs.

  4. Documentation duplication: docs/scheduling-runtime-design.md:272-284 duplicates the specification in docs/scheduling-utility.md:287-318. Keep the complete formula and edge cases in docs/scheduling-utility.md and reference it concisely from docs/scheduling-runtime-design.md.

  5. Minor Rust cleanup:

    • Remove the #[cfg(test)] pub fn prefill shim in helios/src/scheduler/utility.rs:94-97 and update test callers to prefill_within directly.
    • Remove the redundant .min(1.0) in helios/src/scheduler/utility.rs:106 (consumed / initial_prefill.max(consumed).max(1) is already <= 1.0).

Summary of Required Changes Before Merge

  1. Fix preserve_first_output_wait on multi-chunk TerminalPrefill stopping at an interior Anchor (scheduler.rs:2695) and deduplicate complete_inner.
  2. Prevent f64 overflow for large finite decode_age_price (policy.rs:750-768).
  3. Exclude Mixed graphs from incumbent_decode_batch_ms in both Rust (service.rs) and Python (utility.py), remove slot-order dependence in fixed-width Speculative, and compute served * duration_ms directly.
  4. Carry host-published timestamps across forced reasoning-budget close on readmission (runtime.rs) and remove the set_first_output_wait / set_arrival call-order hazard.
  5. Reconcile docs/scheduling-theory.md:850-851, docs/scheduling-runtime-design.md:234, docs/scheduling-runtime-design.md:331-334, and docs/scheduling-utility.md:310, and trim duplicated spec prose.
  6. Restore relative balanced burst-coalescing non-regression assertions and add the missing Rust and Python unit tests listed in Section 3.2.
  7. Update the PR description to report the max_output_gap_ms and decode_age_area_ms2 trade-offs, exact GPU A/B reproduction commands, and unrun checks, and get explicit maintainer sign-off on enabling this default-ON under --scheduler-policy balanced.

…rounds

Under the balanced scheduler policy (`decode_age_price = 0.1`), active
decoding streams accumulate waiting-age utility scaled by their batch-feasible
excluded wait while prompts waiting for their first output accumulate none.
When a returning or newly arrived prompt competes against a large active
decode cohort on a model without mixed prefill-decode graphs (for example,
8 to 16 concurrent decoders on DeepSeek-V4.1-Flash or Qwen3.8-Flash-Next),
the prompt stalls for multiple seconds waiting for its token-service fairness
price to climb high enough to displace a full-batch decode round. When an
interior conversation-anchor checkpoint splits a single-chunk prompt into a
main chunk, a boundary snapshot, and a short tail, the prompt incurs that
wait twice because progress resets its waiting state while its service price
drops on the first chunk.

This change closes the asymmetry inside the shared Helios scheduler and the
Python utility reference simulator without adding configuration flags, CLI
options, model branches, new graph kinds, or `ServicePrice` exemptions:

- `helios/src/scheduler/service.rs`: Extend delivery-reference selection with
  `delivery_references_and_decode_batch`, returning the fastest pure incumbent
  `Decode` or `Speculative` round's work-time `b_served * T_dec` (in
  stream-ms, excluding `Mixed` graphs and returning `0.0` when no measured
  decoder is active). For fixed-width packed speculative rounds, evaluate each
  measured packed shape's token budget directly so feasible batch capacity and
  per-slot delivery references are exact and slot-order invariant under
  heterogeneous verification lengths.
- `helios/src/scheduler/utility.rs` and `helios/src/scheduler/policy.rs`: Add
  `LaneValue::first_output_value` and `LaneValue::prefill_within`. When
  `decode_age_price > 0.0` and `b_served * T_dec > 0.0`, each waiting prompt
  with `max_new_tokens > 0` receives waiting-age credit
  `decode_age_price * (b_served * T_dec) * age_ms * frac`, multiplying
  `decode_age_price * unit` before scaling by `b_served * T_dec * age_ms` to
  avoid premature overflow or `inf * 0 = NaN` under large finite prices.
  `frac = 1.0` when the step completes the prompt and
  `frac = work / initial_prefill` on partial chunks. The credit flows through
  prerequisite and two-stage continuation scoring (`Init`, `Restore`,
  `Vision`, `Snapshot`) without adding waiting prompts to the common
  `-T/2 * sum c_j` waiting-penalty sum.
- `helios/src/scheduler.rs` and `helios/src/server/runtime.rs`: Track
  `RequestAccounting::first_output_wait_ns`. Preserve it across a prefill
  stopped at an armed interior `RetentionRole::Anchor` cut when the prompt
  otherwise fit in a single eligible prefill graph (including when the anchor
  coincides with the chosen chunk capacity or when a `TerminalPrefill` chunk
  clears `deferred_prefill` while landing on an interior anchor), while
  continuing to charge all measured token service truthfully in
  `observe_service`. Fold `readmitted_output_ns: Option<u64>` into
  `set_arrival` so admission timestamp assignment has no call-order hazard.
  Carry `Carried::last_output_ns` across preemption and forced-reasoning
  readmission, recording host-published forced-close timestamps when
  `close_reasoning` advances `publications` and taking the latest of graph and
  host publication timestamps.
- `scripts/scheduling_sim/utility.py`, tests, and docs: Mirror the pure-decode
  zero-knob formula in `UtilityScheduler`, add Rust and Python unit tests for
  inertness, `b_served * T_dec` scaling, `Mixed` exclusion, packed speculative
  feasibility and slot-order invariance, large finite `decode_age_price`
  overflow/NaN safety, anchor-vs-message cut boundaries, multi-chunk
  `TerminalPrefill` deferred-state anchor preservation, pipelined prefill
  wait projection, forced-reasoning-close readmission (with and without prior
  graph publication), balanced burst coalescing, and oversubscribed/small-batch
  adversarial bursts, and reconcile `docs/scheduling-theory.md`,
  `docs/scheduling-utility.md`, and `docs/scheduling-runtime-design.md`.

Result:
- Paired zero-re-export `flare run` A/B on 4x DGX Spark GB10 (SM121,
  DeepSeek-V4.1-Flash-1017 TP4, `--scheduler-policy balanced`, zero errors):
  - Returning agent + K=8 decoders: TTFT p50 `2,812 -> 1,025 ms` (-63.5%),
    turns/min `13.21 -> 21.77` (+64.8%), bg gap p95/p99 `168.1 -> 151.0` /
    `334.1 -> 328.3 ms`.
  - Returning agent + K=16 decoders: TTFT p50 `5,265 -> 894 ms` (-83.0%),
    turns/min `8.75 -> 18.00` (+105.7%), bg gap p95 `211.1 -> 184.0 ms`,
    p99 `368.4 -> 463.5 ms`.
  - C=12 simultaneous burst: max TTFT `7,177 -> 5,416 ms` (-24.5%), gap p99
    `183.9 -> 158.3 ms`.
  - Paired 4-visit ABAB returning-agent suite (closed 8x8, cold, single,
    sustained, burst at K=16): `closed` 6/6 gates (`73 -> 127` valid turns,
    +74%, TTFT p50 `6,493 -> 1,933 ms`, `step_cost` `0.840 -> 0.611`), `cold`
    4/4 parity, `single` TTFT p50 `3,301 -> 590 ms` (-82%), `sustained` 26/26
    valid (vs 24/26 on main, completing the 28K long return that main timed
    out), `burst` TTFT p50 `6,381 -> 1,668 ms` with higher p99/max gap
    (`376 -> 493 ms`, `426 -> 995 ms`).
  - `--scheduler-policy throughput` control (K=16): parity.
- Paired zero-re-export `flare run` A/B on 2x DGX Spark GB10 (SM121,
  Qwen3.8-Flash-Next TP2, hybrid Mamba/GatedDeltaNet + Attention, zero errors):
  - Standalone prefill 8K/32K exact parity (+0.1%); batched decode C=1..32
    parity to +6.5%; 45 s fixed-window returning agent + K=16 bg: TTFT p50
    `4,324 -> 868 ms` (-79.9%), turns `9 -> 22` (+136%), streamed bg throughput
    `237.1 -> 234.1 ch/s` (-1.3% parity), bg gap p99 `334.5 -> 410.5 ms`;
    35 s throughput control exact parity (`2,540 vs 2,539 ms`).

Supporting evidence and limitations:
- Rust (`--release`, Linux): `helios` (`runtime-core,server` lib: 1,783 passed),
  `flare` (253 passed), `flare-cli` (241 passed), `heliopause` `cargo check`
  (0 new warnings).
- Python: `pytest tests/test_scheduling*.py` (830 passed); `scheduling_sim`
  matches baseline traces identically across all 21 workloads at
  `age_price = 0.0`, while under `balanced` max TTFT and makespan improve on
  `burst_eight`, `burst_eight_8k`, and `sixteen_prefills` with modest
  increases in `max_output_gap_ms` and `decode_age_area_ms2`.
- TLA+ lifecycle conformance (`verification/helios-lifecycle/check.py`,
  TLA+ 1.7.4): 10/10 TLC models, 8/8 observed Rust trace checks (594,065
  transitions), 12/12 auxiliary conformance tests passed.
- Limitations: Gated template tests requiring `FLARE_TEST_TEMPLATE_DIR`
  (blocked locally by gated Hugging Face repo 401 in `prepare_templates.py`),
  `native-serving.yml`, and `kani` proofs were not run locally.

Co-authored-by: logprobz <321553542+logprobz@users.noreply.github.com>
Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
@yatesdr
yatesdr force-pushed the feat/knob-free-first-output-scheduling branch from 8aa79e3 to 5bf9085 Compare December 1, 2026 22:53
@yatesdr

yatesdr commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @lukealonso for the thorough review! Several items had just landed in 8aa79e31 right before your comment posted, and I've now addressed every remaining item in 5bf90854:

  1. Multi-chunk TerminalPrefill clearing deferred_prefill at interior Anchor (Section 1.1): Updated preserves_first_output_wait (helios/src/scheduler/policy.rs) to check !(request.deferred_prefill && kind != GraphKind::TerminalPrefill) while running fits_single_prefill_from against the pre-completion deferred_prefill state; deduplicated complete_inner (helios/src/scheduler.rs) so record, finished, prefill, and output are computed once per lane; added terminal_prefill_clearing_deferred_state_at_interior_anchor_preserves_wait.
  2. Large finite decode_age_price overflow / NaN protection (Section 1.2): Store unscaled incumbent_decode_batch_ms * age_ms (gated on age_ms > 0.0) and multiply by self.policy.decode_age_price * unit after scale and unit (policy.rs); added first_output_wait_large_finite_decode_age_price_avoids_overflow_and_nan.
  3. Mixed exclusion & fixed-width Speculative slot-order invariance (Section 1.3): Compute best_decode strictly over pure Decode/Speculative as (cost, served, nanos) in service.rs (and filter not graph.prefill_capacity in scripts/scheduling_sim/utility.py), scan packed_round_shapes() directly for fixed-width packed speculative feasibility and slot-order invariance; added first_output_wait_excludes_mixed_graphs_and_respects_packed_speculative_feasibility.
  4. Forced reasoning-budget close host timestamps & set_arrival call-order hazard (Section 1.4): Record host publication timestamp when close_reasoning advances incoming.publications and take max(live_last_output_ns, carried.last_output_ns) on park (runtime.rs); folded readmitted_output_ns: Option<u64> directly into set_arrival and removed set_first_output_wait; added forced_reasoning_close_readmission_anchors_first_output_wait_with_and_without_prior_publication.
  5. Anchor preservation boundary & helper reuse (Section 1.5): Kept RetentionRole::Anchor && endpoint == consumed && fits_single_prefill_from (documented why prefill == step.token_capacity must preserve when an anchor coincides with a catalog bucket), reused self.prefill_catalog(...) in fits_single_prefill_from, and added anchor_wait_preservation_at_bucket_capacity_and_reset_on_message_cut.
  6. Docs, tests, and PR body (Sections 2.1, 3, 4): Reconciled docs/scheduling-theory.md:850, docs/scheduling-runtime-design.md:234 & :330, and docs/scheduling-utility.md:310 (removing the "never shortens" overstatement and trimming duplicated prose); removed the LaneValue::prefill test shim and redundant .min(1.0); restored relative balanced burst-coalescing non-regression assertions in Rust and Python; added pipelined prefill projection and Python scaling/linearity/adversarial-burst tests; added exact GPU A/B reproduction commands, balanced simulator trade-offs, and unrun checks to the PR body.

Re-verified on 5bf90854: helios lib (1,783 passed), flare (253), flare-cli (241), heliopause cargo check (0 new warnings), pytest tests/test_scheduling*.py (830 passed), and TLA+ 1.7.4 (10/10 TLC models, 8/8 Rust trace checks / 594,065 transitions, 12/12 auxiliary conformance tests).

Ready for re-review and maintainer sign-off on enabling this default-ON under --scheduler-policy balanced (and closing #654, with @logprobz credited as co-author).

Discord: D-Rock

FujitsuPolycom added a commit to FujitsuPolycom/flare-local-inference that referenced this pull request Dec 1, 2026
…l swap

Why

Under concurrent mixed prefill and decode workloads (multiple long prompts
competing alongside active decoders), prefill valuation in
helios/src/scheduler/policy.rs and scripts/scheduling_sim/utility.py exhibits
two structural bottlenecks:

1. Scalar minimum peer_budget collapse: clamping the decode-batch coalescing
   horizon and expected speculative output across all active decoders by
   min_i(rem_i) collapses coalescing credit for every queued prefiller whenever
   a single active decoder nears completion.
2. Multi-chunk heavy prefill lockstep: ServicePrice::observe credits each
   intermediate prefill chunk, dropping the executing multi-chunk prompt's
   normalized price below untouched peers so competing long prompts advance in
   lockstep rather than finishing sequentially and freeing KV pages.

Averaging the bounded peer horizon across active decoders eliminates
single-stream collapse without inflating credit beyond the cohort's remaining
output. Pairing competing multi-chunk prefills by aged remaining-time urgency
and exchanging dimensionless normalized GPU-time shares at submission conserves
aggregate prefill entitlement against decode while allowing long prompts to
complete sequentially, including across deferred intermediate chunks on
TerminalPrefill cores.

What

- Helios scheduler (helios/src/scheduler.rs, helios/src/scheduler/policy.rs,
  helios/src/scheduler/service.rs, helios/src/scheduler/utility.rs; +136/-13,
  +123 net non-test Rust production LOC):
  - Replaced scalar peer_budget = min_i(rem_i) in coalescing_prefill_log_bonus
    with per-decoder remaining budgets averaged across active decoders for both
    speculative expected output and the coalescing horizon (bounded by
    PolicyConfig::coalescing_horizon_tokens and each prefiller's post-prefill
    output budget).
  - Added ServicePrice::log_normalized_share and
    ServicePrice::swap_normalized_share in utility.rs, best_prefill_chunk and
    heavy_prefill_donors in policy.rs, and submit-time share exchange in
    service_participants (passing &step from scheduler.rs). When active
    non-terminal decoders exist (excluding policy::terminal_cleanup Snapshot
    requests), token_fairness > 0, and at least two non-terminal,
    non-prompt_logprobs prefills have remaining > c_max (best measured
    pure-prefill chunk, including deferred intermediate chunks on
    TerminalPrefill cores), pairs descending aged remaining-time urgency
    (1 + wait_ms / (1.5 * t_max)) / rem_ms with descending normalized share and
    exchanges shares on submit; single-chunk prefills (remaining <= c_max) are
    excluded.
- Python scheduling simulator (scripts/scheduling_sim/utility.py; +71/-7, +64
  net production LOC): mirrored cohort-mean coalescing and multi-chunk
  entitlement share swap (filtering pure-prefill graphs in pref_best, ranking
  donors by ascending log_fraction, pricing paired recipients with their own
  coefficient and the donor's log_fraction, and swapping log_fraction in
  UtilityScheduler::observe).
- Documentation and tests (docs/scheduling-runtime-design.md +27/-9;
  helios/src/scheduler/policy_tests.rs +240/-0;
  tests/test_scheduling_utility.py +108/-0): updated present-state scheduler
  design documentation and added unit tests verifying cohort-mean horizon
  behavior, normalized-share conservation across rates, sequential multi-chunk
  completion on both Prefill and deferred TerminalPrefill cores, submit/observe
  share exchange, single-chunk exclusion, retiring Snapshot exclusion, mixed
  graph filtering, and weighted donor parity.
- Compatibility: zero new CLI flags or PolicyConfig fields, zero decode-side
  changes, zero Protobuf/ABI/core-format changes, zero unsafe code, and zero
  new locks.

Result

Expected behavior (verified in unit tests and Rust/Python policy parity):
- Eliminates single-stream near-EOS coalescing collapse when one decoder has
  one remaining output token alongside longer active decoders.
- Serializes competing multi-chunk prompts across both standard Prefill and
  deferred TerminalPrefill chunks while conserving aggregate prefill
  entitlement relative to active decoders and leaving single-chunk prefills
  untouched.
- Offline calibrated simulation on this reduced diff and live SM120/SM121
  flare run GPU A/B benchmarks are pending before leaving Draft.

Evidence

Verified on a clean git archive extract of this commit atop
5d53040:
- git merge-tree --write-tree confirms zero conflicts against 5d53040,
  a3c80e1, live main, and NVIDIA#663 (a5c3697)
- cargo check --locked --release across helios (--features runtime-core,server
  --lib), flare (--lib), flare-cli (--bins), and heliopause with zero warnings
- cargo test --locked --release across helios (--features server --lib and
  --features runtime-core,server --lib), flare (--lib), and flare-cli
- pytest on tests/preparation/test_core_boundary.py and tests/test_scheduling*.py
- ruff==0.12.8 check on scripts/scheduling_sim/utility.py and
  tests/test_scheduling_utility.py
- All 10 standalone TLA+ TLC models, Rust trace conformance across all 8
  modeled protocols, auxiliary conformance tests, and lifecycle mutation checks
- Live fault-injection mutations across all retained Rust and Python code paths
  verified 100% killed by unit tests

Material limitations:
- Standalone calibrated discrete-event simulation on this reduced change and
  live SM120/SM121 flare run GPU A/B serving measurements are pending prior to
  marking ready for review.
- scripts/scheduling_sim/learning.py --preset validate and cargo-kani were not
  run because timing estimation, funded refresh, completion-vector validation,
  and StateView extent arithmetic are unchanged.

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
@lukealonso
lukealonso merged commit 8489d50 into NVIDIA:main Dec 1, 2026
3 checks passed
FujitsuPolycom added a commit to FujitsuPolycom/flare-local-inference that referenced this pull request Dec 2, 2026
…ced streams

Why

To keep decode cadence responsive without mixed prefill-decode graphs, Helios
interleaves smaller prepared prefill chunks with normal decode steps under the
default balanced policy (PolicyConfig::decode_age_price = 0.1 value/ms^2,
specified in docs/scheduling-theory.md and docs/scheduling-runtime-design.md).
On prepared cores whose TERMINAL_PREFILL catalog covers capacities above the
smallest chunk (for example, 256..=16384 alongside PREFILL 128..=16384), long
cold prompts contending with active decoding streams still cause multi-second
decode stalls for three reasons:

1. Cold-discovery lockout: prompts up to max_terminal measure TerminalPrefill(c)
   while leaving smaller non-terminal Prefill(c) unmeasured; add_candidate and
   continuation_candidate skip unmeasured capacities other than natural_fit, and
   funded refresh only revisits measured keys.
2. Monolithic-tail lockout: prefill_requires_terminal_completion_from excludes
   non-terminal Prefill whenever remaining tokens fit within max_terminal,
   forcing any remaining tail up to max_terminal into one TerminalPrefill step.
3. Two-frame prefill pipelining: prefill_step_requires_feedback lets consecutive
   non-terminal Prefill steps fill both transport frames ahead of active
   age-priced decoders and updated output ages.

Pricing unmeasured smaller prefill capacities from already-measured GPU
durations, allowing non-terminal Prefill chunks below max_terminal while active
age-priced streams exist, and requiring feedback between non-terminal chunks
lets ValueRate choose latency-bounded chunks by default under balanced without
new CLI flags, hardcoded capacities, duration ceilings, or per-model branches.

What

Net non-test production change: +319 LOC (+397/-78) across 4 Rust scheduler
files (11 files total, +1,949/-106; zero new CLI/config flags, zero unsafe,
zero hardcoded capacities, zero model-name branches, zero Protobuf or ABI
changes):

- Interpolated GPU-measured prefill estimates and discovery origin
  (helios/src/scheduler/cost.rs, policy.rs): added
  ActionCosts::interpolated_prefill_duration, deriving positive durations
  strictly from measured GPU timings (same-capacity sibling first, else linear
  interpolation between nearest smaller peer or fastest Decode/Speculative/Resume
  floor and nearest strictly larger peer, with order-independent same-kind
  precedence and ScoredPrefill isolation). When age_price > 0.0, unmeasured
  pure-prefill capacities <= nat_fit compete by ValueRate in add_candidate and
  continuation_candidate (excluding oversized padded shapes > nat_fit). In
  select_plan() and phase_plan(), unmeasured interpolated winners return
  PlanOrigin::Discovery directly (preventing displacement by stale refresh
  probes and preventing unmeasured interpolated durations from entering
  PlanOrigin::AcceptanceStart), drain on first run as TimingOrigin::Discovery,
  and record real GPU timings. Solo prefill (age_price == 0.0), service_rates,
  and checkpoint planning are unchanged.
- Chunkable non-terminal Prefill, resize capping, and hot-path caching
  (helios/src/scheduler.rs, policy.rs, service.rs): tightened
  resolve_prefill_kind_from so deferred_prefill never selects non-terminal-
  catalog shapes when needs_terminal is false; updated resize_prefill to select
  from terminal_prefill_catalog whenever request.deferred_prefill is active and
  cap age-priced non-terminal prefill growth at candidate.capacity; added
  prefill_must_complete_terminally_from and
  prefill_requires_terminal_completion_for_age; cached terminal_prefill_window
  and hoisted per-slot prefill planning state across capacities/continuations;
  kept the token_rate == 0.0 non-terminal Prefill fallback in service_rates.
- Active-stream feedback barrier (helios/src/scheduler.rs):
  prefill_step_requires_feedback drains between non-terminal Prefill steps when
  an active Decode/Resume (decode_age_price > 0.0) or terminal-cleanup
  (terminal_age_price > 0.0) stream exists, preserving two-frame pipelining for
  solo prefill and --scheduler-policy throughput (decode_age_price = 0.0).
- Added a GB10 simulator workload (scripts/scheduling_sim/workloads.py), unit
  and mutation-coverage regression tests, updated the deferred-prefill source
  mutation pattern in verification/helios-lifecycle/check.py, and reconciled
  present-state documentation (docs/scheduling-runtime-design.md,
  docs/scheduling-theory.md, helios/README.md). Existing signed cores load and
  serve unchanged.

Result

Live zero-re-export flare run A/B measurements with stock --scheduler-policy
balanced (0.1) and --scheduler-policy throughput (0.0) (zero new CLI flags,
DeepSeek-V4.1-Flash signed cores, zero errors, zero non-finite logprobs):

- 4x RTX PRO 6000 (SM120 TP4, signed core gb202-tp4-202612010626, flare run
  --gpus 0,1,2,3 --max-concurrency 32 --mtp-draft-tokens 7
  --mtp-adaptive-verification --mtp-max-verification-token-budget 128
  --mtp-adaptive-verification-alpha 1.0 --scheduler-policy balanced
  --embedding-table-storage disk --embedding-table-cache-size 84GiB
  --embedding-table-workers 1 --embedding-table-resident-scales
  --kv-cache-limit memory --prefix-cache-memory 0):
  - Standalone pre-NVIDIA#663 (5d53040 vs fdb10bb): on 4 active decoders + staggered
    14K+32K+64K prefills (T_50C, n=2), peak decode gap drops 331.9 -> 260.3 ms
    (-21.6%), mean max gap drops 279.7 -> 246.1 ms (-12.0%), and mean TPOT drops
    6.10 -> 5.55 ms (-9.0%) for +1.8% makespan (3.164 -> 3.221 s). On tokbench
    mixed-c32 (FujitsuPolycom/tokbench d6b74524, C=32, seed 42, temperature 0.0,
    warmup 15s + measure 60s + drain 30s, n=1), >250 ms stalls drop 215 -> 78
    (-63.7%), gap p99 drops 237.2 -> 188.6 ms (-20.5%), and per-user p50 rises
    93.9 -> 99.2 tok/s (+5.7%) for -2.0% output (1,072.8 -> 1,050.8 tok/s). Solo
    27.5K TTFT stays within +0.7% (540.7 -> 544.2 ms, n=1); solo C=1 short (464
    tok, n=2) Trial 0 matches base (58.91 vs 58.58 ms; Trial 1 189.2 ms jitter).
  - Post-NVIDIA#663 stacked SM120 A/B (a3c80e1 base vs NVIDIA#663 vs NVIDIA#660+NVIDIA#661+NVIDIA#663,
    mixed-c32, n=1): standalone NVIDIA#663 raises mixed-c32 gap p99 from 227.3 to
    286.0 ms and >250 ms stalls from 206 to 431; stacking NVIDIA#661 eliminates that
    regression, cutting gap p99 by -29.0% (286.0 -> 203.1 ms, -10.6% below
    pre-NVIDIA#663 base) and >250 ms stalls by -78.9% vs NVIDIA#663 (431 -> 91, -55.8% below
    pre-NVIDIA#663 base) while sustaining 97.8% SLO and 1,354.9 tok/s output.
- 4x DGX Spark GB10 (SM121 TP4, signed core gb10-tp4-202612010243, pre-NVIDIA#656
  571a447, n=3 trials, 12 decoders + 3x19.5K prompts): >1 s decode stalls drop
  24 -> 0 (-100%), p99 ITL drops 1,670 -> 713 ms (-57.3%), max burst gap drops
  1,699 -> 725 ms (-57.4%), trading +2.8% heavy TTFT p50 and -1.3% decode output.
- 4x RTX PRO 6000 throughput control (pre-NVIDIA#656 571a447, --scheduler-policy
  throughput, n=2 across 3 workloads): prefill launches are bit-identical
  (28/24/19) and makespan stays within +0.3% (3.64 vs 3.65 s).
- Host planning & calibrated simulation: 25-bucket dense-catalog plan() is
  4.70x-8.65x faster than base 571a447 (55.8-196.0 us mean). All 21 existing
  workloads remain bit-identical under Python UtilityScheduler.

Evidence

Verified on a clean git archive of this commit atop 1fbcc3c (post-NVIDIA#663 main)
via release cargo check (-D warnings) and cargo test (helios --features server
and --features runtime-core,server, flare, flare-cli, and heliopause), pytest
(core boundary and scheduling suites), ruff 0.12.8 lint, throttled
scripts/scheduling_sim/learning.py smoke and screen presets (known, ttl,
retained-refresh), and TLA+ lifecycle models, Rust trace conformance, and full
source/model mutation testing (verification/helios-lifecycle/check.py
--mutations). Standalone SM120 hardware A/B ran on direct pre-NVIDIA#663 predecessor
fdb10bb (atop 5d53040) and stacked post-NVIDIA#663 SM120 A/B ran on 82f68ea8
(NVIDIA#660+NVIDIA#661+NVIDIA#663 atop a3c80e1), both prior to the resize_prefill
deferred_prefill guard, select_plan() PlanOrigin::Discovery guard, doc sync,
and rebase onto 1fbcc3c.

Limitations: live flare run A/B benchmarks were not re-executed on this exact
rebased SHA atop 1fbcc3c; gated Hugging Face chat-template tests require
FLARE_TEST_TEMPLATE_DIR with gated repo credentials; cargo-kani was not run
because completion-vector and StateView validators are unchanged.

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
FujitsuPolycom added a commit to FujitsuPolycom/flare-local-inference that referenced this pull request Dec 2, 2026
…l swap

Why

Under concurrent mixed prefill and decode load (multiple long cold prompts
competing alongside active decoders), prefill valuation in
helios/src/scheduler/policy.rs and scripts/scheduling_sim/utility.py has two
structural defects:

1. Scalar min_i(rem_i) collapse: clamping the decode-batch coalescing horizon
   and expected speculative output across active decoders to min_i(rem_i)
   collapses coalescing credit whenever one active decoder nears completion.
2. Multi-chunk prefill lockstep: ServicePrice::observe credits each
   intermediate prefill chunk, dropping the executing prompt's normalized
   price below untouched peers so long prompts advance in lockstep instead of
   completing sequentially and freeing KV pages.

Averaging bounded per-decoder remaining budgets across active decoders prevents
single-stream collapse without inflating credit past the cohort's remaining
output. Recording planned normalized-entitlement swaps among competing
multi-chunk prefills at submission, projecting queued swaps across depth-2
pipelines, and applying the exchange only at validated completion conserves
aggregate prefill entitlement relative to active decoders while preserving
completion-only accounting and rejection safety.

What

- Helios scheduler (helios/src/scheduler.rs, helios/src/scheduler/policy.rs,
  helios/src/scheduler/service.rs, helios/src/scheduler/utility.rs; +263/-39,
  +224 net non-test Rust production LOC; zero CLI, config, decode, ABI, unsafe,
  or lock changes):
  - Replaced scalar min_i(rem_i) in coalescing_prefill_log_bonus with the
    cohort mean across all active decoders for both speculative expected output
    and the coalescing horizon (bounded by coalescing_horizon_tokens and each
    prefiller's post-prefill output budget).
  - Added ServicePrice::{log_normalized_share, swap_normalized_share},
    best_prefill_chunk, stack-allocated heavy_prefill_donors (zero heap Vec
    allocations), projected_services, and Submission::prefill_share_swap.
  - Multi-chunk pairing activates only when active non-terminal decoders exist
    (excluding retiring Snapshot requests), token_fairness > 0,
    decode_age_price > 0 (inactive under --scheduler-policy throughput), and at
    least two non-terminal, non-prompt_logprobs prefills exceed
    prefill_chunk_size (including deferred TerminalPrefill chunks). Single-chunk
    prefills (remaining <= prefill_chunk_size) are excluded even when the
    highest-throughput chunk c_max is smaller than prefill_chunk_size.
  - Submission records any non-self (recipient, donor) handle pair computed
    from projected prices without mutating stored prices. Depth-2 projection
    (projected_services) applies pending swaps before projecting queued frames.
    observe_service executes swap_normalized_share only after
    observed_duration_ns returns Some, verifying non-error status, positive
    useful_tokens on the recipient, and matching live request handles.
- Python scheduling simulator (scripts/scheduling_sim/utility.py; +105/-7):
  mirrored cohort-mean coalescing and weighted-conserving multi-chunk share
  exchange (ranking and swapping log_price to conserve aggregate sum q_i across
  unequal weights, gated on reference is not None, age_price > 0,
  rate_history == "service", and remaining_prefill > max_prefill_cap, using
  log-space urgency to avoid overflow on tiny durations, and validating
  duration_ms and committed rows before mutating prices or clearing donors).
- Documentation and tests (+127/-35 docs; +784/-0 Rust tests; +245/-0 Python
  tests): placed canonical specification and linear-aging preemption limits in
  docs/scheduling-utility.md, reconciled docs/scheduling-runtime-design.md,
  docs/scheduling-theory.md, and helios/README.md, and added unit tests
  covering packed/unpacked speculative cohort-mean, zero-fairness/throughput
  opt-out, prompt_logprobs exclusion, single-chunk exclusion below
  prefill_chunk_size, arrival-wait aging and tie-breakers, completion-only
  depth-2 pipelining, error/zero-timing invariance, Mixed prefill swaps, and
  weighted Python conservation.

Result

Measured incrementally atop post-NVIDIA#663 main (1fbcc3c):
- All 21 standard simulator workloads in scripts/scheduling_sim/workloads.py
  under both standard and mixed catalogs and both balanced and throughput
  policies show zero regressions (0/21 changed).
- --scheduler-policy throughput (decode_age_price == 0) is byte-for-byte
  unchanged by share swaps across all tested workloads.
- Under balanced policy on concurrent multi-chunk workloads alongside active
  decoders (standard catalog): 2 decoders + 2x16k shifts heavy TTFTs from
  [593.1, 678.4] ms to [383.9, 857.2] ms (first -35.3%, mean 320.1 -> 312.5 ms,
  max_output_gap_ms unchanged at 217.3 ms, output_tok_s -1.9%, decode_age_area
  +6.2%); 4 decoders + 4x16k shifts heavy TTFTs from [1436.0..1637.3] ms to
  [788.0, 970.6, 1968.6, 2200.6] ms (first -45.1%, mean 773.5 -> 744.7 ms,
  max_output_gap_ms 213.0 -> 226.6 ms, output_tok_s -2.4%, decode_age_area
  +7.9%). On mixed catalog: 2 decoders + 2x16k shifts mean TTFT -17.2% (first
  -36.9%, gap unchanged 145.0 ms, out -1.8%); 4 decoders + 4x16k shifts mean
  TTFT -21.1% (first -57.4%, gap unchanged 114.7 ms, out -1.5%). Live
  SM120/SM121 flare run GPU A/B is pending before upstream review.

Evidence

Verified on clean git archive (tree d0c622a) atop 1fbcc3c:
- Merge-tree: 0 conflicts vs upstream/main (1fbcc3c), NVIDIA#660 (9709d49),
  NVIDIA#661 (c588d61), NVIDIA#665 (c5b3923), and composed main + NVIDIA#660 + NVIDIA#665.
- Rust builds & tests: RUSTFLAGS="-D warnings" cargo check --locked --release
  across helios, flare, flare-cli, and heliopause passed with 0 warnings;
  helios --features server --lib 1,284 passed; helios --features
  runtime-core,server --lib 1,796 passed (excl. 6 FLARE_TEST_TEMPLATE_DIR
  tests); flare --lib 246 passed; flare-cli 245 passed (0 failed).
- Python & simulator: pytest (test_core_boundary.py + test_scheduling*.py) 838
  passed; ruff==0.12.8 0 issues; full 21-workload sweep under balanced and
  throughput (standard + mixed catalogs).
- Formal & mutations: 10/10 standalone Java TLC configs, 8/8 observed Rust
  TLA+ traces (594,065 transitions, 0 errors), 12/12 aux tests, 26/26 check.py
  Rust lifecycle mutations + 13/13 TLA+ model mutations + 1/1 DispatchRing
  SlotReuseSafe observed-edge check KILLED (0 survivors), plus 13/13 reachable
  custom Rust PR mutations and 12/12 custom Python PR mutations KILLED.
- Limits: live SM120/SM121 flare run GPU A/B is pending; learning.py --preset
  validate and cargo-kani were not run because their covered code is unchanged.

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:scheduling Request scheduling, fairness, batching, and speculative-width selection. duplicate This issue or pull request already exists enhancement New feature or request performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:design-review Needs a maintainer scope, architecture, or contract decision before implementation or integration.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants