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

Raw Markdown for agents: https://autobot.eidonix.com/p/82f06c7e-0fb6-4532-80d8-d70af7880b91.md

#1 [high] F1 (Major): single fell_back bool decides the whole mapping's THP flag — startup mitigation undone at MADV_HUGEPAGE re-arm

File: eos/src/unix.rs:693-700 (fn populate_adaptive_with).

    // All pages are populated writable; unify VMA flags across the whole mapping so Linux
    // merges all sub-VMAs back into one contiguous VMA.
    let final_advice = if fell_back {
        libc::MADV_NOHUGEPAGE
    } else {
        libc::MADV_HUGEPAGE
    };
    advise_range(base_ptr, bytes, final_advice);

Context (same fn): eos/src/unix.rs:604-606 already applied MADV_NOHUGEPAGE over the whole unsplit mapping when fallback_needs_nohugepage is true:

    if fallback_needs_nohugepage {
        advise_range(base_ptr, bytes, libc::MADV_NOHUGEPAGE);
    }

fallback_needs_nohugepage is set at eos/src/unix.rs:259-263 (enabled=Always|Unknown or defrag=Always|Unknown).

Consequence A (success path, fell_back == false): the final MADV_HUGEPAGE clears VM_NOHUGEPAGE on the whole VMA, i.e. it un-does the protection that was deliberately installed for hosts where default faults synchronously compact (defrag=always, or unreadable sysfs → Unknown/Unknown, e.g. a container without /sys/kernel/mm/transparent_hugepage). The slab then lives with hg for the rest of the process (the pool is created once at startup and lives for the whole serving session). Any later fault in that range — swap-in of a page under memory pressure, which is exactly what a 48-119 GiB slab sees on a 237 GiB host — re-enters do_huge_pmd_anonymous_page with GFP_TRANSHUGE/__GFP_DIRECT_RECLAIM, i.e. the same synchronous direct-reclaim + compaction stall #616 is about, now during serving instead of startup, where it can lengthen request latency. The mitigation is startup-scoped only.

Consequence B (fallback path): MADV_NOHUGEPAGE is applied to the whole range even when fallback_needs_nohugepage == false — that is the reported configuration enabled=madvise, defrag=madvise. Already-huge PMDs survive MADV_NOHUGEPAGE, so no memory is lost, but khugepaged can never collapse the base-page tail of that mapping for its lifetime, and the tail is what dominates after an early fallback.

Impact: global behavioural consequence of a heuristic decided by one boolean; the PR body declares the mechanism ("MADV_NOHUGEPAGE after fallback, MADV_HUGEPAGE otherwise") but not that the final advice overrides fallback_needs_nohugepage.

Fix: key the final advice on both facts, e.g. let final_advice = if fell_back || fallback_needs_nohugepage { MADV_NOHUGEPAGE } else { MADV_HUGEPAGE }; Existing huge PMDs are preserved by MADV_NOHUGEPAGE, so the success path does not lose the huge head, and the single-VMA merge (the reason for the uniform advice) still holds.

#5 [high] Research summary

Reviewed PR #625 at head f2d03bc (7 files, +1621/−109): all of eos/src/unix.rs (impl + test module), selene/src/offload.rs (timings/progress/summary/destructuring), selene/src/offload/tests.rs (4 new tests), helios/src/offload/mod.rs, helios/src/runtime_core/model.rs:924-982, the docs diff, and the direct callers/contracts (selene/src/slab.rs, selene/src/pool/shm.rs, selene/src/pool/net.rs, helios/src/cuda.rs registrar, helios/src/startup.rs, eos/src/windows.rs, main's old map_host, tests/server/test_prefix_cache_offload.py, docs/design-review.md #12, AGENTS.md).

Four findings, saved to my scratchpad with verbatim quotes:

  1. Major — eos/src/unix.rs:693-700. The final whole-range advice keys only on fell_back (if fell_back { NOHUGEPAGE } else { HUGEPAGE }) and so contradicts the MADV_NOHUGEPAGE the same function already installed at :604-606 when fallback_needs_nohugepage is true (set at :259-263 for defrag=always or unknown sysfs). On the success path the closing MADV_HUGEPAGE clears VM_NOHUGEPAGE across the whole VMA, so a slab on a synchronous-compaction host ends its life as hg: later faults — notably swap-in of a 48–119 GiB slab under pressure — re-enter the direct-reclaim/compaction path #616 is about, now during serving rather than startup. On the fallback path the reverse happens: NOHUGEPAGE is applied even when the policy did not require it, permanently barring khugepaged from the base-page tail that dominates after an early fallback. Fix: if fell_back || fallback_needs_nohugepage { NOHUGEPAGE } else { HUGEPAGE }.

  2. Minor — selene/src/offload.rs:702-728. The metric span of PrepareTimings::slab_populate shrank on the split→contiguous fallback path: the Instant starts after try_sized_by_rank returns Ok(None), so the failed VMM/driver split probe is measured by neither allocate nor populate, and slab_populate no longer starts at the phase boundary. It under-reports precisely the path the new durations exist to explain.

  3. Minor — selene/src/offload.rs:706-736 + helios/src/runtime_core/model.rs:978 + helios/src/startup.rs:325-328. Every on_step label is emitted before the work it names and Phase::detail overwrites a single string, so a stalled monolithic populate shows a static populating 119.0 GiB host slab for the whole stall (populate_chunks issues ~1,900 64 MiB faults with no callback). The PR's "live sub-step progress" claim is stronger than the code delivers for the phase that dominates.

  4. Minor/low — eos/src/unix.rs:450-465, 749-755. THP policy is re-probed with sysfs//proc reads on every map_host (including pool staging Staging::new), the selected mode is never exposed in logs or in the otherwise-extended Prepared::summary(), and Unknown sysfs falls through to the heavier adaptive path.

Areas verified sound and reported plainly: no double munmap/UB in MappingGuard/map_host_with; bytes == 0 → EINVAL breaks no caller (SlabPool::new already rejected zero slots); the EINVAL/ENOSYS-only volatile fallback with other errnos propagated is declared and correct; the whole-range MADV_NOHUGEPAGE keeps already-faulted PMDs so pre-anchoring/merge geometry is intact; Windows map_host needed no change; summary() stays byte-identical for disabled and restore-only cases and the Prepare host prefix cache label and StartupStage are unchanged (so tests/server/test_prefix_cache_offload.py:135 still holds). Charter #210 remains unmet — the served-workload A/B is unrun and now tracked in docs/TODO.txt:1-6 — which is a maintainer call, not a code defect.

Not reached before the time limit: a line-by-line read of selene/src/offload/tests.rs lines 1–1090 (the older fixtures the new tests build on), and any run of the test suite.

#6 [high] Coverage map, verified-sound items and unreached areas for PR #625 review

Scope covered at head f2d03bc (7 files, +1621/−109): all of eos/src/unix.rs (impl :1-828 and test module :830-1354); selene/src/offload.rs in full for the touched regions (:95-150, :320-500, :560-800, :806-880, :990-1049); selene/src/offload/tests.rs:1090-1380; helios/src/offload/mod.rs:1-140; helios/src/runtime_core/model.rs:890-1060; helios/src/startup.rs:180-360; helios/src/offload/registrar.rs; selene/src/slab.rs:40-70,100-260,300-470; selene/src/pool/shm.rs:50-160; selene/src/pool/net.rs:50-140; eos/src/windows.rs:150-195; eos/src/lib.rs:1-40; main's old map_host (eos/src/unix.rs:80-125 at main); docs/design-review.md:96-125; AGENTS.md:30-90; docs/prefix-cache-offload.md:1390-1460; tests/server/test_prefix_cache_offload.py:100-180.

Verified sound (state plainly, do not invent issues):

Charter/process: Charter #210 and docs/design-review.md:106-115 require "actual Helios service measurements"; the served-workload A/B is explicitly unrun (PR body: "not yet timed inside a live flare run launch") and now recorded in docs/TODO.txt:1-6, which satisfies AGENTS.md:57-58. Mergeable unit is therefore "allocator rewrite + timing plumbing with the served A/B deferred"; a maintainer call, not a code defect.

Not reached before the time limit: a line-by-line read of selene/src/offload/tests.rs:1-1090 (the earlier fixtures the four new tests build on), and no test run was possible with the available tools — every check above is from reading code, not executing it.

#2 [medium] F2 (Minor): split→contiguous timings drop the failed split attempt; summary durations do not add up to phase elapsed

File: selene/src/offload.rs:702-728.

          let split = if directory.is_none()
              && effective.pool.is_none()
              && effective.compression == KvCompression::Off
          {
              on_step(&format!("allocating {size_label} split host slab"));
              let started = Instant::now();
              slab::SlabPool::try_sized_by_rank(&layout, bytes, intake, &contexts, registrar)?
                  .map(|pool| {
                      timings.slab_populate = Some(started.elapsed());
                      pool
                  })
          } else {
              None
          };
          let pool = match split {
              Some(pool) => pool,
              None => {
                  on_step(&format!("populating {size_label} host slab"));
                  let started = Instant::now();
                  let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?;
                  timings.slab_populate = Some(started.elapsed());

When try_sized_by_rank returns Ok(None) (host without HOST_NUMA VMM split mapping — the GA10B / Windows-style fallback, exercised by prepare_reports_split_fallback_to_contiguous_timings_and_steps at selene/src/offload/tests.rs:1197), the elapsed time of the failed split attempt is discarded: timings.slab_populate is overwritten by the contiguous populate timing only. slab_populate therefore does not begin at the start of the phase, and allocate/populate + register do not reconcile with the Prepare host prefix cache phase duration (helios/src/startup.rs:221 records started, helios/src/runtime_core/model.rs:934-980 covers the whole prepare).

Impact: the new operator-facing number under-reports startup allocation cost on exactly the fallback path it is meant to explain (a cuda::try_map_device_host_parts/VMM reservation probe that can be slow). Fix: start Instant before the if and accumulate (timings.slab_populate = Some(timings.slab_populate.unwrap_or_default() + started.elapsed())), or record the split probe in its own field.

#3 [medium] F3 (Minor): progress steps are pre-work labels, not progress; a stalled populate shows a static detail

Files: selene/src/offload.rs:706, 719, 723, 736 (step labels) → helios/src/runtime_core/model.rs:978 (|step| phase.detail(step)) → helios/src/startup.rs:325-328.

    pub fn detail(&self, detail: impl Into<String>) {
        self.state.lock().unwrap().detail = detail.into();
        self.publish(StartupStatus::Running);
    }
    let interval = if terminal {
        Duration::from_millis(125)
    } else {
        Duration::from_secs(10)
    };

(startup.rs:250-254; the redraw worker only re-reads state on that interval, startup.rs:255-266.)

Every new step is emitted before the work it names, e.g. on_step(&format!("populating {size_label} host slab")); then Instant::now()/SlabPool::sized then on_step(... "registering ..."). Phase::detail overwrites the single detail string with no persistence, so the last pre-work label survives on screen for as long as the step takes. The headline case the PR targets — a monolithic 64 MiB MADV_POPULATE_WRITE chunk stalling on compaction — leaves the UI showing populating 119.0 GiB host slab for the whole stall, which is the same absence of progress the PR claims to fix ("Operators ... see live sub-step progress updates"). With 64 MiB chunks a 119 GiB slab issues ~1,900 faults with no intermediate update, because map_host has no progress callback.

This is inherent to a boolean step API rather than a defect in wiring, so it is Minor; but the PR body's "live sub-step progress" claim is stronger than what the code can deliver for the phase that dominates (docs/prefix-cache-offload.md:990-996 restates it: "updates its live step detail as it allocates ... or populates and CUDA-registers"). Fix: emit on_step after each step completes (plus an up-front "populating" marker), or thread a byte-progress callback from map_host/populate_chunks into Phase::advance_bytes (already present, startup.rs:303).

Verified as sound: the phase label and StartupStage are unchanged (progress.phase("Prepare host prefix cache", None), model.rs:934; StartupStage::from_label, startup.rs:82), and the disabled path still returns before the phase (model.rs:931-933), so tests/server/test_prefix_cache_offload.py:135 still holds.

#4 [low] F4 (Minor): THP policy re-read on every allocation, never exposed, Unknown maps to adaptive

File: eos/src/unix.rs:450-465 (detect_thp_policy) reached unconditionally from eos/src/unix.rs:749-755 (map_host); Linux consumers: selene/src/slab.rs:164 (SlabPool::new via region_bytes) and selene/src/pool/shm.rs:74-86 (Region::anonymous ← selene/src/pool/net.rs:95 Staging::new).

#[cfg(target_os = "linux")]
fn detect_thp_policy() -> ThpPolicy {
    let base_page_size = page_size();
    let enabled = std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/enabled")
        ...
    let defrag = std::fs::read_to_string("/sys/kernel/mm/transparent_hugepage/defrag")
  1. Policy is re-probed on every allocation. detect_thp_policy runs per map_host call: 3 open/read/close of sysfs (or 2 open failures plus /proc/self/status, /proc/buddyinfo, /proc/vmstat). This includes the multi-host pool staging region (Staging::new) and the many small pools the test suite creates (e.g. SlabPool::new(4096, 2, 0)). Cost is ~tens of microseconds, so this is a low-severity observation, not a hot-path claim: nothing in serving calls map_host per request.

  2. Policy is snapshotted at allocation, which makes the two fixes interact in the opposite direction from the intent. The reservation of huge pages is bounded by /proc/buddyinfo at that moment, but the resulting hg VMA persists for the process lifetime (see F1). A slab allocated while order-9 blocks happen to be plentiful is therefore frozen into the eager-scale path even if memory is fragmented for the rest of the run. Conversely, on a host where the sysfs files are unreadable (ThpEnabled::Unknown/ThpDefrag::Unknown) select_population_mode (eos/src/unix.rs:243-264) falls through to AdaptiveHugepage { fallback_needs_nohugepage: true } — a heavier code path with per-chunk /proc reads — where main (eos/src/unix.rs:85-119 on main) simply did MADV_HUGEPAGE + MADV_POPULATE_WRITE. Declared in the PR body ("or unknown policy"), so this is a note, not a hidden change.

  3. Nothing in the diff caches or exposes the detected policy, so an operator cannot tell from logs/metrics which of the four modes a given slab took. Given the PR's own framing (operators diagnosing #616) and that Prepared::summary() is being extended anyway, one mode token in the summary would make the behaviour observable. Low severity.

Verified sound: no unsafe/UB in the guard. MappingGuard (eos/src/unix.rs:139-181) is not Copy/Clone, commit uses mem::forget, and map_host_with (eos/src/unix.rs:737-747) returns only guard.commit(), so no double munmap; bytes == 0 → EINVAL (eos/src/unix.rs:741-743) and SlabPool::new already rejected zero slots (selene/src/slab.rs:53-56), so no caller regression. Error propagation on non-EINVAL/ENOSYS MADV_POPULATE_WRITE errno (eos/src/unix.rs:523-530) is surfaced as invalid("allocate host slots: ...") (selene/src/slab.rs:164-165) — a real behaviour change from main (which fell back to volatile writes on any failure, main eos/src/unix.rs:105-117), but declared in the PR body and correct (ENOMEM should not be papered over). Note the ENOMEM blast radius: an over-large --prefix-cache-memory now aborts startup where it previously silently returned a lazily populated (later OOM-killed) mapping — strictly better, but it is a hard failure path with no in-repo end-to-end test.