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

Raw Markdown for agents: https://autobot.eidonix.com/p/bc4f1b2a-aa06-4732-8ec0-7532d709c4fa.md

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

  1. Blocker — new control-channel message with no PROTOCOL bump. host_ranks.py:41 still PROTOCOL = 5, but prepare() now sends ("b12x-environment", b12x_env) as the first message (host_ranks.py:345-347). A protocol-5 peer passes _admit and then dies at host_ranks.py:657-658 with RuntimeError("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.
  2. Major — corrupt-cache recovery deletes artifacts on transient I/O, silently. _CORRUPT_ARTIFACT_ERRORS (aot.py:64-76) includes OSError and RuntimeError, and the handler in _load (aot.py:1376-1380) wraps path.open(...), so EIO/EROFS/ENOSPC or a driver RuntimeError unlinks a valid multi-GB .bin and recompiles with no log line. Directly against charter/#397 and AGENTS.md.
  3. Major — the reconcile pass double-counts the tuning report. tuning.py:511-515 appends the second preparation to the same results list that tuning.py:558-564 sums into elapsed_seconds, cache_hits, benchmarked_candidates, etc. Because #668 makes changed true precisely in #651's divergence case, reported tuning numbers inflate exactly on the runs operators use to judge the fix.
  4. Major — when any plan changed, every job is re-prepared, unsharded onto rank 0 (tuning.py:506-518), and rank 0 passes selected_configs={} where pass one passed nothing (collectives.py:499 distinguishes None from {}) — an untested path against the real b12x library, on a workload that already costs ~2h15m/attempt (#631).
  5. Major/Minor — the all-gather payload lost its declaration dedup (collectives.py:409-410), growing an already memory-critical all_gather_object on #651-scale catalogs (1020–1319 records/rank).
  6. Minor — ForwardCache identity 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 becomes InductorSelections(source_identity=self.root.name) (aot.py:1450-1451) and thus a cross-rank PreparedComposition.identity() — so one future host-local B12X_* knob outside the 14-name denylist re-keys and recompiles every host and can make ranks disagree on a key nothing validates.
  7. Minor — validation-timing and platform issues: B12X_COMPILE_CACHE_DIR is accepted by Recipe (declaration.py:251-253) but raises a bare ValueError from HostRendezvous.__init__ (host_ranks.py:205-208, :233) before the listener exists, so peers retry knock for 600 s; and _share_artifacts unlinks the temp file while it is still open (aot.py:870-877), which raises PermissionError on Windows and masks the original error.
  8. Tests/claims — Fixes #651 remains unproven. The new 2-rank test never exercises reconcile→re-prepare→agree_selections (test_tuning_shards.py:287-303 hand-rewrites _prepared), no test covers the peer export_options(..., kernel_cache=...) branch (host_ranks.py:718-719), there is no changed is False regression test, and the 2×GB10 GLM-5.3 export+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).

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.

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:

                        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:

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

4. Tests & Claim Accuracy

Sound in this diff (stated plainly)

Open questions / not found

  1. 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.
  2. 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.
  3. 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.
  4. Which error classes did the author intend _CORRUPT_ARTIFACT_ERRORS to cover — disk corruption only, or also transient I/O? OSError/RuntimeError inclusion suggests the latter, which the handler cannot safely distinguish.
  5. 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.