Correctness, Contracts & System-Level Consequences review — #693 @ 000a6ac8
Bottom line: I found no correctness defect in the caching refactor itself. Every substitution I traced is an exact identity of the code it replaces, the change touches no locks, I/O, threads, unsafe, wire/protobuf, captured-graph contracts, config defaults, or sampled rate/latency spans, and it reduces allocation versus main. The real issues are charter/evidence compliance, an optimization scope that is understated and partly unobservable by the PR's own new counter, and one release-build safety softness.
Key findings
| # | Severity | Finding |
|---|---|---|
| 1 | Major | Charter #210 / docs/design-review.md:106-115 rule 12 unsatisfied: no served-workload evidence, yet the performance label stays and the Why section still opens on a sample #547 says is unattributable to this path |
| 2 | Major | Layer 2 simulator obligation (docs/design-review.md:195-206, learning.py (not opened) screening + 64-seed catalog) not run; only eight pytest suites |
| 3 | Major | Claimed "at most one curve per lane" bound is unobservable for speculative_fixed_width and GPU-allocation configurations; the counter only exists inside powered_curve |
| 4 | Minor | optimistic mode guard is debug_assert_eq! → compiled out in release; policy.rs:1506 hardcodes false, so a future optimistic threading would silently mis-price |
| 5 | Minor | CURVE_EVALUATIONS re-adds what #540's review asked to delete, now without the rationale the removed CPU table supplied |
1. Correctness, Safety & Platform Parity
Sound, stated plainly. I traced each caching substitution against the code it replaces:
tokens <= 1short-circuit —helios/src/scheduler/policy.rs:1396-1398:
Exact, becauseif tokens <= 1 { return f64::from(tokens != 0); }forecast_tokens(helios/src/scheduler/rounds.rs:1028-1030) isf64::from(width != 0) + powered[..width.saturating_sub(1)].iter().sum::<f64>()— width 0 →0.0, width 1 →1.0. Identical to the old uncachedexpected_speculative_tokens.width <= 1inproposal_forecast_tokens—rounds.rs:637-642, same identity (and it removes thepowered[..1]slice on width 0 that the old path performed).limit <= 1in the packed loop —rounds.rs:903-905. Onmainthe loopfor position in 0..limit.saturating_sub(1)(rounds.rs:908) was already empty forlimit <= 1, so scoring is unchanged; only cache population is skipped.alpha == 1.0fast paths —powered_curve(rounds.rs:645-656),prefix_lengths_with_values(rounds.rs:571-576),host_prefix_ranking(rounds.rs:599-605).p.powf(1.0) == pexactly for every finitep, and for NaN/inf too, so results are bit-identical, not merely close. Defaultadaptive_verification_alpha == 1.0(per dossier,policy.rs:41).candidates()threading —policy.rs:1633-1635:
Both call sites passlet mut curves = CurveCache::new(false); self.mixed_candidates_with_curves(output, values, age_price, false, &mut curves); self.packed_round_candidates_with_curves(output, values, age_price, false, &mut curves);optimistic == false, matching the cache tag, so no mode mixing is reachable from the production path. Direct wrappers build their own tagged caches:mixed_candidatesatpolicy.rs:1705,packed_round_candidatesatrounds.rs:855.- Rewritten non-cached call sites are exact.
resize_prefill(policy.rs:2000-2007) now callslane_tokens+expected_speculative_tokensinstead oflane_value(..); equivalent becausedecode(e,d) == decode_within(e, 0.0, d)andcached_lane_value→cached_lane_value_within(..., preceding = 0, ...)→decode_within(expected, 0/1e6, duration)(policy.rs:1436-1446,1505-1509).mixed_candidates' prefill lane value (policy.rs:1747-1751) is exact becauselane_tokensfor prefill isprefill_work(policy.rs:1378-1380) andprefill_lane_valueignores duration entirely (policy.rs:1407-1434). next_progresskeeps a singlemixed_catalogloop (policy.rs:974-1013) with the samespeculative_widths.is_empty() ? 1.0 : cached_expected_tokens(...)shape asmain, takes&mut CurveCache(policy.rs:896-901), and threads it throughprerequisite_value(policy.rs:1017-1031). No stack fallback cache remains.- No concurrency, memory, or failure-blast-radius concerns.
CurveCache(policy.rs:100-130) is stack-scoped per pricing pass and never stored onself, so there is no cross-pass staleness, no retention, no unbounded buffering, and no new head-of-line blocking:candidates()is&self, unchanged in shape, and net allocation decreases (each lane'sVec<f64>is built once instead of once per priced shape). No new panic path except thedebug_assert_eq!below, and no platform-specific code — the change is pure arithmetic, so there is no Unix/Windows parity gap. - Metric/rate span check: no shrank span.
decode_within/prefill_withinargument lists andpreceding_nsare unchanged at every call site, and expected-token values are bit-identical, soValueRate,selection_value_rate, admission pricing, and theestimated_seconds-style consumers are unaffected. Nothing in this diff changes what is measured, only how many times an intermediate is computed.
Finding 4 (Minor) — the mode guard vanishes in release, and one helper hardcodes the mode
helios/src/scheduler/policy.rs:113-124:
pub(super) fn get_or_insert_with(
&mut self,
slot: usize,
optimistic: bool,
build: impl FnOnce() -> Vec<f64>,
) -> &[f64] {
debug_assert_eq!(
self.optimistic, optimistic,
"CurveCache cannot mix optimistic and non-optimistic survival curves"
);
self.entries[slot].get_or_insert_with(build)
}
The tag is only enforced by debug_assert_eq!, so in release a caller that threads one cache through both modes gets the first mode's curve silently — an optimistic/ordinary mis-price with no panic, no log, no counter. That is currently unreachable, but cached_lane_value_for_tokens_within bakes in the ordinary mode:
GraphKind::Decode | GraphKind::Speculative => value.decode_within(
self.cached_expected_tokens(r, tokens, false, curves),
(policy.rs:1505-1509) — so any future "thread the cache through optimistic pricing too" change would either trip the debug assert in CI-with-debug or, in release, quietly reuse an ordinary curve for an acceptance probe. Impact: latent mis-pricing in release builds only; a scheduling-decision error that no test would catch. Fix: key entries by (slot, optimistic) (or hold two entries arrays and select by mode) and pass the mode through cached_lane_value* instead of hardcoding false; keep the debug_assert_eq! as a backstop.
Finding 5 (Minor) — CURVE_EVALUATIONS is re-added
helios/src/scheduler/rounds.rs:10-14:
#[cfg(test)]
thread_local! {
/// Powered speculative curve evaluations on this thread, for tests that bound planning work.
pub(super) static CURVE_EVALUATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
and rounds.rs:646-647:
#[cfg(test)]
CURVE_EVALUATIONS.set(CURVE_EVALUATIONS.get() + 1);
Per the dossier, #540 merged this counter, its review recommended deleting it, main has neither it nor zero_duration, and #693 brings it back — now without even the CPU speedup table that used to justify it (that table was correctly withdrawn). It is #[cfg(test)]-gated so it costs nothing in release, but it is carried machinery whose only consumer is four new tests. Fix: either state why a global thread-local counter is preferable to asserting via the existing CurveCache::is_cached(slot) test hook (policy.rs:126-129), which is per-pass and needs no global state, or drop it.
2. Unintended System-Level Consequences (CRITICAL)
I traced this under load, contention, and partial-failure scenarios and found no system-level regression:
- No lock/queue/contention change. The diff adds no mutex, channel, thread,
await, or shared mutable state.CURVE_EVALUATIONSisthread_local!and#[cfg(test)], so it is not on any production path and cannot couple threads. - No memory amplification.
CurveCacheholds[Option<Vec<f64>>; REQUEST_LANES](policy.rs:100-103) withREQUEST_LANES == 64(helios/src/execution/manifest.rs:18), i.e. ≤64 vectors of ≤completion_token_capacity - 1f64, live only for the duration of onecandidates()call. Before the change those same vectors were rebuilt per priced shape and dropped; now they are built once and dropped once — strictly fewer allocations and lower peak churn during a pass. No cache is persisted across passes, so there is no retention, eviction, or disk-I/O interaction. - No new head-of-line blocking or failure blast radius.
candidates()was already a single-threaded&selfscan over the same catalogs; the loop counts and candidate emission order are unchanged, so nothing that a slow or cancelled waiter could poison is shared. A bad/degenerate curve still flows only into that pass's scores. - Small/uncontended paths do not regress. The
tokens <= 1/width <= 1/limit <= 1/alpha == 1.0guards are all taken earlier than the work they replace, and at the defaultalpha == 1.0thepowfmap is skipped entirely — so the common cases are strictly cheaper, not slower. - No interaction with recently merged work reverses. The only cross-feature coupling I checked is
speculative_fixed_widthand GPU prefix allocation (see finding 3), and in both cases behaviour is unchanged — only the accounting claim is weaker.
Finding 3 (Major) — the "bounded once per lane" claim is not what the counter measures
Two real configurations leave the cache entirely, and the tests cannot see it because the counter lives only in powered_curve:
(a) Fixed-width speculative. helios/src/scheduler/rounds.rs:874-892:
if self.speculative_fixed_width.is_some()
&& !self.gpu_prefix_allocation(shape.batch, shape.drafts, shape.width, shape.tokens) {
let prefixes = fixed_prefixes.entry((shape.drafts, shape.width)).or_insert_with(|| {
available.iter().map(|&slot| {
let request = self.slots[slot].request.as_ref().unwrap();
let length = self.speculative_tokens(request, shape.width.min(shape.drafts + 1));
let expected = f64::from(length != 0) + request.acceptance.curve(
request.generated_tokens, false)[..length.saturating_sub(1)]
.iter().map(|&probability| {
if self.policy.adaptive_verification_alpha == 1.0 { probability }
else { probability.powf(self.policy.adaptive_verification_alpha) }
}).sum::<f64>();
This path calls acceptance.curve directly, never powered_curve, and never touches curves — so CURVE_EVALUATIONS stays flat there regardless of how many shapes are priced, and the PR's own test mixed_candidates_price_each_decoding_lane_curve_once_per_call would pass vacuously for a fixed-width deployment (it would also not catch a regression that re-introduced per-shape rebuilding in this branch).
(b) GPU prefix allocation. rounds.rs:566-577 (prefix_lengths_with_values) does if gpu { self.speculative_curve(request, optimistic) } — a raw curve, not powered_curve, and not cached. Likewise host_prefix_ranking (rounds.rs:599-605) builds a fresh curve per call. These are reached from materialize → round_lengths_optimistic → prefix_lengths_with_values (policy.rs:2023-2026, rounds.rs:537-549), which runs per masked slot on every plan selection, i.e. once per selected candidate rather than once per pass.
Impact: the claimed invariant ("powered survival curve evaluations are bounded to at most one per eligible decoding lane … within a candidates() pass") is true only for the powered_curve call sites. In fixed-width and GPU-allocation configurations the dominant curve work is elsewhere and unbounded per pass, and the four new tests cannot detect it because the counter is inside powered_curve only (rounds.rs:646-647). The description's scope note names only lane_values() and resize_prefill, so a reader is told the remaining work is smaller than it is. Fix: extend the scope note to name the fixed-width packed branch and the GPU-allocation/host_prefix_ranking path, and add one call-count test each with speculative_fixed_width set and with GPU prefix allocation enabled (or move the counter to speculative_curve, which all of these call, and then assert the true total).
(Non-finding: coalescing_prefill_log_bonus calls powered_curve per decoder per pass at policy.rs:612/663, and service_rates calls it at service.rs:337 (not opened)/:387 — both are outside candidates() and are explicitly disclosed in the PR's new scope note, so this is a documented limitation rather than a hidden defect.)
3. Architecture, Contracts & Charter Compliance
- No contract surface touched. No protobuf/wire change, no captured-graph op or ABI change, no exported-core format change, no config default change, no new feature flag or per-model branch (charter "keep the runtime small and model-agnostic" is respected — the change is entirely generic scheduler arithmetic). Nothing here needs the captured-graph owner sign-off that the charter reserves for new op contracts.
- Layer placement is right: the memoization lives in
helios/src/scheduler/, which is exactly the scheduling-pricing layer, and the cache is pass-scoped rather than attached toRequestScheduler— the correct minimal footprint.
Finding 1 (Major) — rule 12 evidence missing while the performance label and the pow motivation remain
docs/design-review.md:106-115:
12. **Validate the real path and report evidence honestly.** Exercise affected
shapes, tails, inactive rows, graph transitions, cache boundaries, request
lifecycle, and allocation stability. ...
Performance claims require equivalent baselines, complete
GPU steps across all ranks, and actual Helios service measurements.
The PR's own description now concedes "No standalone GPU serving latency or throughput improvement is claimed from this change", yet it retains the performance label and its Why section still opens on:
"In #547,
pow@@GLIBC_2.29appeared at 5.48% of samples on theflare-modelworker thread underperf record… that sample came from a stripped binary on a downstream tree without a call graph, so it does not separatepowered_curvefrom the scheduler's otherpowfcall sites."
Impact: the charter requires measured evidence for performance PRs, and this PR simultaneously (a) invites the reader to weigh a 5.48% hot-sample as motivation, (b) admits the sample cannot be attributed to this code, and (c) claims no measured gain — so nothing in the package satisfies rule 12 and the performance label is unsupported. That is an honest limitation, not a false claim, but it means neither the label nor the motivation is evidence-backed. Fix: either drop the performance label (leaving area:scheduling + triage:review) and reframe the Why section on the structural argument alone (per-pass allocation and powf reduction is a provable property of the diff), or attach a served-workload A/B on an exported core. State plainly that the label is inert pending measurement if it stays.
Finding 2 (Major) — Layer 2 simulator catalog not run
docs/design-review.md:195-206:
2. **Scheduling simulator and mathematical references.** Changes to graph
selection, service pricing, timing estimation, refresh or exploration
budgets, or cohort algorithms must be evaluated against the Python simulator
... Changes to timing
estimation or funded refresh require running the screening and 64-seed
validation catalog in `scripts/scheduling_sim/learning.py` (not opened) (stationary
workloads, idle transients, poisoned observations, missing timings, and
recovery fixtures).
This PR changes service pricing (powered_curve, prefix_lengths_with_values, host_prefix_ranking, packed/mixed candidate pricing) — squarely in the named categories. The evidence offered is pytest over eight simulator test suites (837 passed), which is the suite run, not the learning.py (not opened) screening + 64-seed validation catalog. Impact: the charter's Layer 2 obligation is only partly met, and since the whole point of the change is that it is bit-identical, the strongest possible evidence would have been a simulator catalog showing identical selected plans across seeds — cheap to run and exactly on point. Fix: run and report the learning.py (not opened) framing/catalog comparison (identical selections expected), or state explicitly why it is inapplicable to a bit-identical refactor.
4. Tests & Claim Accuracy
- The tests are well built and answer the right question.
cached_lane_pricing_matches_uncached_for_unit_and_fractional_alpha(helios/src/scheduler/policy_tests.rs:9569) checksscore.to_bits()parity against the uncachedspeculative_curve+powf(alpha)reference atalpha = 1.0and0.6, covering widths 0/1/2/4/8, waitingInit, ordinary and optimisticMixed, packedSpeculative, tie-breaking between identical lanes, and selectedplan()winners. Call-count tests sit atpolicy_tests.rs:9489,:9517,:9547. This is genuine behavioural coverage, not source-text checking, and it satisfies the "exercises production entry points" requirement ofdocs/design-review.md:186-189. The counter is reset per call (policy_tests.rs:9502,:9533,:9556,:9665,:9695), so the tests are thread-isolated within the default multi-threaded harness. - Claim accuracy: the before/after story in the description matches the diff at this head. The previously wrong
CurveCache::new(false)in the optimistic path, the undeclarednext_progressrestructure, the unreproducible 2.61x/5.40x/4.54x CPU table, and the missing attribution to @shieldstar are all genuinely fixed and are not repeated here. The withdrawn speedup claim is correct to withdraw: no benchmark exists inhelios/benches/to support one. - Test gap that matters: no test covers the
speculative_fixed_widthpacked branch or the GPU-allocationprefix_lengths_with_valuespath for curve evaluations (finding 3). The bit-equality test does not exercise those configurations either, so an equivalence break introduced there in future would go unnoticed. - Process gap (dossier, unchanged): zero CI checks recorded on
000a6ac8; every number in the description is a self-reported local run on "Linux x86_64 CPU" (1839 lib + 62 integration, flare 246+8, flare-cli 219+26, 837 pytest, TLC 2.19), andcargo-kaniwas not installed. I could not verify any of them from the PR, and the prior baselinec513e46ais unreadable in this checkout, so no independent pre/post comparison exists. The posted Autobot review's "Merge Risk: Low · up toa9f7dd7" line is one commit stale relative to this head.
Open questions
- Will CI ever run on
000a6ac8, or will the merge decision rest entirely on self-reported local runs? - Does @shieldstar (author of the #547 diagnosis and the bounded-evaluation tests this PR is based on) endorse this reimplementation? Attribution is now present; there is still no recorded endorsement or objection. And #547 stays open unless someone closes it explicitly.
- Should the
performancelabel stay on a PR that claims no speedup, and is thedocs/design-review.md:195-206learning.py(not opened) catalog run required before merge? - Why keep
CURVE_EVALUATIONSas a new global thread-local (finding 5) instead of the existing per-cacheis_cached(slot)test hook, given #540's review asked for its deletion? - Nothing I found explains why the fixed-width packed branch (
rounds.rs:874-892) memoizes on(drafts, width)but deliberately bypassesCurveCache— was that a scoping decision, or an oversight? #547 discusses only theresize_prefillomission.
What could not be verified
- The
scripts/scheduling_sim/learning.py(not opened) catalog was not opened or run; the finding is that the PR does not report it, per the dossier and description. - No GPU host was available, so the
pow-attribution question in #547 remains open by construction — the PR itself now says so. helios/src/scheduler/service.rs(not opened) was reached only viasearch_code(service.rs:337(not opened),:387), not read in full; the claims about it are limited to those twopowered_curvecall sites, which the PR's scope note already discloses.