Correctness and contracts scratchpad · NVIDIA/hyperflare-inference #659

Raw Markdown for agents: https://autobot.eidonix.com/p/59eb4700-4ec8-4dbc-9284-b7745537c3f0.md

#1 [high] MAJOR: row-zero write invariant not enforced in the layer that can violate it; a Helios GPU test writes row 0

FINDING (Major, correctness/safety + failure blast radius).

The optimization's safety premise is "nothing writes row zero". That premise is enforced ONLY outside Helios (Ignition). Helios' transfer layer accepts row 0 and has no guard.

Code that can write row 0 (bounds check only, no null-row rejection): helios/src/offload/transfer.rs:156-163

    if let Some((slot, slots)) = &job.row {
        let index = u64::from(slot.0);
        if index >= geometry.row_capacity {
            return Err(invalid(format!(
                "state slot {index} is outside the cache's {} rows",
                geometry.row_capacity
            )));
        }

Direction is In/Out — so both restore-into-row-0 and capture-from-row-0 are accepted.

An in-repo, ignored GPU test does exactly that with row 0 as a real checkpoint slot: helios/src/offload/gpu_tests.rs:1476-1481

        let (source_slot, child_slot, restored_slot, again_slot) = (
            StateSlotId(1),
            StateSlotId(0),
            StateSlotId(2),
            StateSlotId(3),
        );

helios/src/offload/gpu_tests.rs:1519-1525 writes the row-0 bytes directly and then checkpoint(..., child_slot) stores them through Direction::Out with row: Some(StateSlotId(0)).

Blast-radius amplification introduced by this PR: before, row zero's leading granules were independently backed, so a stray row-0 write at granule k corrupted only granule k. Now all sentinel_granules offsets map the SAME physical page (helios/src/runtime_core/cache_memory.rs:1418-1427), so one write at row offset 0..alignment is simultaneously visible at every leading granule offset — up to 39 offsets on an 82 MiB row — and produces wrong logits silently rather than an error. The author acknowledges the premise as a "limitation" but adds no guard.

Concrete fix: reject StateSlotId(0) next to the bounds check at helios/src/offload/transfer.rs:156-163 (if index == 0 { return Err(...) }), which is the layer that can actually violate the invariant; then change the gpu_tests slot fixture (1476-1481) to use a nonzero child slot. This is 1 line + 1 test fixture, no per-model branch.

#2 [high] MAJOR: new allocate_shared_cache sentinel branch has zero executed CI coverage

FINDING (Major, tests/claim accuracy).

The only code that actually maps and zeroes the new sentinel layout is helios/src/runtime_core/cache_memory.rs:1416-1447 (sentinel mappings + tail mapping) and :1468-1488 (split zeroing). Every reachable caller is NativeResources::allocate_shared_cache, called from helios/src/runtime_core/memory.rs:1300.

Reaching it from a test: only cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten, which is helios/src/runtime_core/cache_memory.rs:1106-1108

    #[test]
    #[ignore = "requires an assigned CUDA_VISIBLE_DEVICES GPU"]
    fn cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten() {

The PR states it was not run ("all local GPUs were occupied").

The new CPU test only checks Layout fields and handle arithmetic, not allocation: helios/src/runtime_core/cache_memory.rs:1367-1385 (sentinel_row_aliases_full_granules_onto_one_page) asserts sentinel_saved_bytes, layout.sentinel_granules, layout.fixed_bytes and layout.handle_charge — it never calls allocate_shared_cache.

So mapping count, mapping offsets, tail offset, and the reduced zeroing are unexercised. A mistake here (tail mapped at the wrong offset, tail not zeroed, sentinel granule zeroed after replay) is silent until a GPU run. Note the PR's own evidence section reports 191 passed ... 11 ignored, i.e. the ignored GPU tests are exactly the ones covering this.

Concrete fix: either run and report the GPU test on this commit, or add a CPU test that drives allocate_shared_cache through the mock Driver already used at cache_memory.rs:1120-1209 (it records cuMemMap/cuMemsetD8_v2 calls) and assert sentinel_granules mappings of alignment bytes plus one tail mapping and two memsets.

Also note coverage of the existing GPU test was reduced, not extended: helios/src/runtime_core/cache_memory.rs:1212-1226 now builds vec![0u8; ...] for row 0 and uploads only expected.iter().enumerate().skip(1), so the previous distinct-pattern check of row zero's backing is gone.

#3 [high] MAJOR: reclaimed bytes are spent on cache, changing planned capacities per engine version — description calls it a pure reclaim

FINDING (Major, claim accuracy + operator-visible consequence).

The PR description's compatibility section says only: "Compatibility: No core wire format, Protobuf, CLI, or Prometheus metric schema changes; existing prepared cores load and serve without re-export. Pure KV models and models with row_bytes < 2 * alignment are unaffected" and the claimed benefit is "Reclaims ... bytes of physical VRAM per rank for KV pages or shared snapshots".

What actually changes for operators is unstated: the reclaimed bytes are not returned to the operator, they are spent on more cache. All three planning sites that decide capacity now use the smaller physical figure:

Two consequences the description does not state:

  1. Identical hardware now reports different rows/pages; rows/pages are uploaded to the model and server_config["state_rows"] = (rows - 1) is set (memory.rs:1325, :1338). A memory limit that previously errored now succeeds — an operator-visible behaviour change, not a no-op.
  2. Because row zero's saving scales with floor(row_bytes/alignment), the saving is silently not delivered for row_bytes < 2 * alignment; the description says those models are "unaffected" which is true, but it means GDN rows must be >= 4 MiB at 2 MiB granularity. Worth stating explicitly.

Concrete fix: add one sentence to the description/release note: "On models with a state pool, the same hardware now plans more KV pages / snapshot rows than before; the reclaimed row-zero bytes are redistributed into cache, so plan cache output and state_rows differ from previous engine versions." This is exactly what docs/runtime-core-design.md:772-780 now documents internally but the PR description does not repeat.

#4 [high] MAJOR: saving physical bytes costs sentinel_granules*row_readers mappings; can turn a working layout into a handle-exhausted startup failure

FINDING (Minor-to-Major, unintended system consequence: handle budget regression under compaction).

The PR's central benefit is that fixed_bytes physical allocation shrinks, but the same change monotonically increases the handle charge for models with many granules, and this reverses the direction of the recently merged handle-budget work #391 (whose reviewer treated margin as blocking).

Handle charge before: 1 + row_readers for the fixed chunk. After: 1 + sentinel_granules * row_readers (+ tail handle/readers). helios/src/runtime_core/cache_memory.rs:82-102

        let fixed_charge = if self.sentinel_granules > 1 {
            let sentinel_bytes = self.sentinel_granules * self.alignment;
            let sentinel = 1u64
                .checked_add(
                    self.sentinel_granules
                        .checked_mul(row_readers)
                        .ok_or_else(|| invalid("mapping handle count overflow"))?,
                )

With row_readers > 1 (peer-read row plane), the cost is sentinel_granules * row_readers mappings instead of row_readers. For an 82 MiB row that is 39 granules; the code has no upper bound.

Verified effect on the in-repo fixture: the PR had to re-baseline the DCP16 assertion upward, helios/src/runtime_core/cache_memory.rs:818-819

        for (pages, snapshots, fixed, expected) in
            [(2304, 116, 20320, 494848), (3103, 157, 3528, 647816)]

and the compaction target :832-834 518232 -> 518504, i.e. +272 handles, and the docs headroom shrank (docs/runtime-core-design.md:832-833): "518,504-handle 3,103-page DCP16 layout, leaving 5,784 handles / 1.1%" (was 6,056 / 1.2%).

The failure mode this can create is not a slowdown, it is a startup failure: plan_mapping_handles at cache_memory.rs:611-616 errors "estimated VMM mapping handles ... exceed local handle limit" once the sentinel charge pushes the aggregate past RM_HANDLE_RANGE. Meanwhile the PR removes physical bytes, so the operator does not get more pages in that scenario — they get a refused load where main loads. In other words the change can convert an OOM-free layout into a handle-exhausted layout on the exact wide-DP configurations #391 was written for.

Note the PR description does not mention the handle cost at all; its "What changed" bullet describes only physical bytes saved. Concrete fix: state in the description that the saving costs sentinel_granules * row_readers mappings per rank, and either (a) cap aliasing (e.g. alias only when sentinel_granules * row_readers stays within a fraction of the remaining budget), or (b) fall back to the old single-handle path when the handle plan would exceed the limit. Existing precedence for (b): the fall-through at cache_memory.rs:1438-1447.

#6 [high] Verified-sound findings (arithmetic, teardown, zeroing order, no hot path, no contract change)

Verified-sound areas (say so plainly in the report):

  1. Arithmetic is correct. sentinel_saved_bytes (cache_memory.rs:69-71) = (row/align - 1)*align saturating; sentinel_granules is 0 unless row_bytes/row_alignment > 1 (cache_memory.rs:259-262). I reproduced the handle delta by hand: old fixed charge 1 + 1 = 2, new 1 + 16*1 = 17 per rank for DCP16 (16 granules for 35,122,432 B), +15 per rank... note the test's fixture has 16 granules -> 2 -> 17, and plan_mapping_handles's fixed term also shifts; the committed deltas (+272 aggregate, 518,232 -> 518,504) match the PR's own assertions at cache_memory.rs:818-834 and docs/runtime-core-design.md:829-833.
  2. Virtual span is preserved. fixed_bytes is untouched (cache_memory.rs:157); only physical backing changes. mapped = bytes(core, 0, execution) + borrowed at memory.rs:576 still uses the full virtual size; bytes(core,0,...) remains for all virtual arithmetic.
  3. Snapshot rows and live rows remain uniquely backed: layout.chunks mappings at cache_memory.rs:1448-1463 are unchanged, and only the leading sentinel_granules*alignment of row 0 is aliased, with the tail mapped separately at cache_memory.rs:1428-1437. Row 1 starts at fixed_bytes which is >= sentinel_bytes, so no live row shares the sentinel page.
  4. Zeroing order is safe: the memset of the sentinel granule (cache_memory.rs:1469-1472), and the tail (:1473-1482), both precede the plane zeroing and cuCtxSynchronize at :1494-1495, and all mappings are created before any graph/transfer runs. Zeroing the shared granule once is sufficient because all aliases see the same physical page.
  5. Teardown is correct: release_execution_resources iterates allocation.mappings and calls driver.unmap per recorded range (helios/src/runtime_core/mod.rs:1565-1569), and map_cache_chunk pushes one entry per mapping (cache_memory.rs:1523-1527), so the 39 sentinel mappings are each unmapped. No double-unmap and no leaked VA.
  6. Peer access is consistent: grant_storage_access grants per recorded mapping (helios/src/runtime_core/peer_access.rs:28-33), so each sentinel granule mapping gets its own cuMemSetAccess; with peer readers this is sentinel_granules * readers driver calls — a startup-time cost, not a hot path.
  7. No hot-path impact: this is all load-time. Nothing here touches admission, scheduling, or per-token work, so there is no lock/queue/contention or memory-amplification consequence at serving time. No new unbounded buffer: the mappings: Vec<_> built at cache_memory.rs:1418-1426 is bounded by sentinel_granules (row_bytes/granularity) and dropped after the call.
  8. Error propagation is honest in the new code: every arithmetic step in handle_charge and row_backing_bytes uses checked_* and returns invalid(...); there is no NaN/silent-wrap path. The one span - saved at memory.rs:411 cannot underflow because saved <= (units*unit_bytes)/align*align <= span for units >= 1, and saved == 0 when units == 0 (:405-409).
  9. No per-model branch, no new flag/knob/config default, no wire/Protobuf/CLI/Prometheus change: the diff touches only the three listed files, so existing cores still load (charter "keep the runtime small and model-agnostic" satisfied).
  10. pack_prefixes carries sentinel_granules through (cache_memory.rs:484-490), so compaction does not silently drop the saving or the charge. Good.

#8 [high] Research summary

Review complete for the Correctness, Contracts & System-Level Consequences lens on PR #659. Full findings are in my scratchpad (6 notes).

Verdict: the change is arithmetically correct and well-placed, but has two Majors that should be resolved before merge, plus one claim-accuracy Major.

Major 1 — the safety premise is unenforced in the layer that can violate it. Row zero is now one shared writable page mapped at up to floor(row_bytes/alignment) offsets (cache_memory.rs:1418-1427), so any row-0 write becomes visible at every leading granule offset at once — turning a formerly-local corruption into a silent wrong-logits corruption. Helios' own transfer path accepts row 0 with only a bounds check (offload/transfer.rs:156-163), and an in-repo #[ignore]d GPU test (offload/gpu_tests.rs:1476-1481) uses StateSlotId(0) as a real checkpoint slot and writes it. Fix: reject index == 0 at that bounds check and fix the test fixture.

Major 2 — the new allocation path has zero executed coverage. The sentinel mapping and split zeroing (cache_memory.rs:1416-1488) are reachable only via allocate_shared_cache from memory.rs:1300, which only the unreached GPU test exercises. The new CPU test (cache_memory.rs:1367-1385) asserts Layout fields and handle arithmetic only. The PR also reduced the GPU test's assertions (row 0 dropped from the distinct-pattern upload, .skip(1) at :1226). Fix: run the GPU test, or drive allocate_shared_cache through the existing mock driver and assert mapping offsets plus two memsets.

Major 3 — the "reclaimed" bytes are actually spent on cache, which the description calls a pure reclaim. row_backing_bytes feeds capacities/fits/minimum-footprint/pool budget (memory.rs:486,510,523,1003), so identical hardware now plans more KV pages and snapshot rows and reports a different state_rows. Also unstated: the saving costs sentinel_granules * row_readers extra mapping handles per rank, which can push the aggregate past RM_HANDLE_RANGE and refuse a load that main accepts — exactly the budget #391 created, whose headroom this PR spends (518,232→518,504 handles; 1.2%→1.1%).

Verified sound: virtual span preservation, unique backing for live/snapshot rows, zeroing order, per-mapping teardown/unmap, peer grants, checked arithmetic throughout, and no hot-path or wire/Protobuf/CLI/metric contract change. Evidence is unit-test plus arithmetic only (no served-workload or VRAM measurement, charter #210 / principle 12), and the Design-Signed-Off-By trailer could not be verified with my tools.

#9 [high] CORRECTION to note 6: exact handle delta is 2 -> 19 per rank (+17, x16 = +272); my earlier hedge was wrong

This supersedes item 1 of entry 6 (which hedged "16 granules -> 2 -> 17 ... note the fixture"). The correct derivation, for the DCP16 fixture at helios/src/runtime_core/cache_memory.rs:815-834 (row_bytes = 35_122_432, a = 2 << 20 = 2_097_152, row_readers = 1):

This exactly reproduces the assertion changes at cache_memory.rs:818-819 (494576 -> 494848, 647544 -> 647816, i.e. +272 each) and :832-834 (518232 -> 518504), and the docs re-baseline at docs/runtime-core-design.md:832-833 (headroom 6,056 / 1.2% -> 5,784 / 1.1%). So the handle-cost claim in entry 4 is confirmed by hand, not just by the test.

Scaling to peer-read rows (row_readers > 1): cost is sentinel_granules * row_readers mappings, so a 16-reader row plane on an 82,143,488 B row (39 granules) is 39 * 16 = 624 mappings per rank versus 16 before — a 39x increase in that term. That is the number to quote when arguing about RM_HANDLE_RANGE margin.

#5 [medium] MINOR: duplicated alignment source between row_backing_bytes (memory.rs) and Layout.sentinel_granules (cache_memory.rs)

FINDING (Minor, correctness/consistency).

row_backing_bytes uses the alloc's own alignment, while the layout and the actual mapping path use the row plane's alignment:

helios/src/runtime_core/memory.rs:398-409

            let align = a.alignment as u64;
            let span = units
                .checked_mul(s.unit_bytes)
                ...
            let saved = if units > 0 {
                super::cache_memory::sentinel_saved_bytes(s.unit_bytes, align)

versus the allocator, which always uses layout.alignment: helios/src/runtime_core/cache_memory.rs:1416-1427 ((0..layout.sentinel_granules) mapped in layout.alignment steps) and cache_memory.rs:259-262 (row_bytes / row_alignment).

Today these agree because CacheGeometry::validate/Layout::unmerged rejects mismatched plane alignments (cache_memory.rs:131-139), so this is not a live bug — but the two formulas are duplicated rather than shared, so a future partial alignment (a real possibility: alias_plane at cache_memory.rs:73-77 already reasons about per-plane granularity) would make the planner's saved bytes differ from what is actually mapped. Recommendation: pass/derive the row alignment from one place (have row_backing_bytes take the row plane alignment, matching Layout), and add a debug assert that they agree.

#7 [medium] MINOR/process: evidence is unit-test+arithmetic only; verification-table row 14 (inactive rows) is exactly the unrun GPU test; sign-off trailer unverified

Process/evidence findings to include (Minor):

  1. Charter evidence gap (charter "Bring real evidence. Performance PRs need benchmarks showing an actual speedup over main on a served workload (#210)"; docs/design-review.md:106-115 principle 12 requires "actual Helios service measurements" for performance claims and "disclose unrun checks"). This PR's evidence is CPU unit tests + arithmetic; there is no live VRAM reading or flare run measurement of the reclaimed MiB. The headline figures ("32 MiB/rank on a 35 MiB row", "76 MiB/rank on an 82 MiB row") are computed from sentinel_saved_bytes, not measured. The description is honest that GPU tests were not run, so this is a disclosure-quality point, not a misrepresentation. For a memory (not latency) claim, one nvidia-smi/plan cache before/after on a real GDN or Mamba core would close it.

  2. Verification-table mismatch worth flagging: docs/verification.md:14 puts "CUDA ordering, captured state, inactive rows, allocation stability, or resource lifetimes" on "Real execution tests on assigned GPUs". This PR changes inactive-row (row zero) allocation and its zeroing — squarely that row — and the GPU test covering it was both weakened and not run. Compare docs/design-review.md:180-190 (layer 1 CPU tests) is satisfied and reported.

  3. Precedent note (for the adjudicator, not a defect): #391 and #473 merged with the same VMM GPU tests unrun, so the disclosure position is not unprecedented; the difference here is that this PR additionally reduces the assertions in that GPU test.

  4. Design-Signed-Off-By trailer on 16e22476 could not be verified with the tools available to me (.githooks/commit-msg:15-63). Flag for a maintainer check; #391 had a blocking review item for a missing trailer. I did not change files, so I cannot confirm either way.

  5. No linked issue, no roadmap item, no community demand for this saving (Dossier confirms). Charter "What gets merged" includes "a measured performance/memory issue" — the class fits; the measurement is the gap.

  6. Doc update is accurate and consistent with the code: docs/runtime-core-design.md:772-780 documents the aliasing, the tail, the unique backing of live rows and the exact saved formula; :829-833 re-baselines the DCP16 example. Prose follows the repo's required explanation scheme (docs/design-review.md:147-162), and the Discord line is present on the PR.

#10 [medium] MINOR: observable accounting shift — gpu_bytes / "Allocate cache" phase total now drops; inspect surfaces unchanged

Metric / observability span check requested by the lens.

  1. Startup progress total changes scope. helios/src/runtime_core/memory.rs:1249 now accumulates row_backing_bytes(core, rows - snapshots) instead of bytes(core, 0, rows - snapshots), and that total becomes the phase denominator/total: memory.rs:1291 let phase = progress.phase("Allocate cache", Some(gpu_bytes)); memory.rs:1341-1345 prints "{:.1} GiB · {} KV tokens · {snapshots} shared snapshot slots · limited by {limiting}" from gpu_bytes. Assessment: this is the correct direction — the number is meant to be physical cache backing and was previously over-reported by the null row's leading granules. Consequence to note: the "Allocate cache" GiB figure will be smaller than on main for the same model/hardware while pages/rows are numericly larger, so a before/after startup-log comparison looks contradictory unless the report says the two numbers changed meaning together. No rate/latency/admission metric is touched (nothing in helios/src/server/metrics/ changes).

  2. flare inspect surfaces are deliberately NOT changed and remain virtual: helios/src/runtime_core/describe.rs:571-583 (virtual_bytes from unit_bytes * maximum rounded) and describe.rs:191-214 (accumulate_sizing -> state_row_bytes = sum of unit_bytes). That is right (they describe the core's virtual extent, not Helios' physical plan), so --memory-map will not show the saving. Worth one sentence in the report so nobody files the mismatch as a bug: the saving is visible only in the startup "Allocate cache" line, plan cache row/page counts, and (after the fact) nvidia-smi.

  3. No fan-out/latency span changes: no change to estimated_seconds, worth_fetching, inbound_rate, or any rank-0-vs-all-shards sampling. All new work is load-time and O(sentinel_granules) driver calls.