Code review summary report · NVIDIA/hyperflare-inference #574

Raw Markdown for agents: https://autobot.eidonix.com/p/9a345dc7-78b0-4353-98c7-54d3a29e6e3b.md

Candidate brief — PR #574 (for Verify & Adjudicate)

Identifiers. PR #574, open, "Strip unguarded attributes from hyperflare_recipes objects in AOT guard serialization". Author fordbmorris (Discord woooflet), opened 2026-11-28 19:21. Branch pr/aot-guard-pickler-hyperflare-recipes → main, head 16ffc6fdd8e0132cf3c5c0c1da98d456cf05c184. +54/−1 across 2 files (ignition/preparation/forward_metadata.py +1/−1 at line 42; tests/preparation/test_guard_code.py +53/−0 at lines 252–302). Zero reviews, zero CI checks on head; the only discussion entry is the flare-autobot case-file notice (no human review, no prompt-injection attempt found in title, description or comments). Mentions #509 (merged, commit b0d35934, immediately before head).

Key findings (framing for the adjudicator)


Candidate Blockers

B1. The PR is unverified on its own head, and both suites are CPU-only

docs/design-review.md:247-251 (verbatim):

- **Disclosure does not excuse skipping runnable CPU checks.** All three layers
  run without a GPU or model checkpoint. Leaving an applicable crate test,
  simulator sweep, TLA+ conformance run, or Kani proof unrun blocks commit and
  PR acceptance; noting it as a limitation does not make the omission
  acceptable.

The PR body concedes the gap and pushes the work to the reviewer:

**Caveats:** **Original unit tests ran prior to rebasing onto `#509`'s extraction of
`_uses_custom_object_state` (`167f22c8`); please run CI on `test_guard_code.py` and
`test_core_boundary.py`. Note: `ignition/preparation/rebuild_manifest.py:365` has a similar
`('b12x.', 'ignition.')` check intentionally left out of this 1-line PR unless maintainers want
it included or replaced by a declared-root mechanism.**

tests/preparation/test_guard_code.py:147 is torch.device("cpu") — the only device reference in the file — so the suite needs no GPU and no checkpoint; docs/design-review.md:180-186 names tests/preparation a required layer-1 suite. History narrows the gap: b0d35934 (#509) is the commit immediately before head 16ffc6f, and the head commit itself carries the forward_metadata.py:42 edit — the head is rebased; only the recorded run predates it. Fix: run pytest tests/preparation/test_guard_code.py tests/preparation/test_core_boundary.py on 16ffc6f and paste counts/skips. This same run is the settlement for the unrun "fails on main" claim behind B2 (see Provenance).

B2. The new test never asserts the stripping it is named for

tests/preparation/test_guard_code.py:252-265 and :277-302 (new):

class _UnpicklableHandle:
    def __reduce__(self):
        raise TypeError("compiled kernel handles cannot be pickled")

class _RecipeKernelOwner:
    __module__ = "hyperflare_recipes.components.synthetic"

    def __init__(self, scale):
        self.scale = scale
        self.compiled_handle = _UnpicklableHandle()
...
def test_guard_pickler_strips_unguarded_attributes_from_recipe_objects(monkeypatch):
    import types
    from torch._dynamo.aot_compile_types import GraphModuleSerializableCallable

    module_name = "hyperflare_recipes.components._synthetic_guard_test"
    synthetic = types.ModuleType(module_name)
    _RecipeKernelOwner.__module__ = module_name
    synthetic._RecipeKernelOwner = _RecipeKernelOwner
    monkeypatch.setitem(sys.modules, module_name, synthetic)
...
    loaded = type(compiled).deserialize(data)
    torch.testing.assert_close(loaded(forward), torch.full((2,), 3.0))
    assert loaded.guard_check(forward) is True
    forward.owner.scale = 5
    assert loaded.guard_check(forward) is False
    forward.owner.scale = 3
    assert loaded.guard_check(forward) is True

There is no _Missing assertion anywhere in it: the test passes iff no exception is raised, so it proves the pickler did not crash, not that compiled_handle became _Missing. The file's own idiom for this branch does assert it — tests/preparation/test_guard_code.py:118-124:

    restored = _roundtrip_guard(
        tensor,
        guard_tree_values={id(tensor): tensor, id(guarded_scale): guarded_scale},
    )
    assert tuple(restored.shape) == (4, 8)
    assert tuple(restored.scale.shape) == (4, 1)
    assert isinstance(restored.unguarded, _Missing)

Rules: AGENTS.md:194-199 ("Tests must exercise the affected behavior or contract; source-text checks and mocks that bypass the behavior cannot establish runtime correctness"); AGENTS.md:188-193 (reject churn); docs/design-review.md:135-146 (principle 15 — rejection criteria apply to tests too). Interaction with C3 below must be adjudicated together: taking C3 adds the missing assertion and removes 34 lines, dissolving B2; if C3 is rejected, B2 must be repaired in place.


Candidate Should Fix

SF1. Hardcoded package literal versus the project's documented external-recipe mechanism (4 lenses concur)

ignition/preparation/forward_metadata.py:39-45 (the changed predicate):

def _uses_custom_object_state(value):
    return (
        hasattr(value, '__dict__')
        and type(value).__module__.startswith(('ignition.', 'b12x.', 'hyperflare_recipes.'))
        and not inspect.isclass(value)
        and not isinstance(value, _NON_OBJECT_NEW_TYPES)
    )

_NON_OBJECT_NEW_TYPES (forward_metadata.py:33-36) is (Tensor, nn.Module, enum.Enum, int, float, str, bytes, dict, list, tuple, set, frozenset).

The mechanism it bypasses — the repo handles external packages declaratively, never by name:

# ignition/registry.py:24-31
_ACTIVE_RECIPES: contextvars.ContextVar[tuple[Recipe, ...]] = contextvars.ContextVar(
    "flare_active_recipes", default=()
)

def current_recipes() -> tuple[Recipe, ...]:
    """Return the recipes active in the current CLI invocation context, or an empty tuple."""
    return _ACTIVE_RECIPES.get()
# ignition/preparation/source_identity.py:12-25
_EXTRA_ROOTS: contextvars.ContextVar[tuple[tuple[str, Path], ...]] = contextvars.ContextVar(
    "flare_source_identity_roots", default=()
)

@contextmanager
def source_roots(roots=()):
    """Bind external `(label, path)` source roots for the duration of a CLI invocation."""

Governing rule, AGENTS.md:379-384 / :392-393:

- Official model recipes live in `local-inference-lab/hyperflare-recipes`
  (`hyperflare_recipes/recipes/`), and external recipe repositories can pass
  their own `Recipe` tuples directly to `ignition.cli.main(...)`.
...
  Core `ignition` must never import `hyperflare_recipes` or introduce a
  plugin discovery framework.

Any external recipe package whose module name is not hyperflare_recipes still reproduces the exact PicklingError: Can't pickle <class 'triton.compiler.compiler.CompiledKernel'> the PR describes (forward_metadata.py:41 requires __dict__, so a slots-only class falls through too). Fix options, cheapest first, to constrain the judgment: (a) derive the roots from registration — __module__ roots of current_recipes() targets and/or _EXTRA_ROOTS labels, read through a ContextVar exactly as _MODE/_TENSOR_KINDS already are at forward_metadata.py:25-26 (keeps it a string comparison, imports nothing, generalizes); (b) hoist one named constant with a docstring stating the rule (also satisfies SF2); (c) keep the literal and state in the description that it is a stopgap with a referenced follow-up, per AGENTS.md:188-193.

Dropped sub-claim (do not carry): the simplicity lens's "just delete the module-prefix clause". _uses_custom_object_state is applied from a repo-root pickle, so removing the clause would force object.__new__ + vars() reduction onto arbitrary third-party classes (torch/triton objects with __dict__) — the allowlist exists to avoid precisely that.

SF2. The second, now-divergent allowlist at rebuild_manifest.py:365

ignition/preparation/rebuild_manifest.py:362-369:

elif is_dataclass(value) and not isinstance(value, type):
    owner = f'{type(value).__module__}.{type(value).__qualname__}'
    children = ((f'.{field.name}', getattr(value, field.name)) for field in fields(value))
elif type(value).__module__.startswith(('b12x.', 'ignition.')) and hasattr(value, '__dict__'):
    owner = f'{type(value).__module__}.{type(value).__qualname__}'
    children = ((f'.{key}', child) for key, child in vars(value).items())
else:
    return

The legacy branch is real, not dead code — ignition/preparation/rebuild_manifest.py:445-449:

if isinstance(roots, WeightDeclaration):
    return _declared_metadata(roots)

tensors, unavailable = [], []
for name, owner, tensor in weight_views(roots):

A plain-dict rebuild_weights (supported in-repo) falls through to weight_views and hits :365; consumers are ignition/preparation/runtime_core.py:130 and :367-369. Reachability correction (supersedes the stronger upstream claim): the live in-repo caller, helios/tests/runtime_core_fixture.py:186 (rebuild_weights={"weight": tensors["weight"]} if legacy else declared), is CUDA-only, and it passes raw tensors that match the isinstance(value, torch.Tensor) branch at rebuild_manifest.py:347-349 and never need the prefix clause. So the divergence is exercised on GPU CI only, and no lens nor I could show that a hyperflare_recipes.* weight holder is silently dropped. This stays a "share one constant / make the asymmetry deliberate and documented" request, not a demonstrated weight-loss bug. Judgment to settle: whether :365 should be widened in this PR or the asymmetry stated with a reason (the PR body currently poses it as merge logistics).

SF3. An undocumented serialization contract is now imposed on externally owned classes

ignition/preparation/aot.py:153-166:

    if isinstance(obj, JITFunction):
        return _deserialize_triton_kernel, (_serialize_triton_kernel(obj),)
    from .forward_metadata import _uses_custom_object_state

    if _uses_custom_object_state(obj):
        state = {key: value if id(value) in self.guard_tree_values
                 else _Missing('unguarded attribute')
                 for key, value in vars(obj).items()}
        from b12x.preparation.device import DetectedDevice

        if isinstance(obj, DetectedDevice):
            return restore_prepared_device, (type(obj), state)
        return _guard_object, (type(obj),), state
    return super().reducer_override(obj)

with _guard_object at aot.py:98-99 (return object.__new__(cls)) and the docstring at aot.py:103 ("Exclude unguarded kernel resources from prepared Python objects.").

Verified residual contract for any matched class: the pickler bypasses custom __getstate__/__reduce__, and it requires non-slot __dict__ state (forward_metadata.py:41), so a slots-only recipe class holding a compiled handle still raises the original PicklingError. Recipe authors must therefore keep serializable state in __dict__, which is documented nowhere: docs/preparation-development.md:377-384 is the nearest guard-retention text and says nothing about module prefixes, and a search of docs/ finds no mention of _uses_custom_object_state or the prefix rule. Fix: one sentence in docs/preparation-development.md and/or the _GuardPickler docstring (aot.py:103); optionally union __slots__ into the state so the strip is complete.

Refuted sub-claim (do not carry): the correctness lens's "a recipe class with a custom __setstate__ expecting its own __getstate__ shape will raise at load". No state-setter is emitted — the guard reduction is a 3-tuple (_guard_object, (type(obj),), state) (aot.py:165), and the _set_state used elsewhere is value.__dict__.update(state) (forward_metadata.py:164-165) — so pickle's BUILD step does not call __setstate__ on this path and that failure cannot occur.


Candidate Subtract / Simplify

C3. Replace the 53 added lines with ~20 that assert the strip

Deduplicates subtractive #1, simplicity #3, conventions nits 3a/3b, architecture S2 and the missing-assertion half of B2. It reuses the file's own helper at tests/preparation/test_guard_code.py:91-100:

def _roundtrip_guard(value, *, guard_tree_values=None, empty_values=None, missing_values=None):
    buffer = io.BytesIO()
    pickler = _GuardPickler(
        {} if guard_tree_values is None else guard_tree_values,
        {} if empty_values is None else empty_values,
        {} if missing_values is None else missing_values,
        buffer,
    )
    pickler.dump(value)
    return pickle.loads(buffer.getvalue())

Corrected replacement (~20 lines; _Missing is already imported at test file line 14). Note: the sketches proposed by the subtractive and simplicity lenses are buggy — with guard_tree_values={id(prepared): prepared} alone, prepared.scale is not guarded, so restored.scale becomes _Missing and assert restored.scale == 3 fails. The guarded value must be listed explicitly, as the existing test does at :120:

class _RecipePrepared:
    __module__ = "hyperflare_recipes.components.synthetic"

    def __init__(self, scale):
        self.scale = scale
        self.compiled_handle = _UnpicklableHandle()      # reuse tests/preparation/test_guard_code.py:252-254


def test_guard_pickler_strips_unguarded_attributes_from_recipe_objects(monkeypatch):
    import types

    module = types.ModuleType(_RecipePrepared.__module__)
    module._RecipePrepared = _RecipePrepared
    monkeypatch.setitem(sys.modules, _RecipePrepared.__module__, module)
    prepared = _RecipePrepared(3)
    restored = _roundtrip_guard(
        prepared,
        guard_tree_values={id(prepared): prepared, id(prepared.scale): prepared.scale},
    )
    assert type(restored) is _RecipePrepared
    assert restored.scale == 3
    assert isinstance(restored.compiled_handle, _Missing)

What it drops, each verifiably redundant with code already in the file: the compile/serialize block (:288-296) duplicating :236-244; guard invalidation True → False → True (:298-302) already at :47-51 and :248-249; output parity (:297) already at :245; the _RecipeForward wrapper (:268-274); the dead __module__ literal (:258, overwritten at :283); the unrestored class mutation at :283; the local import types (:278). It still pins the fix because the unpatched predicate falls through to super().reducer_override (aot.py:166), whose default reduction pickles vars(obj) including the raising _UnpicklableHandle. Residual risk: _roundtrip_guard bypasses torch.compile, so it does not by itself prove type(compiled).serialize stopped raising — that pipeline shape is already covered at :232-249. If maintainers want the recipe object inside a compiled graph, keep the PR's compile block and only add the isinstance(..., _Missing) assertion; either path closes B2.


Candidate Nits

N1. One pass over the PR description (all prose-lens items merged into a single edit)

AGENTS.md:103-112 requires each material claim to carry "the behavior tested, baseline or reference, configuration, result, and limits of the conclusion". The published evidence bullet reads in full: "Verified with pytest tests/preparation/test_guard_code.py tests/preparation/test_core_boundary.py on ARM64 GB10 and end-to-end 4-Spark TP4 Inkling 2 Small exports." It gives no pass counts, no skips, no baseline, and no command/core/revision for the end-to-end run (the "154 multimodal graphs" figure the architecture lens quotes is not in the published body); test_core_boundary.py is listed without saying what it establishes (it only AST-scans imports, tests/preparation/test_core_boundary.py:28-36); and the Caveats paragraph poses the rebuild_manifest.py:365 question as merge logistics rather than a stated reason. One edit: add the pre-change failure as the baseline (revert line 42, show the test failing), state counts and skips, say what test_core_boundary establishes, and either give the reason :365 is out of scope or cross-reference SF2 — then delete the Caveats paragraph. Structure (why → what changed → benefit/evidence → caveats) and the mandatory Discord: woooflet line are already correct (AGENTS.md:72-112, :142-153).

N2. Two small fidelity gaps in the fixture (low; vanishes under C3)

tests/preparation/test_guard_code.py:252-254 raises TypeError where the field failure is PicklingError from triton.compiler.compiler.CompiledKernel (raising pickle.PicklingError would reproduce the field signature); and :298-302 asserts is True/is False identity while the rest of the file asserts truthiness (:248-249).


Provenance and limits (weigh, do not re-research)

  1. "The new test fails on main and passes with the fix" is lens consensus from three reviewers, none of whom ran pytest — and neither did this brief's author. It is plausible from the code path (aot.py:166 → default reduction → __reduce__ at :253-254 raises) but unproven. B1's requested pytest run settles it in one command and should be treated as the settlement, not a restatement of the caveat.
  2. The description's end-to-end claim is unverifiable in this repo: no hyperflare_recipes code exists here (test_core_boundary.py:40 even asserts the package is absent), so nobody could confirm that PreparedResidualMix-style objects truly reach the widened branch. A coverage-limits note attached to N1, not a defect claim.

Dropped as noise (do not re-report)

Open questions for adjudication

  1. Accept C3 (smaller test, adds the assertion) or repair B2 in place? They are one decision.
  2. Generalize SF1 by deriving roots from registration (a), hoist a constant (b), or accept a stated stopgap (c)? All are compatible with AGENTS.md; (c) needs a description edit.
  3. Is rebuild_manifest.py:365 in scope for this PR, or explicitly deferred with a stated reason (SF2/N1)?
  4. Is the unrun-on-head gap (B1) acceptable to the project as a merge gate given docs/design-review.md:247-251, or does the author need to paste the run first? The rule text says the latter.