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

Raw Markdown for agents: https://autobot.eidonix.com/p/ebb8d899-f42f-4626-b37a-a30a7d4b4140.md

#1 [high] Gate wiring map and verified code facts (PR #628)

VERIFIED by opening files at PR head 1870a27.

Gate implementation: helios/src/offload/copy_gate.rs (new, 263 lines).

Graph path: helios/src/execution/ranks.rs

Offload paths gated:

NOT gated:

Detection: helios/src/runtime_core/mod.rs:1144-1156 sets has_peer_copies only for Node::Copy whose allocation is Memory::Peer (format.rs:43-49); pushed per graph at mod.rs:1238; mapped to execution graph order at runtime_core/serving.rs:49-59 (index-by-name lookup) → correct index alignment with manifest.graphs.

Manifest field: helios/src/execution/manifest.rs:436-449; has_peer_copies used only in the ranks.rs test (no validate() check that peer_copy_graphs.len() == graphs.len()).

Release boundary: guard released only when RankExecutor::poll returns a completion, i.e. after the frame completes on all ranks incl. host readback — conservative, not early.

Docs contract contradicted (no docs/ file in the 14 changed files):

BATCH_BYTES = 16<<20, BATCH_ENTRIES = 4096 (helios/src/cuda.rs:169-171). Evidence: PR description quotes 1,176 Node::Copy peer nodes in the prefill7168 graph.

#2 [high] Findings F1-F6 for correctness/system-consequences lens

F1 (Major) Unbounded block of the model worker thread reverses a documented invariant. helios/src/offload/copy_gate.rs:45-56: pub fn enter_peer_graph(self: &Arc) -> PeerGraphGuard { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); state.peer_graphs_waiting += 1; while state.offload_batches_active > 0 { state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); } Taken on the model worker thread before any CUDA work: helios/src/execution/ranks.rs:90-101: let guard = if self.peer_copy_graphs.get(graph).copied().unwrap_or(false) { self.copy_gate.as_ref().map(CopyEngineGate::enter_peer_graph) No timeout, no cancellation, no liveness. The engine's own 120 s stall detector (helios/src/execution/threaded.rs:23 const TIMEOUT: Duration = Duration::from_secs(120), checked in poll_ranks at threaded.rs:942-952) cannot fire because submit has not returned. Before this PR the offload tier was explicitly isolated from that thread: docs/prefix-cache-offload.md:133 "Offload work never blocks the model worker thread or the model stream."; :907 "The model stream never waits on an offload event."; :1015 "The model worker thread never waits for offload work." Impact: any stuck offload batch (a driver-level event.synchronize() that does not return — exactly the #627 failure class — or a wedged copy_batch) now propagates into the request-serving thread instead of being contained to the offload threads, converting a cache-tier stall into a full serving hang with no timeout. Fix: bounded wait (Condvar::wait_timeout) with a monitored counter, or acquire the guard on the executor side and let submit proceed with a logged deferral; and update docs:133/907/1015 + docs/same-process-tp.md:177-180 (Not qualified list names this exact region).

F2 (Major) Offload can be starved indefinitely by the priority rule; no aging/timeout. helios/src/offload/copy_gate.rs:60-67: pub fn enter_offload_batch(&self) -> OffloadBatchGuard<'_> { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); while state.peer_graphs_active > 0 || state.peer_graphs_waiting > 0 { state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); } TP decode graphs are peer-copy graphs too, and frames are pipelined/back-to-back (threaded.rs:202-209: rank zero publishes Commit "BEFORE calling local.submit()"), so peer_graphs_waiting > 0 can hold continuously for a whole busy serving window. The only test (copy_gate.rs:205-239 peer_graph_takes_priority_over_continuous_offload_stream) asserts the peer side is not starved; nothing bounds offload starvation. When offload cannot progress, helios/src/offload/transfer.rs:641-645 refuses at QUEUE_DEPTH (selene/src/copier.rs:16 pub const QUEUE_DEPTH: usize = 16;) → pending.error → StoreEvent::Stored{result: Err} → server/runtime.rs:2387-2392 prints HOST_CACHE_STORE_ERROR and bumps host_retry_abandoned[5]. Net effect under sustained prefill: host-prefix-cache writes are abandoned exactly at peak load, so the next burst loses the warm path the PR's own evidence relies on (5.08x/2.45x). Fix: bounded wait + periodic re-admission (after N peer graphs or T ms, allow one batch), and count gate-deferred stores.

F3 (Major) Metric span expanded: gate wait is charged to codec transform time and to tier transfer rates. (a) helios/src/offload/transfer/codec.rs:283-290: let start = Instant::now(); ... let stored_len = { let mut guard = gpu.codec.lock().unwrap(); let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); let res = guard.encode_pages_batches_with( with stats.transform_ns += start.elapsed() at codec.rs:302/335/369 (same pattern at 664/667/688 and 749/752/769). That counter is exported as flare_kv_codec_transform_nanoseconds_total "Cumulative time spent in KV checkpoint codec transforms and coding" (helios/src/server/metrics.rs:686-690). Gate wait (peer-copy graph contention) is now reported as codec transform time. (b) Bigger: the tier rate samples. selene/src/memory.rs:1450-1457 self.outbound_rate.observe(reply.bytes, reply.elapsed) / inbound_rate.observe(...), where elapsed is submit→last-rank-reply (helios/src/offload/transfer.rs:752-754), i.e. it now includes time the offload thread spent blocked in enter_offload_batch. Rates feed estimated_seconds (selene/src/memory.rs:1174, selene/src/disk_store.rs:3242, composite.rs:375) and admission pricing worth_fetching/worth_transfer (selene/src/store.rs:423-442: estimated_seconds < 0.5 * gained_tokens / prefill_tokens_per_second.max(1.0)); Rate keeps a 3-sample median (selene/src/levels.rs:57-68) recovering only toward the seed over RECOVERY. So a handful of prefill-contended restores permanently depress the advertised tier rate and make the store reject restores that would pay off — pessimism concentrated exactly when prefix-cache hits matter (concurrent prefill). Fix: time the copy only (start after acquiring the guard), and/or keep gate wait in a separate counter.

F4 (Major) The entire gated offload branch has zero test coverage in-repo; the new tests exercise only the mutex. Every Copiers construction in the tests passes no gate, so copy_gate is None and both gated arms are dead in test builds: helios/src/offload/gpu_tests.rs:126,286,456,588,650,856,1004,1266,1271,1558 and helios/src/offload/transfer/codec.rs:1129,1133,1249,1359,1363 all use Copiers::new(...). The only with_gate(..., Some(_)) callers are production: helios/src/runtime_core/model.rs:986-989 and helios/src/server/runtime.rs:731 via offload/mod.rs:121-130 (open() passes None). Consequently transfer.rs:398-434 (gate + DrainOnDrop + per-batch record/synchronize), codec.rs:976-1002 gated flush, and codec.rs:290/318/352/668/752 acquire sites are never executed by any test — yet they are the code that must not deadlock or leave the stream un-drained. Also missing: no test that RankExecutor releases a guard on poll/close (ranks.rs:108-124, 170-181); the only new executor test is the pure-manifest union at ranks.rs:188-201.

F5 (Major) Claim accuracy: "zero gate overhead" and "pool and CPU codec paths share the same wiring" are both narrower than written.

F6 (Minor) Working-set serialization inside the GPU codec lock. codec.rs:666-668 and :751-752 acquire try_lock() first and then call enter_offload_batch() while holding gpu.codec. Lock order is consistent with the claim (no inversion), but an offload thread waiting out a peer-copy graph now holds the single shared GPU-codec mutex, so all other ranks' GPU-codec work (and the try_lock fallback that exists to keep restores off the critical path, codec.rs:683-716, 764-772) is blocked behind that wait. Fix: acquire the batch guard before the codec lock, or drop the codec lock and retry.

Sound areas (say so plainly): Fence ordering for guard release is correct (cache.rs:20-22 Ord; ranks.rs:114-122 front-only pops are safe because guards are pushed in submit order); the Ok(None) backpressure path drops the guard without leaking (ranks.rs:102-104); close() releasing residual leases after inner close (ranks.rs:170-181) is what lets Transfers::close drain instead of erroring; peer_copy_graphs index alignment with manifest.graphs is correct (runtime_core/serving.rs:49-59 maps by graph name via self.names, pushed in lockstep with graphs); absent/empty defaults are genuinely backward compatible (manifest.rs:447-449) with no proto/format change; per-NativeModel Arc sharing is real (model.rs:27, 662, 988, 1036); DrainOnDrop ordering after the guard declaration correctly drains before release on error (transfer.rs:407-419); lock ordering gpu.codec → gate is consistent everywhere.

#3 [high] Research summary

I reviewed all 14 changed files plus their direct callers, contracts, docs and tests, and recorded six concrete findings (citations, verbatim quotes, severity, impact, fix) in the scratchpad under "Findings F1-F6", alongside a verified wiring map in entry 1.

Summary of what I found:

I also verified and stated plainly the areas that are sound: fence ordering for guard release, no guard leak on the Ok(None) backpressure path, correct index alignment of peer_copy_graphs with manifest.graphs, genuine backward compatibility with no proto/format change, real per-NativeModel Arc sharing, and consistent gpu.codec → gate lock ordering with correct drain-before-release on the error path.

#4 [high] Verbatim PR-description claims vs the diff (claim-accuracy lens)

Quotes are verbatim from the PR #628 description (head 1870a27), for the report's claim-accuracy section.

  1. Claim: "Graphs without peer-copy nodes do not touch the gate." and (Resulting behavior) "zero gate overhead on graphs without peer-copy nodes." Contradicted for the offload side: the gate is attached to EVERY offload binding unconditionally —
  1. Claim: "Record peer_copy_graphs[i] = true whenever any Node::Copy node in graph i has a Memory::Peer source or destination" — accurate, verified at runtime_core/mod.rs:1149-1156, 1238 and serving.rs:49-59. Coverage gap: kernel-driven DMA and copies to a peer-mapped local Memory::Device allocation are not marked (Memory::Peer semantics at runtime_core/format.rs:43-49: "Another rank's device allocation, referenced at its recorded address").

  2. Claim: "Share one Arc<CopyEngineGate> per NativeModel across RankExecutor, local offload::Binding / offload::open_with_gate, and NativeModel::attach_offload (Selene pool workers)." Narrower than it reads: heliopause/src/python.rs:331 peer_copy_graphs: Vec::new(), means any Python/Heliopause-built manifest never marks peer graphs, so the graph side never engages on that path; helios/src/offload/shard.rs:44-50 join_peer(store, rank, &super::transfer::Copiers::new(gpu_cubins), ...) leaves the multi-host disk-store peer rank ungated. The Limitations paragraph does concede "Multi-host TP, live Selene pool serving, live CPU KV codec serving, and non-SM120 GPUs were not tested end-to-end".

  3. Claim: "release completed leases in RankExecutor::poll" — verified ranks.rs:114-122. Note the release point is conservative: a guard is dropped only when a full frame completion (all ranks, incl. host readback) is returned by poll, not when the GPU work finishes, so the gate stays closed longer than strictly necessary; combined with F2 this lengthens offload stalls.

  4. Claim (Validation): "helios offload::copy_gate + execution::ranks: 5/5 passed (multi-rank concurrency, peer-graph wait/drain, priority under continuous offload, panic-unwind release, asymmetric rank union)." Verified: the file contains exactly 4 gate tests (copy_gate.rs:115, 134, 206, 242) plus 1 merge test (ranks.rs:189). All five exercise the mutex/condvar or the pure flag union only — none exercises the gated copy path (see F4). "zero gate overhead" and the per-batch cost are supported by no test or measurement anywhere in the diff. CI failed on the head commit; no test output is attached (matches the dossier).

#5 [medium] Charter/contract items verified for this change

Charter-compliant aspects I verified in the code (say so plainly, do not invent problems):

Charter rules not satisfied in the direction asked:

Merge-order note (not a defect): peer_copy_graphs is a new public field on ExecutionManifest (helios/src/execution/manifest.rs:436-439); open PR #621 edits the same struct, so a rebase to sequence is needed. No other open PR touches these hunks.

Also worth carrying: no validate() asserts peer_copy_graphs.len() == graphs.len() — the field is index-addressed and silently defaults to false past its end (manifest.rs:447-449), so a future producer that emits a short vector disables the gate silently. Cheap guard to add.