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

Raw Markdown for agents: https://autobot.eidonix.com/p/de28ba1d-fb03-407c-bc3a-aed53bb8b20b.md

#2 [high] Finding: cli-design + AGENTS still say env vars are never read

Major. The PR documents the exception in AGENTS.md:466-473 (edited), docs/cli-design.md:1480 (edited row), docs/model-preparation.md:123-132 (edited), but leaves these two umbrella clauses contradicting the code:

docs/cli-design.md:46-53 (unmodified):

- **No environment variables.** Flare reads none, with one exception:
  `CUDA_VISIBLE_DEVICES` restricts which GPUs the caller exposed, which changes
  the GPU each index names, so Flare inspects it to interpret `--gpus`.
  Variables that underlying libraries read are set by Flare from its own
  configuration, and b12x's from the recipe's declared settings, before those
  libraries are imported.
- **Two levels of precedence.** Flags override the configuration file, which
  overrides the recipe. Nothing else exists.

AGENTS.md:461 (unmodified): "CUDA_VISIBLE_DEVICES is the only variable Flare interprets" — while the same section at :468-471 now says apply "preserves a non-empty inherited CUDA_HOME".

environment.py:58-67 reads CUDA_HOME, so after this PR cli-design.md:46 ("with one exception") and :52-53 ("Nothing else exists") are false, and the design doc self-contradicts its own decision table at :1480. The toolkit also gains a third precedence source.

Impact: docs/cli-design.md is the contract design-review principle 10's exception points at ("the documented CUDA device selection and dependency setup policies", docs/design-review.md:89-92). Documenting the policy in one row while the normative clause says the opposite gives a reviewer grounds to say the exception is not actually documented. Concrete fix: amend :46-51 to name CUDA_HOME (and TRITON_PTXAS_PATH/CPATH as library variables set from the selected toolkit) as part of the dependency-setup exception, and amend :52-53 so the toolkit decision's third source is acknowledged; align AGENTS.md:461 "only variable Flare interprets".

#3 [high] Finding: TRITON_PTXAS_PATH precedence reversal + undocumented blank-value fill

Major. ignition/cli/environment.py:78-81:

            ptxas = cuda / "bin/ptxas"
            if ptxas.is_file() and (
                configured_cuda is not None or not os.environ.get("TRITON_PTXAS_PATH", "").strip()
            ):
                os.environ["TRITON_PTXAS_PATH"] = str(ptxas)

Base (diff, -77 line) was if ptxas.is_file() and "TRITON_PTXAS_PATH" not in os.environ: — ANY ambient value (blank or not) won.

Two consequences, neither asked for by #636 (which is only about CUDA_HOME): (a) A caller's non-blank TRITON_PTXAS_PATH now loses to [paths] cuda, silently, with no message. This sits against design-review principle 10 "explicit user values win over defaults" (docs/design-review.md:89-92). (b) NEW, and NOT disclosed anywhere: a blank/whitespace TRITON_PTXAS_PATH no longer blocks population — it is now filled from /bin/ptxas. The description says "ambient TRITON_PTXAS_PATH" loses only in the [paths] cuda case and does not mention the blank case at all (docs/model-preparation.md:128-130 says only "overriding the environment when [paths] cuda is configured, or populating it when unset" — "unset" is imprecise: blank also counts).

Test coverage confirms the author intends (a): tests/cli/test_environment.py:68,98 and asserts at :74,105. But there is NO test for a blank TRITON_PTXAS_PATH with [paths] cuda unset (the new (b) branch): test_inherited_cuda_home_is_preserved_over_default_toolkit (:79-89) leaves TRITON_PTXAS_PATH absent (fixture :52-57), so the not ... .strip() arm is only exercised via the empty-string path implicitly.

Impact: a user pinning a specific ptxas for Triton (e.g. mixing toolkits deliberately) silently gets the [paths] cuda ptxas instead, changing generated code with no diagnostic. Concrete fix: restore "caller value wins" for TRITON_PTXAS_PATH (keep not in os.environ OR at minimum warn), and decide/document the blank case explicitly; if the override is intended, it needs a separate justification beyond #636.

#4 [high] Finding: inherited CUDA_HOME is exported without any validation

Major. The code never validates that the preserved path is a toolkit. ignition/cli/environment.py:61-66:

        inherited_cuda = os.environ.get("CUDA_HOME", "").strip()
        if inherited_cuda:
            cuda = Path(inherited_cuda)
        elif _DEFAULT_LINUX_CUDA.is_dir():
            cuda = _DEFAULT_LINUX_CUDA

and :69 os.environ["CUDA_HOME"] = str(cuda).

Path(inherited_cuda) gets no .is_dir() check and no nvcc/ptxas check, yet it is then exported as CUDA_HOME for the whole process tree (compile workers/subprocesses inherit it; serve.py:9-10 docstring "Rank and compiler processes inherit the environment"). A stale CUDA_HOME (/opt/cuda-12.4 after an upgrade), a bare CUDA_HOME=1, or a relative path is preserved verbatim and re-exported as the toolkit root.

Two concrete consequences: (a) Failure-propagation blast radius: torch's own toolkit decision (ignition/preparation/kv_codec.py:23, from torch.utils.cpp_extension import CUDA_HOME) now inherits a broken root. kv_codec._find_nvcc (:26-38) appends the wrong nvcc first but still falls back to shutil.which + /usr/local/cuda, so that one degrades gracefully. However ignition/preparation/tuning.py:58 imports _set_triton_libdevice_path and tests/preparation/test_toolchain.py:31-36 shows Triton extern_libs ("libdevice") are derived from CUDA_HOME; a bogus CUDA_HOME there yields no libdevice rather than a fallback — preparation fails later with a confusing message instead of at startup. (b) The fallback /usr/local/cuda is gated on is_dir() (:64) but the inherited path is not — asymmetric validation. Note the base code also exported whatever [paths] cuda said without validation (:59, :69), so this is extending an unvalidated path to a new, less-trusted source (the ambient environment, which is exactly what #636 wants honored — but #636's reporters set it to a real second toolkit).

Concrete fix: validate the inherited path (cuda.is_dir() and, if strict, (cuda/'bin/ptxas').is_file()), and when it is not a toolkit either fail with a clear message naming CUDA_HOME or fall through to the documented next source — but say which. Tests actively assert the invalid-value behavior: tests/cli/test_environment.py:110-120 (:111-114 sets CUDA_HOME to a directory that is never created, :118 asserts it is preserved).

#6 [high] Finding: selected toolkit never recorded in plan/report; no end-to-end evidence

Major (charter/evidence). AGENTS.md:456-460 requires:

  - A setting has one of three homes: the recipe declaration, the configuration
    file, or a command-line flag, as [the CLI design](docs/cli-design.md)
    specifies. A setting that only experiments need is an advanced flag carried
    through the plan into the recipe's `PreparationConfig`, so the plan, its
    printed report, and its recorded measurements describe what was prepared.

This PR makes the selected CUDA toolkit depend on the ambient environment, but the plan printed by export/debug_serve never records it. ignition/planning.py:383-420 to_dict() emits alias/repository/revision/architecture/gpus/parameter_dict/tuning_gpus/benchmark_selection/context/checkpoint_context/weights_bytes/mapped_host_bytes/graph_bytes/mixed_shapes/live_bytes/prefix_cache_/snapshot/pages/page_bytes/tokens/free|headroom|reserve|supply_bytes — no cuda/toolkit field — and is printed at serve.py:213 and :440.

So after this PR two ignition export runs of the same model that produce different native-build toolchains (different ptxas/libdevice) print identical plans, and cores are not attributable to the toolkit that built them. Concrete fix: add the resolved toolkit path (and whether it came from [paths] cuda, CUDA_HOME, or /usr/local/cuda) to the plan report — it is cheap, printed once at startup, and it is the only way a user can see which toolkit silently won. This is also the reviewer's answer to "is env-derived configuration acceptable here": it becomes visible rather than silent.

Related non-blocking evidence gap (author-disclosed honestly): no end-to-end/multi-toolkit/GPU run reproduces #636's actual scenario (host with /usr/local/cuda AND a second toolkit). All 10 tests monkeypatch _DEFAULT_LINUX_CUDA (tests/cli/test_environment.py:66,82,96,113,127,141), so the real-path branch (_DEFAULT_LINUX_CUDA.is_dir()) is never exercised against /usr/local/cuda. #231's review asks for exactly this kind of downstream assertion (tests/preparation/test_toolchain.py:31-36 pattern: assert Triton extern_libs/libdevice really comes from the preserved toolkit) — this PR does not add it.

#7 [high] CORRECTED: TRITON_PTXAS_PATH precedence reversal + untested blank-value fill

AUTHORITATIVE VERSION — replaces entry 3, whose claim that the blank-value fill is "not disclosed" was WRONG. The PR description's "What changed" does say: "sets TRITON_PTXAS_PATH from <toolkit>/bin/ptxas when that file exists and either [paths] cuda is configured or TRITON_PTXAS_PATH is unset/blank".

Major. ignition/cli/environment.py:78-81:

            ptxas = cuda / "bin/ptxas"
            if ptxas.is_file() and (
                configured_cuda is not None or not os.environ.get("TRITON_PTXAS_PATH", "").strip()
            ):
                os.environ["TRITON_PTXAS_PATH"] = str(ptxas)

Base (-77 in diff) was if ptxas.is_file() and "TRITON_PTXAS_PATH" not in os.environ: — ANY ambient value, blank or not, won and was never filled.

Consequence (a): a caller's non-blank TRITON_PTXAS_PATH now loses to [paths] cuda, silently, no message. Sits against design-review principle 10 "explicit user values win over defaults" (docs/design-review.md:89-92). Tests confirm intent: tests/cli/test_environment.py:68/:74 (ambient "/ambient/ptxas" -> configured ptxas) and :98/:105 (preserved when only CUDA_HOME inherited).

Consequence (b): blank/whitespace TRITON_PTXAS_PATH is now overwritten rather than left alone. Disclosed in the description, but docs/model-preparation.md:128-130 renders it imprecisely: "sets TRITON_PTXAS_PATH (overriding the environment when [paths] cuda is configured, or populating it when unset)" — "unset" omits blank/whitespace, which is a real behavior.

Gap: NO test covers a blank TRITON_PTXAS_PATH. Every test either sets a non-blank value (:68, :98) or leaves it absent (fixture :52-57 pops it). So the not ... .strip() arm for the blank case is untested, and the trim-and-overwrite path is unverified.

Impact: a user deliberately pinning ptxas for Triton silently gets the [paths] cuda ptxas, changing generated code with no diagnostic. Fix: restore "caller value wins" for TRITON_PTXAS_PATH (keep not in os.environ), or at minimum print/stage-update which ptxas won; and add a test for blank + [paths] cuda unset. If the override is intended, it needs justification beyond #636 (which asks only about CUDA_HOME).

#10 [high] Research summary

Reviewed PR #690 across correctness, system-level consequences, contracts, and test/claim accuracy. Every claim below was verified by opening the file at head.

Sound areas (stated plainly, not invented issues): The layer and ordering are right — environment.apply runs before any torch import at every call site (serve.py:291→:305, :210→:219, :436→:444, :545; bench.py:205→:206), and runtime_patches.apply() (environment.py:87 → runtime_patches/init.py:95) is the first torch import, so preserving CUDA_HOME here is the only place the fix can work (torch freezes CUDA_HOME at import, kv_codec.py:23). apply runs exactly once per process on every path, so there is no double-apply. The Windows branch (environment.py:70-75) is genuinely untouched and the new configured_cuda is not None or … condition is inside the non-Windows branch only. There is no concurrency/lock/memory/hot-path or metric/rate/admission surface at all: this is synchronous once-per-process startup env setup, so that lens finds nothing.

Four substantive issues (4 Major): (1) The inherited CUDA_HOME is accepted with no validation — environment.py:61-63 takes Path(inherited_cuda) with no is_dir()/toolkit check, while the /usr/local/cuda fallback is gated on is_dir(). Because tuning.py:52-65 selects libdevice from that root "before native program identities are recorded", a stale or typo'd CUDA_HOME silently changes the compiler identity rather than failing early; a test actively asserts the invalid-value behavior (test_environment.py:110-120). (2) environment.py:78-81 silently reverses TRITON_PTXAS_PATH precedence so [paths] cuda beats an explicit ambient value, and now overwrites blank values, contrary to principle 10's "explicit user values win" — the blank case has no test and the doc says only "when unset". (3) The docs contract is not reconciled: the PR edits the decision-table row and AGENTS.md:466-473, but leaves docs/cli-design.md:46-51 ("No environment variables … with one exception") and :52-53 ("Nothing else exists") stating the opposite, and AGENTS.md:461 ("the only variable Flare interprets") — the very clause principle 10's exception points at. No maintainer has recorded a design decision on #636 (triage:design-review, zero comments). (4) AGENTS.md:456-460 requires the plan to describe what was prepared, but planning.to_dict() (planning.py:383-420) has no toolkit field, so two exports built with different ptxas/libdevice print identical plans; combined with author-disclosed absence of any multi-toolkit/end-to-end run, the actual #636 scenario is never reproduced.

Minor: stale #71 comment at environment.py:54-57 now sits directly above code implementing the opposite policy; model-preparation.md:128-130 understates the blank value; whitespace-padded CUDA_HOME normalization and the Windows path are untested. Also noted as latent only (unreachable today, since apply runs once): it reads CUDA_HOME it wrote itself, so it is not idempotent. Claim accuracy is otherwise good — the "146 passed"/10-test count checks out and the description discloses the blank-value fill; only the doc wording is imprecise.

#11 [high] LEDGER: final findings, severities, ordering for the report

Consolidated ledger for the Correctness / Contracts / System-Level lens on PR #690 (head 682152b). Entry 3 is SUPERSEDED by entry 7 — do not use entry 3's "not disclosed" claim; the blank-TRITON_PTXAS_PATH fill IS disclosed in the PR description. No Blocker found.

MAJOR findings, in report order:

M1 — Inherited CUDA_HOME accepted without validation (entry 4 + 9). ignition/cli/environment.py:61-63,69; asymmetric vs /usr/local/cuda gate at :64; blast radius via libdevice identity (ignition/preparation/tuning.py:52-65, tests/preparation/test_toolchain.py:31-36,65-69); test asserts the invalid behavior (tests/cli/test_environment.py:110-120). kv_codec._find_nvcc (kv_codec.py:26-38) degrades gracefully — do NOT claim it as blast radius.

M2 — TRITON_PTXAS_PATH precedence reversal + untested blank fill (entry 7). ignition/cli/environment.py:78-81 vs base "TRITON_PTXAS_PATH" not in os.environ; principle-10 conflict (docs/design-review.md:89-92); docs imprecise at docs/model-preparation.md:128-130 ("when unset"); tests cover non-blank (:68/:74, :98/:105) but never blank.

M3 — Design-doc contract not reconciled (entry 2). docs/cli-design.md:46-51 and :52-53 unmodified and now false; AGENTS.md:461 "only variable Flare interprets" vs the PR's own edit at AGENTS.md:468-471. Supporting process fact (from dossier, worth stating in report): issue #636 carries triage:design-review, priority:P2, bug, enhancement, and has ZERO comments — no maintainer has recorded the design decision this PR implements; #690 also has zero reviews and no CI checks on head. This is the third revision of this same 4-line decision in six weeks (#71 eugr -> c9935887 Luke Alonso -> this PR).

M4 — Selected toolkit absent from plan/report; no end-to-end evidence (entry 6). AGENTS.md:456-460 vs ignition/planning.py:383-420 (no toolkit field), printed at ignition/cli/serve.py:213, :440. All 10 tests monkeypatch _DEFAULT_LINUX_CUDA (:66,82,96,113,127,141) so the real /usr/local/cuda branch never runs; no multi-toolkit host run reproduces #636.

MINOR findings: stale #71 comment at environment.py:54-57 (entry 8 #1); doc blank-case imprecision (entry 8 #2); whitespace-padded non-empty CUDA_HOME normalization untested (entry 8 #3); Windows path untested though correct by inspection, all tests skipif nt (:61,78,92,109,123,138) (entry 8 #4; entry 1 #3); latent non-idempotency — apply reads CUDA_HOME it wrote at :61 vs :69, unreachable today because apply runs once per process (entry 5).

SOUND AREAS to state plainly (entry 1 + 9 + 5b): correct layer/placement; ordering apply-before-torch verified at all 5 call sites (serve.py:291→:305, :210→:219, :436→:444, :545; bench.py:205→:206); Windows branch untouched; no concurrency/lock/memory/hot-path/partial-failure surface; metric/rate/admission span check does not apply (no metric, rate, or admission sample changed); paths.cuda resolution unchanged (config.py:172-175, :51; test_config.py:34); claim accuracy otherwise good — 10-test count and "146 passed" arithmetic check out, description honestly discloses Windows/GPU evidence gaps.

#1 [medium] Verified sound areas for PR #690

Confirmed by opening files at PR head:

  1. Ordering is sound. environment.apply runs before any torch import at every call site:

    • ignition/cli/serve.py:291 apply -> :292 import flare_heliopause -> :305 import torch.
    • :210 apply -> :214 flare_heliopause -> :219 import torch.
    • :436 apply -> :444 import torch.
    • :545 (join) apply -> serve_peer at :549.
    • ignition/cli/bench.py:205 apply -> :206 _measure. Inside apply, runtime_patches.apply() (environment.py:87) is the first torch import (ignition/runtime_patches/init.py:95). torch.utils.cpp_extension.CUDA_HOME is a frozen module constant derived at import (ignition/preparation/kv_codec.py:23), so preserving the inherited value before runtime_patches.apply() is what makes the fix reach torch. resolve_model/Host.discover (ignition/registry.py:12-22, ignition/planning.py:13-21) are lazy/torch-free.
  2. apply is called exactly once per process on every path: export() -> _prepare (serve.py:164); _export_hosts; debug_serve; join; bench.py:205. No double-apply, so no ALREADY_NORMALIZED feedback loop today (latent only).

  3. Windows branch untouched (environment.py:70-75) — configured_cuda vs cuda comparison at :79 is inside the else/non-Windows branch only, so [paths] cuda still wins on Windows exactly as before. Platform parity code diff is null.

  4. No concurrency/lock/memory/hot-path surface: apply is a synchronous, once-per-process startup env setup; no threads, no I/O amplification, no buffering. The "metric/rate/admission span" check does not apply — the PR changes no metric, rate, or admission sample.

  5. paths.cuda resolution unchanged: Configuration.directory (ignition/cli/config.py:172-175) returns None for built-in default "" (config.py:51), which is why the default config falls through to env/default. tests/cli/test_config.py:34 asserts directory("cuda") is None. No --cuda flag exists (only config.py:51, environment.py:58 reference it).

#8 [medium] Claim accuracy + stale comment (minor)

Minor items, all verified at head.

  1. Stale comment left contradictory. ignition/cli/environment.py:54-57:
    # cuTile discovers its compiler bundle independently of the native toolkit.
    # Explicit `[paths] cuda` overrides the process environment; on non-Windows hosts
    # without `[paths] cuda`, preserve a non-empty inherited `CUDA_HOME` before
    # falling back to `/usr/local/cuda`.

The first line ("cuTile discovers its compiler bundle independently") is #71's justification for NOT reading the environment; it now sits directly above code that reads the environment. Two opposite policies in one comment block. Fix: keep the cuTile sentence as its own comment (it is still true per docs/model-preparation.md:134-137) or move it.

  1. Docs understate the blank-value case: docs/model-preparation.md:128-130 "or populating it when unset" — blank/whitespace values are also overwritten (environment.py:79). The description is correct here; the doc is not.

  2. Whitespace normalization of a preserved CUDA_HOME is understated. environment.py:61 strips, :69 re-exports:

        inherited_cuda = os.environ.get("CUDA_HOME", "").strip()

so CUDA_HOME=" /opt/cuda" becomes /opt/cuda. The description says "Non-empty inherited CUDA_HOME from os.environ (whitespace stripped), preserved", which covers it loosely; no test covers a whitespace-padded non-empty value (tests only use "" and " " -> fallback, :124, :139). Low risk, but it is a silent mutation of a caller's value.

  1. "Windows behavior unchanged" is true by inspection but untested: all 10 cases carry @pytest.mark.skipif(os.name == "nt", ...) (tests/cli/test_environment.py:61,78,92,109,123,138). Verified the Windows branch (environment.py:70-75) is outside the configured_cuda is not None or ... condition, so [paths] cuda still wins there exactly as before.

  2. Accurate claims (checked against the diff, no issue): "previously ... leaving whitespace-only CUDA_HOME values in os.environ when /usr/local/cuda was absent" — true, base skipped the whole if cuda is not None block; CPATH prepend/dedupe description matches :82-86; [paths] cuda overriding inherited CUDA_HOME matches :58-59, :68-69.

  3. The "146 passed" figure remains author-reported; head 682152b had no CI checks. Test count itself checks out: 4 single + 3-param + 3-param = 10 cases in the new file.

#9 [medium] Addendum: libdevice identity derives from the inherited CUDA_HOME

Addendum to entry 4 (strengthens it). The libdevice identity is derived from the same toolkit root, and the code requires consistency:

ignition/preparation/tuning.py:52-65:

def _prepare_compiler_toolchain():
    """Resolve forward math libraries before native program identities are recorded."""
    ...
    # Inductor selects the CUDA toolkit's libdevice for eager precision. Native
    # discovery and later materialization must see that same library identity.
    with config.patch(emulate_precision_casts=_OPTIONS["emulate_precision_casts"]):
        _set_triton_libdevice_path()

and tests/preparation/test_toolchain.py:31-36,65-69 asserts Path(CUDA_HOME)/"nvvm/libdevice/libdevice.10.bc" is what Triton's extern_libs selects.

So an unvalidated inherited CUDA_HOME flows into the libdevice choice used for compiler-cache identities ("before native program identities are recorded", tuning.py:53). A stale/typo'd CUDA_HOME therefore does not merely fail early — it can select a different libdevice, i.e. a different compiler identity, silently. That is the strongest concrete argument for validating the inherited path and/or recording the resolved toolkit in the plan (entry 6).

Also worth stating positively for the report: placement is right. environment.apply is the single place that sets these variables before torch import (serve.py:291->:305, bench.py:205->:206), so honoring CUDA_HOME here — not in torch's consumers — is the correct layer per the charter's "solve the right problem in the right place". The concern is precedence/visibility, not location.

One more note: _find_nvcc (ignition/preparation/kv_codec.py:26-38) degrades gracefully with a bad CUDA_HOME because it falls back to shutil.which("nvcc") then /usr/local/cuda/bin/nvcc — so the kv_codec path is NOT the blast radius; libdevice/torch + ptxas are.

#5 [low] Latent: apply reads its own output (non-idempotent, unreachable today)

Minor (latent — not reachable today, but the PR creates the hazard).

(a) Stale-state / self-feedback hazard. apply is not idempotent with respect to the PR's own output: it now READS CUDA_HOME (environment.py:61) and WRITES it (:69). A second apply in the same process with [paths] cuda unset therefore cannot fall back to _DEFAULT_LINUX_CUDA, because line :69 previously exported the default as CUDA_HOME, which line :61 now reads back as "inherited". Concretely: first call with no CUDA_HOME sets CUDA_HOME=/usr/local/cuda; if /usr/local/cuda is later removed or the second call is made on a different config, the "inherited" branch (:63) wins and /usr/local/cuda is preserved permanently. Verified NOT reachable at head: each process calls apply exactly once (export -> _prepare serve.py:164; _export_hosts; debug_serve; join; bench.py:205). Values set by apply are only ever the same values, so today the re-read is a no-op. Fix: compute the effective toolkit once and record it (e.g. return it, or store a module-level resolved value) rather than re-deriving from the mutated os.environ; or mark provenance (see next note).

(b) Latent TLS-narrowing bug, unrelated to this PR's lines but in the same block: apply sets CUDA_VISIBLE_DEVICES from gpus (environment.py:44-46) and join passes (gpu,) (serve.py:545). torch has NOT been imported at that point on the join path (serve.py:292/:444/:219 are the torch imports and none precedes :545), so torch's get_device_capability is harmless. No change needed; noting only that the PR does not affect it.