PR #668 review — Correctness, Contracts & System-Level Consequences
PR: https://github.com/NVIDIA/hyperflare-inference/pull/668 · head d4d7b2d · 8 files, +423/−44 · Fixes #651 · paired with local-inference-lab/flashinfer#199
Reviewed in context: ignition/preparation/collectives.py, ignition/preparation/host_ranks.py, ignition/preparation/aot.py, ignition/cli/serve.py, plus direct callers/contracts ignition/preparation/tuning.py, rank_group.py, inductor_tuning.py, composition_tuning.py, environment.py, declaration.py, core_snapshot.py, runtime_core.py, the four touched tests, AGENTS.md, docs/multi-host.md.
Key findings
- Blocker — new control-channel message with no
PROTOCOLbump.host_ranks.py:41stillPROTOCOL = 5, butprepare()now sends("b12x-environment", b12x_env)as the first message (host_ranks.py:345-347). A protocol-5 peer passes_admitand then dies athost_ranks.py:657-658withRuntimeError("rank zero sent ... before its checkpoint")instead of a clean version rejection — and only for recipes that declare b12x settings (GLM-5.3, Kimi), so it presents as a model-specific failure. - Major — corrupt-cache recovery deletes artifacts on transient I/O, silently.
_CORRUPT_ARTIFACT_ERRORS(aot.py:64-76) includesOSErrorandRuntimeError, and the handler in_load(aot.py:1376-1380) wrapspath.open(...), so EIO/EROFS/ENOSPC or a driverRuntimeErrorunlinks a valid multi-GB.binand recompiles with no log line. Directly against charter/#397 andAGENTS.md. - Major — the reconcile pass double-counts the tuning report.
tuning.py:511-515appends the second preparation to the sameresultslist thattuning.py:558-564sums intoelapsed_seconds,cache_hits,benchmarked_candidates, etc. Because #668 makeschangedtrue precisely in #651's divergence case, reported tuning numbers inflate exactly on the runs operators use to judge the fix. - Major — when any plan changed, every job is re-prepared, unsharded onto rank 0 (
tuning.py:506-518), and rank 0 passesselected_configs={}where pass one passed nothing (collectives.py:499distinguishesNonefrom{}) — an untested path against the real b12x library, on a workload that already costs ~2h15m/attempt (#631). - Major/Minor — the all-gather payload lost its declaration dedup (
collectives.py:409-410), growing an already memory-criticalall_gather_objecton #651-scale catalogs (1020–1319 records/rank). - Minor —
ForwardCacheidentity uses an ambient-env denylist and is reused as a collective identity._b12x_forward_env()(aot.py:79-87) is hashed into the cache root (aot.py:897-899), whose name becomesInductorSelections(source_identity=self.root.name)(aot.py:1450-1451) and thus a cross-rankPreparedComposition.identity()— so one future host-localB12X_*knob outside the 14-name denylist re-keys and recompiles every host and can make ranks disagree on a key nothing validates. - Minor — validation-timing and platform issues:
B12X_COMPILE_CACHE_DIRis accepted byRecipe(declaration.py:251-253) but raises a bareValueErrorfromHostRendezvous.__init__(host_ranks.py:205-208,:233) before the listener exists, so peers retryknockfor 600 s; and_share_artifactsunlinks the temp file while it is still open (aot.py:870-877), which raisesPermissionErroron Windows and masks the original error. - Tests/claims —
Fixes #651remains unproven. The new 2-rank test never exercises reconcile→re-prepare→agree_selections(test_tuning_shards.py:287-303hand-rewrites_prepared), no test covers the peerexport_options(..., kernel_cache=...)branch (host_ranks.py:718-719), there is nochanged is Falseregression test, and the 2×GB10 GLM-5.3export+join— the exact configuration of #651 — is explicitly not run.
1. Correctness, Safety & Platform Parity
F1 — Blocker: new control-channel message without a protocol bump
host_ranks.py:41:
PROTOCOL = 5
New first message from rank zero, host_ranks.py:344-347:
with phase(progress, "Admit checkpoint range readers"):
if b12x_env:
for control in controls:
send_object(control, ("b12x-environment", b12x_env))
Peer side, host_ranks.py:645-658:
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)
...
if not (isinstance(command, tuple) and command[0] == "checkpoint-source"):
raise RuntimeError(f"rank zero sent {command!r} before its checkpoint")
A peer running a stale ignition join (protocol 5, accepted by _admit at host_ranks.py:285-286) reaches the final if with ("b12x-environment", {...}) and raises the generic RuntimeError. It fires only when the recipe declares b12x settings, so an operator sees a model-specific-looking failure on GLM-5.3/Kimi and success elsewhere; the failing message does not mention versions at all. docs/multi-host.md:377 ("All hosts need matching Flare executables and preparation sources") shows stale peers are an expected operator condition, not a hypothetical.
Fix: bump PROTOCOL to 6 so _admit rejects with the intended mismatch error, or drop the out-of-band message entirely and carry the env only inside assignment (already read version-tolerantly via .get at host_ranks.py:666).
F2 — Major: opportunistic restore unlinks valid artifacts on transient I/O, with no log
aot.py:64-76:
_CORRUPT_ARTIFACT_ERRORS = (
EOFError,
pickle.UnpicklingError,
struct.error,
zlib.error,
zipfile.BadZipFile,
OSError,
ValueError,
TypeError,
KeyError,
AttributeError,
RuntimeError,
)
aot.py:1371-1380:
def _load(self, forward, path, *, required=False, before_run=None):
try:
with bind_device(self.device, freeze_tuning=self.options.get(
'triton.autotune_at_compile_time', False)), path.open('rb') as file:
artifact = torch.compiler.load_compiled_function(file)
except _CORRUPT_ARTIFACT_ERRORS as error:
if required or isinstance(error, (MemoryError, torch.OutOfMemoryError)):
raise
Path(path).unlink(missing_ok=True)
return None
The try wraps path.open(...), so a transient read error surfaces as OSError and is classified as corruption: a valid multi-GB compiled forward is deleted and recompiled. Two concrete hazards: (a) on a read-only or full cache the unlink(missing_ok=True) itself raises OSError from inside the handler, converting a recoverable cache miss into a hard failure; (b) genuine driver RuntimeErrors (the tuple's widest member) are likewise swallowed and the artifact destroyed. There is no logging/progress call on this path at all, so an operator never learns an artifact was dropped. Charter: "Bug fixes need to address the root cause; don't just swallow, skip, or retry an unexplained error (#397)"; AGENTS.md forbids suppressing errors. The sole required=False caller is _restore (aot.py:1410-1425, :1420).
Fix: narrow the tuple to deserialization errors (EOFError, pickle.UnpicklingError, struct.error, zlib.error, zipfile.BadZipFile) plus an explicit truncated-read check; keep path.open outside the try (or catch FileNotFoundError separately); emit a warning carrying path and exception before unlinking; wrap the unlink in its own try/except OSError so a read-only cache degrades to a plain miss.
F3 — Minor: Windows-only failure in the new temp-file cleanup, in a path this PR rewrote
aot.py:870-877:
with tempfile.NamedTemporaryFile(dir=target.parent, suffix=".tmp", delete=False) as file:
temporary = Path(file.name)
try:
file.write(payload[0])
file.close()
os.replace(temporary, target)
finally:
temporary.unlink(missing_ok=True)
On Windows, a write failure reaches finally with the handle still open, so unlink raises PermissionError, masking the original error and aborting the publication loop rather than reporting the real cause; the explicit file.close() is also redundant once the context manager exits. The PR's own _save_compiled_function (aot.py:90-100) gets this right by unlinking after the with. Fix: move temporary.unlink(missing_ok=True) outside the with block, matching _save_compiled_function.
F4 — Minor: recipe-legal B12X_COMPILE_CACHE_DIR becomes a fatal, mistimed rendezvous error
declaration.py:251-253 accepts any B12X_ string binding; host_ranks.py:205-208 rejects that one name specifically:
if any(not isinstance(name, str) or not name.startswith("B12X_")
or name == "B12X_COMPILE_CACHE_DIR" or not isinstance(value, str)
for name, value in resolved.items()):
raise ValueError("b12x environment settings must map non-cache B12X_ names to string values")
This runs in HostRendezvous.__init__ (host_ranks.py:233), i.e. before socket.create_server at :235, on the ignition export --ranks N side. Peers launched with ignition join are already knocking and will retry for 600 s before failing with an unrelated "did not join" error. environment.apply itself overrides that variable from the recipe binding (environment.py:47, :51), so setting it in a recipe is not unreasonable. Fix: validate at recipe/declaration time with UsageError, and construct the rendezvous only after the plan is fully validated.
2. Unintended System-Level Consequences
F5 — Major: the second preparation pass is unbounded and unmetered
tuning.py:504-518:
if (self._coordinator is not None and len(self._coordinator.ranks) > 1
and self._replica_coordinator is None):
configs, changed = self._coordinator.reconcile_selections(requests)
if changed:
if self._sharded:
self.configure_tuning_shard(0, (0,))
try:
for job in self._jobs(requests):
plans = {plan for request in job for plan in iter_plans(request)}
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}))
Three consequences, all on the failure path this PR is meant to make cheap:
- Every job is re-prepared, including jobs whose plans are untouched by
configs(the filtered mapping for such a job is empty, yet the job still runs throughprepare). - Sharding is collapsed to rank 0 via
configure_tuning_shard(0, (0,)), so the parallel work that #647's sharded tuning bought is serialized for the whole second pass. - Rank 0 now supplies
selected_configs={}rather than nothing, andcollectives.py:499explicitly distinguishes the two:
options = {} if selected_configs is None else {"selected_configs": selected_configs}
so rank 0 enters a b12x session.begin(..., selected_configs={}) state that pass one never used — a code path with no coverage against the pinned library. #651's reporters measured ~2h15m per failed attempt (#631); nothing in the PR measures the added pass.
Fix: iterate only over jobs whose plans ∩ configs is non-empty; pass None when the filtered mapping is empty (... or None); record the second pass separately (see F6) so the cost is visible.
F6 — Major (metric-scope change): tuning_report now includes the reconcile pass
tuning.py:551-564:
self.tuning_report = {
...
"cache_hits": sum(result.cache_hits for result in results),
"benchmarked_candidates": sum(result.benchmarked_candidates for result in results),
"restored_candidates": sum(result.restored_candidates for result in results),
"rejected_candidates": sum(result.rejected_candidates for result in results),
"elapsed_seconds": sum(result.elapsed_seconds for result in results),
"parent_cute_compilations": sum(result.parent_cute_compilations for result in results),
"parent_triton_compilations": sum(result.parent_triton_compilations for result in results),
Because the reconcile results are appended to results at tuning.py:513, every one of these aggregates changes scope from "one tuning pass over the catalog" to "one pass plus a full second pass" — on exactly the runs where changed is true, i.e. the multi-host divergence case. elapsed_seconds roughly doubles for affected runs, and cache_hits/benchmarked_candidates are counted twice for the same catalog. Any consumer comparing this report across ranks or over time (this field is what operators attach to bug reports for #631/#651) is now misleading.
Fix: keep the reconcile pass's results in a separate list and report reconcile_elapsed_seconds / reconciled counts as their own keys, leaving the top-level aggregates comparable with main.
F7 — Major/Minor: the all-gather catalog lost its dedup and grew per-variant
collectives.py:408-412:
entries = _selected_plan_catalog(requests)
local = [(decl_key, name_key, payload, config)
for _, decl_key, name_key, payload, config in entries]
gathered = [None] * len(self.ranks)
dist.all_gather_object(gathered, local, group=self.group)
Before, the per-rank mapping was keyed by declaration and payload-deduped (local.setdefault(key, {}).setdefault(payload, config), replaced by this hunk). Now each composite plan contributes one element per variant (collectives.py:212-219), each carrying the nested portable_declaration(plan) tuple plus a (name, variant, component_id) tuple plus the pickled config payload, and all_gather_object materializes all ranks' copies in every rank. #651 records 1020 vs 1319 selection-cache records per rank; this is a pickle-and-RPC amplification on a preparation step already contended for memory (the PR itself is about avoiding OOM-driven divergence).
Fix: gather a deduped payload list plus a compact per-rank name_key → payload index map; that preserves the new name-matching semantics at pre-#668 wire size.
F8 — Minor: forward-cache identity now depends on ambient environment and is shared with collective tuning identity
aot.py:79-87 and aot.py:897-899:
def _b12x_forward_env():
"""Return sorted execution-relevant B12X_* environment bindings for forward cache identity."""
return tuple(sorted(
(name, value)
for name, value in os.environ.items()
if name.startswith("B12X_")
and name not in _NON_EXECUTION_B12X_ENV
and not name.startswith("B12X_LOG_")
))
key = hashlib.sha256(pickle.dumps((namespace, options, _b12x_forward_env(), torch_key(),
runtime_patches.identity(), properties.name, properties.major, properties.minor,
properties.multi_processor_count)))
Two system-level consequences beyond the intended one:
- Cache invalidation blast radius:
self.root.nameis a content hash, and it is reused asInductorSelections(..., source_identity=self.root.name)ataot.py:1450-1451, feedingPreparedComposition.identity()— a cross-rank collective key. AnyB12X_*variable an operator exports for debugging that is not in the 14-name_NON_EXECUTION_B12X_ENVfrozenset (aot.py:47-62) now re-keys the entire compiled-forward cache (full recompile) and, if set on one host only, makes ranks disagree on a key that neitheragree_selectionsnor any other check validates. The denylist is a maintenance contract with a library the PR does not own. - This is compounded by the cache-root name change itself: every host with any execution-relevant
B12X_*set gets a new root name, so pre-#668 compiled forwards are silently orphaned with no migration note in the PR.
Fix: hash the recipe's declared b12x_environment (the authoritative, deliberately curated set that this same PR now transmits to peers) instead of ambient os.environ, and document the one-time re-key.
F9 — Minor: redundant env channel; the "before import-time reads" rationale does not hold on the join path
serve.py:547-555:
environment.apply(configuration, (gpu,))
identity = source_identity()
control, executor = knock(args.rendezvous, args.rank, args.ranks, identity=identity,
topology=local_topology(gpu), report=progress)
serve_peer(control, executor, args.rank, args.ranks, hub_cache=hub_cache, progress=progress,
export_staging=configuration.directory("export_staging"), identity=identity,
core_cache=configuration.directory("core_cache"),
kernel_cache=configuration.directory("kernel_cache"),
environment.apply (which also applies runtime patches) runs before knock, and therefore long before serve_peer reads the early command at host_ranks.py:646-648; anything that reads b12x settings at import time in the peer process has already done so. Meanwhile rank zero applies the same settings through its own mechanism (serve.py:211, environment.apply(configuration, local, plan.recipe.b12x_environment)), the environment is sent twice (host_ranks.py:345-347 and inside assignment at :376-377) and validated/applied twice (:647, :666-668) — and test_host_ranks.py:405-411 pins that redundancy. Additionally HostRendezvous.prepare(..., b12x_environment=None) (host_ranks.py:313-314) has no caller passing it; rank_group.py calls prepare without it. Fix: keep the single assignment-borne channel (or make the early channel the only one), drop the unused override parameter, and state plainly in docs/multi-host.md that the recipe env is now transmitted.
3. Architecture, Contracts & Charter Compliance
- Wire contract (F1) is the only genuine contract break: the rank-rendezvous protocol gained a message kind while
PROTOCOLstayed at 5. No other wire/proto/exported-artifact format changes;.binarchives keep their format, and the forward-cache root rename (F8) is a key change, not a format change, so existing cores still load. - Behavioural change without opt-in (contract): peer
config.kernel_cacheno longer inherits rank zero's absolute path (host_ranks.py:212-219,:669). That is the intended fix, but it is unconditional and undocumented; any deployment that deliberately shared onekernel_cachepath across hosts (e.g. an NFS mount) changes behaviour with no flag and no note indocs/multi-host.md. Given the charter's "no magic defaults", this at minimum deserves a documented statement of the new per-host contract. - Charter coherence: the fix is a convergence mechanism, not a root-cause fix. #651's second diagnosed cause — rank-local state leaking into declaration identity via
_mixed_tuning_batches(tuning.py:229-255, 53-vs-65 shard races, 12 extra split components on rank 1) — is untouched; #668 makes peers adopt rank 0's config after the fact. That is defensible as a liveness fix, but the PR title claims reconciliation "of divergent multi-host selections" while the paired flashinfer#199 carries the identity half, and the PR is described as mergeable independently. Charter language ("don't just swallow, skip, or retry an unexplained error") applies to F2 directly, and "Supported matrix & compatibility: … verify cross-node" is the bar the unrun 2-host path sits against. - Layer placement is right: all changes are in ignition preparation/CLI, with no per-model branches; b12x knobs come from
recipe.b12x_environment. - Overlap risk (not resolvable here): #667 (same author) edits the same peer export region of
host_ranks.py; #597 rewrites_share_artifacts/__init__keying/_loadinaot.py. No commits on main since the branch point (a3c80e1) touch these files, so there is no conflict today, but landing order matters.
4. Tests & Claim Accuracy
- The headline claim is unproven. The PR body states the live 2×GB10 TP2 GLM-5.3
export+joinwas not run — that is exactly the configuration in #651, which produced "1321 kernel selections differ from rank zero's".Fixes #651therefore rests on CPU unit tests. - The new reconcile test does not test the fix's mechanism.
test_tuning_shards.py:287-303asserts the returned configs and then hand-rewrites the prepared state; the real path —coordinator.prepare(..., selected_configs=...)(collectives.py:484-519) plus thetuning.py:506-518loop plusagree_selections(collectives.py:375-396, called attuning.py:529-530) — is never executed end to end. A test that ran the loop and then assertedagree_selectionsreturns without raising would actually prove the #651 symptom is gone. - No coverage for two new decision branches: the peer export branch
export_options(core_cache, ..., kernel_cache=kernel_cache)(host_ranks.py:718-719) is the only place peers pick their own cubin directory, and no test asserts it; and there is nochanged is Falsetest proving the rewrite does not trigger a spurious second pass on already-agreeing ranks (the pre-existing common case). - Description accuracy: the "before/after" claims for reconciliation, peer env propagation, atomic saves and corrupt-load recovery all match the diff (verified against
collectives.py:398-449,host_ranks.py:201-219/344-377/645-719,aot.py:79-100/897-899/1371-1380/1454/1463). The two claims that do not hold up: "propagates … so import-time reads see it" (F9 — the join path applies its own env before knocking anyway), and the implied neutrality of the tuning report (F6 — the metrics' scope changed). "Independent of flashinfer#199" is plausible, but CI installs flashinfermain(pyproject.toml:47), so the declaration-identity half of #651 is not exercised by this PR's test run. - Author-reported results (192 preparation CPU tests, 136 CLI tests,
CUDA_VISIBLE_DEVICES="") are consistent with the touched files; GPU, Rust and live multi-host runs are declared not run.
Sound in this diff (stated plainly)
changedandconfigsare derived from the same all-gathered catalogs through the sametarget_for(collectives.py:429-449), so ranks cannot split on whether to enter the reconcile pass — this genuinely closes the liveness hole that made the #647-era declaration-only reconcile loop._save_compiled_function(aot.py:90-100) is a correct same-directory temp +os.replacewith cleanup and is used at all three former direct-save sites (aot.py:1454,:1463, and the sharing path)._remap_peer_config(host_ranks.py:212-219) handles both frozen dataclasses and mutable configs, and correctly no-ops whenkernel_cacheis unset.test_forward_artifact_sharing.py:153-154now round-trips real payload bytes instead of a no-op, which is a genuine strengthening of the sharing tests.- The
MemoryError/torch.OutOfMemoryErrorcarve-out ataot.py:1377is necessary (they are not in the tuple) and correct.
Open questions / not found
- Does #668 actually converge on 2× GB10 with GLM-5.3? No live run exists; neither hiroshi-ya (#651) nor pfn (#631) has been asked to verify, and neither has commented on the PR.
- Does the reconcile logic converge against unmodified flashinfer
main, or does it need flashinfer#199's contract-version/fingerprinting changes? The PR asserts independence but does not show it. - Why does reconciliation discard rank 1's locally tuned (possibly faster) config rather than compare and pick by measured latency? No measurement of the second pass's cost on a ~2h15m workload.
- Which error classes did the author intend
_CORRUPT_ARTIFACT_ERRORSto cover — disk corruption only, or also transient I/O?OSError/RuntimeErrorinclusion suggests the latter, which the handler cannot safely distinguish. - Whether the forward-cache root re-key (F8) is acceptable to operators as a one-time full recompile, and whether #597 (GPU-name keying) or #667 (peer export) are intended to land before or after #668.