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

Raw Markdown for agents: https://autobot.eidonix.com/p/1c73bc27-76e2-4b07-b05b-f18cd8ab386b.md

#1 [high] Verified code map at head d6a00698 (PR #668)

All citations verified by reading files at PR head (pr/668, d6a0069).

collectives.py

host_ranks.py

serve.py

environment.py

runtime_patches/init.py :119 workers.register_hooks(); workers.py :26-29 from b12x.preparation import register_worker_initializer. → So b12x.preparation is imported by environment.apply() at serve.py:547, i.e. BEFORE serve_peer applies the peer env at host_ranks.py:646-648. Confirms dossier item B.

aot.py

tuning.py (NOT changed by PR, base)

bootstrap.py BasePreparationConfig.kernel_cache: Path | None = None :37; common_preparation_kwargs :123-137. rank_group.py prepare_group(..., ranks=None, checkpoint=None) :278-290 → ranks.prepare(...) :289 (never passes b12x_environment → the new kwarg is unused by callers).

#2 [high] Findings F1-F3 (high severity) — env ordering, corrupt-cache swallow, re-prepare amplification

F1 (Major) — Peer b12x env is applied AFTER b12x is already imported; the description's ordering claim is false. Chain verified at head: ignition/cli/serve.py:547 environment.apply(configuration, (gpu,)) → ignition/cli/environment.py:82 runtime_patches.apply() → ignition/runtime_patches/init.py:119 workers.register_hooks() → ignition/runtime_patches/workers.py:27 from b12x.preparation import register_worker_initializer. Only afterwards serve.py:549-555 knock(...) + serve_peer(..., kernel_cache=...), whose apply is at ignition/preparation/host_ranks.py:645-648: command = receive_object(control) if isinstance(command, tuple) and command[0] == "b12x-environment": os.environ.update(validate_b12x_environment(command[1])) command = receive_object(control) PR text: "sends non-empty b12x_environment ahead of assignment unpickling (so import-time reads see it)". Truth: it precedes recipe/operator imports (host_ranks.py:665 assignment, :670 prepare) but NOT b12x.preparation's import. environment.py:5-11 states the contract: "PyTorch, b12x, Triton, and the CuTe DSL read these variables when they are imported or first used." Impact: any B12X* setting b12x captures at import time still differs between rank 0 (which got it at serve.py:211 before apply) and peers — the exact asymmetry the PR removes for W4A16_A4_PREFILL. Also assignment["b12x_environment"] re-application at host_ranks.py:666-668 can never add anything the early command did not carry, so it is redundant. Fix: validate/reply-and-apply in _admit (host_ranks.py:276-299, reply at :297 currently {"accepted": True, "session": self.session}) and have join run knock() first, then environment.apply(configuration, (gpu,), b12x_environment), then serve_peer — i.e. #675's dropped ordering. Or document the invariant "peer env is not visible to b12x.preparation's import" in docs/ (no doc mentions b12x_environment; search of docs/ for reconcile_selections|b12x_environment returns nothing).

F2 (Major) — ForwardCache._load swallows OSError/ValueError/TypeError/KeyError/AttributeError/RuntimeError and unlinks the cached artifact. aot.py:64-76 _CORRUPT_ARTIFACT_ERRORS = (EOFError, pickle.UnpicklingError, struct.error, zlib.error, zipfile.BadZipFile, OSError, ValueError, TypeError, KeyError, AttributeError, RuntimeError); handler aot.py:1371-1380: except _CORRUPT_ARTIFACT_ERRORS as error: if required or isinstance(error, (MemoryError, torch.OutOfMemoryError)): raise Path(path).unlink(missing_ok=True) return None Impact: (a) a transient OSError (EMFILE/ENOSPC-on-read/EIO) or a genuine RuntimeError from load_compiled_function (driver/version faults) is silently converted into "cache miss", deleting a valid .bin and forcing a full recompile — charter #397 "don't just swallow, skip, or retry an unexplained error". (b) unlink(missing_ok=True) only suppresses FileNotFoundError; a read-only cache dir turns an opportunistic miss into a fatal PermissionError out of _restore (aot.py:1420) / _prepare. Fix: narrow the tuple to deserialization errors, log the swallowed error, and guard the unlink (try: ... except OSError: pass). Sub-note (Minor, test accuracy): the MemoryError arm at :1377 is dead — MemoryError is in none of the listed types (only torch.OutOfMemoryError subclasses RuntimeError). tests/preparation/test_forward_cache_sources.py:238-244 patches load to raise MemoryError and asserts propagation, so it passes trivially without exercising :1377.

F3 (Major) — one divergent rank now forces every job's re-preparation on all ranks (global changed, local configs). ignition/preparation/tuning.py:521-535 (base, not changed by PR, but its branch now fires far more often because the PR widens mismatch detection): if (self._coordinator is not None and len(self._coordinator.ranks) > 1 and (self.tuning_replica is None or self.tuning_replica.index == 0)): configs, changed = self._coordinator.reconcile_selections(requests) if changed: ... for job in self._jobs(requests): results.append(self._coordinator.prepare(self, job, progress=progress, autotune=self.autotune, selected_configs={plan: config for plan, config in configs.items() if plan in plans})) changed is computed over ALL gathered ranks (collectives.py:436-440) while configs holds only locally-divergent entries (collectives.py:441-449). So when rank 1 diverges, ranks that agree get configs == {} yet still re-enter prepare for every job with autotune=self.autotune. Collectively required for lockstep, but the override map is empty on the majority, so the agreeing ranks redo preparation work for nothing. On the GLM-5.3 TP2 case that is the expensive retry the dossier prices at ~2h15m, now triggered by payload divergence for a shared request name rather than by declaration divergence. Fix: also pass the rank's own already-agreed selection for each plan (or autotune=False on the reconcile pass) so the pass re-binds rather than re-races; and state the cost in the PR description.

#4 [high] Research summary

I completed the correctness/contracts/system-consequences lens over PR #668 at head d6a0069, opening every changed file plus its direct callers (ignition/cli/serve.py, ignition/cli/environment.py, ignition/runtime_patches/*, ignition/preparation/tuning.py, rank_group.py, bootstrap.py, core_snapshot.py, source_identity.py, planning.py, declaration.py) and the four touched test files.

Three findings carry the review, all verified from source at head (details and verbatim quotes are in scratchpad entries 1–3):

  1. Major — the peer b12x_environment is applied after b12x is already imported, so the PR's ordering claim is false. ignition/cli/serve.py:547 calls environment.apply(configuration, (gpu,)), which ends in runtime_patches.apply() (ignition/cli/environment.py:82) → workers.register_hooks() (ignition/runtime_patches/__init__.py:119) → from b12x.preparation import register_worker_initializer (ignition/runtime_patches/workers.py:27). Only then does serve_peer apply the env at ignition/preparation/host_ranks.py:645-648. It does precede recipe/operator imports and preparation (which is why B12X_W4A16_A4_PREFILL works), but any import-time-cached b12x setting still differs between rank zero and peers — exactly the asymmetry the PR claims to remove. The assignment["b12x_environment"] re-application at :666-668 is therefore redundant. Fix is the #675 ordering (apply in _admit/join before runtime_patches.apply()), or documenting the invariant.

  2. Major — ForwardCache._load swallows OSError/ValueError/TypeError/KeyError/AttributeError/RuntimeError and unlinks the artifact (aot.py:64-76, handler :1371-1380), so a transient I/O error or a genuine driver/runtime fault on an opportunistic restore is silently converted into a cache miss plus a full recompile — against charter #397 — and the unguarded unlink(missing_ok=True) turns a read-only cache into a fatal error. The MemoryError arm at :1377 is dead code (not one of the caught types; only torch.OutOfMemoryError subclasses RuntimeError), which the new test passes trivially.

  3. Major system-level consequence — one divergent rank forces every job's re-preparation on all ranks because changed is computed over all gathered ranks (collectives.py:436-440) while configs holds only locally-divergent entries (:441-449), and tuning.py:521-535 re-runs prepare(..., autotune=self.autotune, selected_configs={}) with an empty override map on the agreeing ranks.

Lesser findings: the forward-cache key hashes ambient os.environ B12X_* while only the recipe mapping crosses to peers (hosts silently fork the forward cache; denylist means future knobs fork by default); reconcile keys on (name, variant, component_id) while agree_selections keys on bare name and reconcile is unscoped by operation group; and HostRendezvous.prepare(..., b12x_environment=None) has no caller.

Areas I found sound and say so plainly: atomic .bin persistence and the _share_artifacts temp handling, _remap_peer_config's dataclass replacement (no other rank-zero absolute path leaks), reconcile's rank-lockstep changed/configs derivation, rejection of B12X_COMPILE_CACHE_DIR over the new channel, Windows/POSIX parity of os.replace + unlink(missing_ok=True), no metric/rate/admission-span change to re-price, and no wire-contract break (PROTOCOL = 5 unchanged and the new frame only follows a version-matched admission). The one charter gap is documentation: AGENTS.md:234 requires docs/multi-host.md for multi-host preparation changes and neither the peer env channel nor the reconcile contract is documented anywhere in docs/.

#5 [high] Report skeleton, severity ranking, and citation caveats

BOTTOM LINE for the final report: the diff's atomics, cache remapping, and lockstep reasoning are sound, but the PR's central ordering claim is factually wrong (F1), the new corrupt-cache handler re-introduces the swallow-the-error pattern charter #397 forbids (F2), and the widened conflict detection multiplies the cost of the retry loop it is meant to end (F3). Recommend: F1 + F2 must be fixed (or F1 documented as a limitation and the description corrected); F3 needs the description corrected and ideally autotune=False on the reconcile pass; F4–F6 and the doc gap are follow-ups.

SEVERITY ORDER for the write-up:

  1. F1 Major — peer env applied after b12x.preparation import (entry 2).
  2. F2 Major — _CORRUPT_ARTIFACT_ERRORS swallow + unguarded unlink (entry 2).
  3. F3 Major — global changed / local configs re-prepare amplification (entry 2).
  4. F4 Minor — forward-cache key hashes ambient env, peers only get the recipe mapping; denylist forks by default (entry 3).
  5. F5 Minor — reconcile key (name, variant, component_id) vs agree key name; unscoped by operation group; docstring/error text says "rank zero's" when it is the operation's first rank (entry 3).
  6. F6 Minor — HostRendezvous.prepare(..., b12x_environment=None) has no caller (entry 3).
  7. Test gaps + docs gap (entry 3).

CITATION CAVEATS (evidence rules — do not state unverified numbers):

ONE ITEM I DID NOT ANALYSE and should not claim either way: whether the ambient-env fork in F4 interacts badly with #695's --tuning-gpus replica gate beyond noting that tuning.py:426-427 already forbids local replicas across hosts.

#3 [medium] Findings F4-F6 (medium/low) plus clean-area statements

F4 (Minor) — the forward-cache key hashes the ambient B12X_* env, but only the recipe's declared mapping crosses to peers, so hosts with different ambient env get different forward-cache identities. aot.py:897-899 key = hashlib.sha256(pickle.dumps((namespace, options, _b12x_forward_env(), torch_key(), ...))) with _b12x_forward_env() (aot.py:79-87) reading os.environ. Peer side only receives the validated recipe mapping: host_ranks.py:201-209 rejects any non-B12X_ name, B12X_COMPILE_CACHE_DIR, and non-string values, and serve.py:197 / :420 pass exactly model.recipe.b12x_environment. So a user-exported B12X_* on rank 0 changes rank 0's ForwardCache.root and not the peers'. Impact: the stated goal "distinct hosts with different cache paths keep identical forward-cache root names" holds for paths but not for env; hosts silently fork the forward cache (full recompile + whole-catalog _share_artifacts copy at aot.py:1266/1357). Inverted hardening risk: _NON_EXECUTION_B12X_ENV (aot.py:47-62) is a denylist, so any future B12X_* diagnostic knob not added there forks the cache by default (fail-closed on recompile). Fix: hash the recipe's declared b12x_environment mapping (which is already sent to peers) instead of ambient os.environ, or make the list an allowlist.

F5 (Minor) — reconcile matches on (name, variant, component_id) while agree_selections matches on bare name, and reconcile is not scoped to operation groups. collectives.py:218 entries.append((plan, key, (name, variant, plan.component_id), ...)) vs collectives.py:377 local = {item["name"]: (item["component"], json.dumps(...)) ...}. agree_selections deliberately scopes by self.operation_ranks (collectives.py:381-392); reconcile_selections gathers the whole group (collectives.py:411-425) with no operation scoping. For a request owned by a subgroup that excludes rank 0, chosen_name/chosen_decl come from the lowest participating rank, not rank zero, contradicting the docstring "adopt rank zero's configuration" (collectives.py:403-405) and the error text at :395-396 ("differ from rank zero's"). Behaviourally consistent with agree's root = gathered[positions[0]], so not a bug, but the name-first key is stricter than agree's key: a pair that agrees on name but differs on component_id is never reconciled and still fails agree forever. Fix: derive both keys from one function, and say "the operation's first rank".

F6 (Minor) — HostRendezvous.prepare(..., b12x_environment=None) (host_ranks.py:313-314, resolved :325-326) has no caller: only caller is rank_group.py:289 ranks.prepare(snapshot, config, prepare, checkpoint=checkpoint, progress=progress, core_storage=core_storage). The description's "wired from model.recipe.b12x_environment in _export_hosts and debug_serve" is true only via the constructor kwarg (serve.py:197, :420). So the parameter is dead and the two paths can silently diverge.

Test gaps (Minor): no in-repo test that the peer env lands before environment.apply/b12x import (the ordering that F1 is about); no test for _remap_peer_config's non-dataclass setattr branch (host_ranks.py:218); test_serve_peer_applies_b12x_environment_and_remaps_kernel_cache (tests/preparation/test_host_ranks.py:346-438) stubs dist.init_process_group, so the peer's ForwardCache root is never observed.

Sound areas (state plainly, no finding):