Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #678

Raw Markdown for agents: https://autobot.eidonix.com/p/bda43d8a-3c6c-49ab-bbdd-671ce920b377.md

#1 [high] Subtraction lens: tuning_replicas propagation is speculative parity (no in-tree reader)

PR #678 (head 90b0d31), subtraction lens, finding 1 — HIGH.

Evidence that the bind is never read on the replica path:

AGENTS.md:165-169 ("Hypothetical future consumers ... do not establish a need for a change") and AGENTS.md:188-193 ("Reject unsupported abstractions and churn ... Do not add frameworks, extension points, speculative compatibility, fallback layers ... without a concrete requirement"). This is the PR's second half and it fails both.

Code to delete (verbatim):

def _replica(parent, prepare, recipe_name, snapshot, values, gpu_uuids, options, extra_source_roots):

(tuning_replicas.py:142) →

    from .source_identity import source_roots
...
    with source_roots(extra_source_roots), CoreStorage(world=plan.world_size) as storage:

(tuning_replicas.py:153, :158) →

    from .source_identity import current_source_roots

    extra_source_roots = current_source_roots()

(tuning_replicas.py:174-176) →

                          {"kernel_cache": options.get("kernel_cache")},
                          extra_source_roots), name=f"flare-tuning-{replica}")

(tuning_replicas.py:193-194).

Consequence: tests/preparation/test_forward_cache_sources.py:163-246 (≈84 lines: _record_replica_source_roots, _REPLICA_TEST_RECIPE Recipe/Checkpoint/RankCosts fixture, _cpu_replica_entry cuda/CoreStorage patching, test_prepare_recipe_propagates_source_roots_to_spawned_tuning_replica) is all scaffolding for an unread ContextVar, and it mutates module-global tuning_replicas._replica (:234) and stubs CUDA to fake a real replica. Delete with the code above.

If maintainers insist on keeping parity plumbing, the cheap fix inside the existing contract is to move the single bind above _resolve_recipe (tuning_replicas.py:155 currently resolves/imports the recipe BEFORE the bind at :158) instead of adding a second context manager; as written the bind cannot affect recipe resolution, i.e. it is decoration.

#3 [high] Research summary

Subtraction/Simplicity/Conventions review of PR #678 done; findings saved to scratchpad (entries 1-2).

One high-value simplification: the entire tuning_replicas.py half of the diff (_replica(..., extra_source_roots) at tuning_replicas.py:142, the source_roots(extra_source_roots) bind at :153/:158, the capture at :174-176 and the args-tuple pass at :193-194) propagates a ContextVar that nothing on the replica path reads: replicas run prepare(..., compile_forwards=False) and exit at TuningComplete (:160-162), so no ForwardCache / source_identity() is ever reached in a child — the PR body says so itself. That is speculative compatibility under AGENTS.md:165-169 and :188-193, and it drags ~84 lines of CUDA-stubbing test scaffolding plus a module-global _replica monkeypatch (test_forward_cache_sources.py:163-246) with it. All of it should be deleted, leaving the accessor plus the two call-site swaps, which is the only defensible outcome here. If parity is insisted upon, the bind belongs above _resolve_recipe (:155, currently before the bind, so it cannot even affect resolution) rather than as a second layer.

Lower value: the pre-existing unused extra_roots= keyword of source_identity() is a second unexercised binding path now that a public reader exists; test_current_source_roots_reflects_active_scope adds only contextmanager-nesting coverage over a one-line .get(); the docstring edit at source_identity.py:24 only documents the speculative context; and the new extra_source_roots name drifts from the repo-wide extra_roots name for the same data. Aside from the replica half, the diff is lean: current_source_roots() is 4 lines and correctly removes #670's two private imports, and _stub_forward_cache_root() is a genuine test dedupe.

#4 [high] Verbatim snippets + exact citations for the #678 subtraction report

Quote bank for PR #678 subtraction review (head 90b0d31, base cc0a49d2). Cited at the head I read.

A. tuning_replicas.py:155-158 (bind is downstream of recipe resolution — the moved-bind alternative)

    recipe = _resolve_recipe(prepare, recipe_name)
    plan = Plan(recipe=recipe, **values)
    torch.cuda.set_device(0)
    with source_roots(extra_source_roots), CoreStorage(world=plan.world_size) as storage:

B. tuning_replicas.py:160-165 (why no ForwardCache is reached — the "defensive parity" proof)

            prepare(snapshot, plan, compile_forwards=False, retain_graphs=False, progress=None,
                    core_storage=storage, **options)
        except TuningComplete:
            torch.cuda.synchronize()
        else:
            raise RuntimeError("a tuning replica continued beyond kernel preparation")

C. tuning_replicas.py:168-176 (entry guard + capture)

def prepare_recipe(prepare, snapshot, plan, **options):
    """Prepare serving ranks while optional replicas contribute kernel candidates."""
    if not plan.tuning_gpus:
        return prepare(snapshot, plan, **options)
    if options.get("ranks") is not None:
        raise ValueError("local tuning replicas cannot replace multi-host preparation")
    from .source_identity import current_source_roots

    extra_source_roots = current_source_roots()

Note: prepare_recipe already falls back to plain prepare(...) at :170-171 when plan.tuning_gpus is empty, and the peers' prepare runs in-process at :197 with the parent's context bound — so the only path that needs propagation is the spawned :187-196 loop, which never reads it.

D. source_identity.py:33-48 (pre-existing dead keyword, second binding path)

def source_identity(*, extra_roots=()):
...
    combined_roots = (*_EXTRA_ROOTS.get(), *extra_roots)

Callers, all bare (search_code source_identity\(): ignition/cli/serve.py:193, :415, :546; ignition/preparation/host_ranks.py:630; ignition/preparation/rebuild_manifest.py:329.

E. test_forward_cache_sources.py:151-160 (the thin accessor test, quoted in report)

def test_current_source_roots_reflects_active_scope(tmp_path):
    first = tmp_path / "first_recipes"
    second = tmp_path / "second_recipes"
    assert current_source_roots() == ()
    with source_roots((("first", str(first)),)):
        assert current_source_roots() == (("first", first),)
        with source_roots((("second", second),)):
            assert current_source_roots() == (("second", second),)
        assert current_source_roots() == (("first", first),)
    assert current_source_roots() == ()

F. test_forward_cache_sources.py:234 + 199-207 (global patch of the production entry point; scaffolding that dies with the replica half)

    monkeypatch.setattr(tuning_replicas, "_replica", _cpu_replica_entry)
def _cpu_replica_entry(*args):
    import torch
    from ignition.preparation import core_storage

    with pytest.MonkeyPatch.context() as patch:
        patch.setattr(torch.cuda, "set_device", lambda _: None)
        patch.setattr(torch.cuda, "synchronize", lambda: None)
        patch.setattr(core_storage, "CoreStorage", lambda **kwargs: nullcontext())
        tuning_replicas._replica(*args)

G. Convention citations, verbatim:

H. Name drift evidence: extra_roots used at rank_group.py:44-45 (_peer(..., extra_roots=())), rank_group.py:60 (with bind_source_roots(extra_roots):), rank_group.py:297/:310, source_identity.py:33/:48, while tuning_replicas.py uses extra_source_roots at :142, :158, :174-176, :194.

I. Diff scale for the report: +136/−20 across 5 files (aot.py +2/−2, rank_group.py +2/−2, source_identity.py +6/−1, tuning_replicas.py +8/−3, tests +118/−12). Of that, the defensible part is ~10 lines; ~130 lines are the replica half plus its test.

J. Nota bene for the report: no CI run exists on this head and the only review predates the rebase (Discovery Dossier), so the author-reported "36 passed" figure is unverified; the replica test is Linux+flare_heliopause-gated (:210-212) and stubs CUDA/CoreStorage, so it cannot establish real replica behaviour on GPUs anyway.

#2 [medium] Subtraction lens: what to keep — the accessor refactor is the real value; dedupe test scaffolding

PR #678 subtraction lens, findings 2-4 (medium/low).

KEEP — the accessor itself is the whole defensible change: source_identity.py:17-19

def current_source_roots() -> tuple[tuple[str, Path], ...]:
    """Return the bound external `(label, path)` source roots for this context."""
    return _EXTRA_ROOTS.get()

plus aot.py:845-847 and rank_group.py:295-297 switching to it. After the change _EXTRA_ROOTS is referenced only inside source_identity.py (definition :12-14, accessor :19, set/reset :26,:30, and :48) — verified by search_code. 6 lines, no new abstraction, replaces two private imports left by merged #670. No simplification available here; it is already minimal.

adjacent dead code worth deleting instead of patched (touches a file this PR edits): source_identity(*, extra_roots=()) (source_identity.py:33, used at :48 combined_roots = (*_EXTRA_ROOTS.get(), *extra_roots)) has NO caller that passes the keyword — grep of source_identity( shows serve.py:193,415,546, host_ranks.py:630, rebuild_manifest.py:329, all bare. Now that the ContextVar has a public reader, this keyword is a second, unexercised binding path for the same data; deleting it removes a fallback layer (AGENTS.md:188-193). Optional, pre-existing.

LOW — test_current_source_roots_reflects_active_scope (test_forward_cache_sources.py:151-160) only exercises a one-line .get() plus contextmanager reset; the two spawn tests (:120-123, :242-245) already assert the accessor's values across a process boundary, so the only extra coverage is contextmanager nesting/reset, which source_roots already owned before this PR. Removable without losing the PR's claim.

LOW — docstring churn at source_identity.py:24 ("...for the active CLI or spawned worker context") exists only to describe the speculative replica context; revert it if the tuning_replicas half is dropped (AGENTS.md:188-193 unsolicited comment expansion). Also: parameter naming drifts — every other site calls this data extra_roots (rank_group.py:44-45 _peer(..., extra_roots=()), source_identity.py:33 extra_roots), while tuning_replicas.py:142,158,174-176,194 introduce extra_source_roots for the same value.

Test-fixture duplication (goes away with finding 1): the replica test builds its own Recipe/Checkpoint/RankCosts/Plan fixture (test_forward_cache_sources.py:175-196, 218-233) and re-does the baseline-root comparison already done at :109-123; _stub_forward_cache_root() (:35-42) was extracted, which is the one good dedupe in the test diff.