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

Raw Markdown for agents: https://autobot.eidonix.com/p/6515a852-afd0-4b8c-bce6-11ac2c00c6ed.md

#1 [high] PR #574 — verified facts & exact code quotes

PR #574 "Strip unguarded attributes from hyperflare_recipes objects in AOT guard serialization", author fordbmorris, head 16ffc6f, +54/−1, 2 files. Discussion contains only the flare-autobot case-file notice (no reviewer instructions, no injection attempt).

DIFF: ignition/preparation/forward_metadata.py +1/−1 (line 42 only) and tests/preparation/test_guard_code.py +53/−0 (lines 252-302).

ignition/preparation/forward_metadata.py:39-45 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 at :33-36 = (Tensor, nn.Module, enum.Enum, int, float, str, bytes, dict, list, tuple, set, frozenset).

Exactly TWO callers (search_code _uses_custom_object_state): aot.py:157 and forward_metadata.py:277. ignition/preparation/aot.py:155-166 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)

aot.py:98-99 def _guard_object(cls): return object.new(cls) aot.py:102-103 docstring: """Exclude unguarded kernel resources from prepared Python objects."""

ignition/preparation/forward_metadata.py:277-278 (second caller, gated on getattr) if _uses_custom_object_state(value) and hasattr(type(value), 'getattr'): return _object, (type(value),), dict(vars(value)), None, None, _set_state forward_metadata.py:160-165 def _object(cls): return object.new(cls) def _set_state(value, state): value.dict.update(state)

ignition/preparation/rebuild_manifest.py:362-369 (the stale second list) elif is_dataclass(value) and not isinstance(value, type): owner = ... 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 rebuild_manifest.py:441-449 rebuild_weights_metadata: if isinstance(roots, WeightDeclaration): return _declared_metadata(roots) else for name, owner, tensor in weight_views(roots). Consumers: ignition/preparation/runtime_core.py:130 and :367-369 pass rebuild_weights_metadata(rebuild_weights).

tests/preparation/test_guard_code.py highlights: :91-100 _roundtrip_guard(value, *, guard_tree_values=None, empty_values=None, missing_values=None) — builds _GuardPickler directly, pickler.dump(value); return pickle.loads(...). :104,146,178,204 are the four test_guard_pickler_* unit tests. :124 assert isinstance(restored.unguarded, _Missing). :139-143 _IgnitionInt sets __module__ = "ignition.test_builtin_subclass" in the class body; :212-214 its test injects the module via monkeypatch.setitem(sys.modules, ...) only (never mutates the class). :232-249 test_guard_serialization_roundtrips_tensor_user_attributes already does torch.compile+aot_compile+serialize+deserialize+assert_close+guard_check; asserts truthiness at :248-249. NEW :252-254 _UnpicklableHandle.__reduce__ raises TypeError("compiled kernel handles cannot be pickled") — NOT PicklingError (correctness nit 2 refuted as significant: repo-root question is only whether the test discriminates, and it does; lens itself admitted this). NEW :257-258 class _RecipeKernelOwner: __module__ = "hyperflare_recipes.components.synthetic" — dead: overwritten at :283. NEW :268-274 _RecipeForward wrapper class. NEW :277-302 test body; :283 _RecipeKernelOwner.__module__ = module_name plain assignment (never restored); :285 monkeypatch.setitem(sys.modules, module_name, synthetic). NEW assertions: :297 assert_close, :298/:300/:302 guard_check is True/is False/is True. NO assertion on stripping (no isinstance(..., _Missing)).

VERIFIED / REFUTED:

#2 [high] CANDIDATE BRIEF — PR #574 for Verify & Adjudicate

Candidate brief — PR #574 (head 16ffc6f, +54/−1, 2 files)

Key findings (framing for the adjudicator)

Candidate Blocker 1 — PR is unverified on its own head; both suites are CPU-only

Both files are CPU-only (tests/preparation/test_guard_code.py:147 is torch.device("cpu")); docs/design-review.md:240 and :247-251 make an unrun applicable CPU suite a hard gate: - Disclosure does not excuse skipping runnable CPU checks. All three layers run without a GPU or model checkpoint. Leaving an applicable crate test, simulator run, or Kani proof unrun blocks commit and PR acceptance; noting it as a limitation does not make the omission acceptable. The PR itself asks reviewers to do the run: "please run CI on test_guard_code.py and test_core_boundary.py". Head 16ffc6f has no checks. History confirms the disclosed gap is real but narrow: b0d35934 (#509) is the commit immediately before head 16ffc6f, and the head commit itself contains 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.

Candidate Blocker 2 — the new test never asserts the stripping it is named for (53 lines, duplicate plumbing)

tests/preparation/test_guard_code.py:252-262, 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):
    module_name = "hyperflare_recipes.components._synthetic_guard_test"
    ...
    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

No _Missing assertion anywhere: the test passes iff no exception is raised. The file's own unit idiom for this branch asserts 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) Blocking-strength rules: AGENTS.md:194-199 (tests must exercise the affected contract; scaffolding churn), AGENTS.md:188-193, docs/design-review.md principle 15 (rejection criteria apply to tests). Note in the PR's favour: the test is discriminating (see Sub1's drop-in, same fixture, _Missing). Interaction to adjudicate: if the reviewer accepts Sub1 (parameterize/replace), the fix is the method call monkeypatch.setattr(f, '_uses_custom_object_state', ...)-style allowing the existing assertion to run against a hyperflare_recipes.* object; then B2 dissolves and the 53 lines go. If not, B2 must be repaired in place (add isinstance(..., _Missing) via a direct pickler round-trip).

Candidate Should Fix 1 — hardcoded package literal vs. 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) ) The mechanism it bypasses (verified): 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 ("external recipe repositories can pass their own Recipe tuples directly to ignition.cli.main(...)") with AGENTS.md:392-393 ("Core ignition must never import hyperflare_recipes or introduce a plugin discovery framework"). Fix options, cheapest first (constrains downstream judgment): (a) derive the roots from registration — __module__ roots of current_recipes() targets / _EXTRA_ROOTS labels, read via a ContextVar exactly like _MODE/_TENSOR_KINDS (forward_metadata.py:25-26); keeps it a string comparison, imports nothing, generalizes. (b) hoist one named constant + docstring stating the rule (also satisfies SF2). (c) keep the literal and say it is a stopgap with a follow-up reference (AGENTS.md:188-193). Refuted sub-claim to discard: the simplicity lens's "just drop the module-prefix clause entirely". _uses_custom_object_state is applied from repo-root pickling; removing the clause would put object.__new__ + vars() reduction on third-party classes (e.g. torch/triton objects with __dict__), which the allowlist exists to avoid. Do not carry it.

Candidate Should Fix 2 — the second, now-divergent allowlist at rebuild_manifest.py:365 is reachable

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 Ignition/preparation/rebuild_manifest.py:445-449 shows the legacy branch is real, not dead: if isinstance(roots, WeightDeclaration): return _declared_metadata(roots)

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

Reachability evidence (settles "is it dead code?"): helios/tests/runtime_core_fixture.py:186 — rebuild_weights={"weight": tensors["weight"]} if legacy else declared — exercises the dict path with legacy=True, and this fixture demonstrably runs (its RuntimeCore export path needs no GPU). So a plain-dict root is an in-repo supported input and hits :365. Judgment to settle: whether a hyperflare_recipes.* non-Module/non-dataclass weight holder exists on that path. Sharing one constant with SF1 makes the answer a one-line reviewable decision; leaving it stale is the exact defect class the PR fixes.

Candidate Should Fix 3 — undocumented serialization contract imposed on externally-owned classes (narrowed, verified slice)

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)   # 2-tuple: state passed as arg
    return _guard_object, (type(obj),), state                # 3-tuple: state comes back UNCHANGED from object.__new__

No state-setter is emitted (_guard_object at aot.py:98-99 returns the bare object; the 3rd tuple element is returned as-is), so load does not call __setstate__. The real residual contract: for any matched class the pickler (i) bypasses __getstate__/__reduce__, and (ii) requires non-slot __dict__ state (forward_metadata.py:41 hasattr(value, '__dict__')) — a slots-only recipe class holding a compiled handle still raises the original PicklingError. Fix: one sentence in docs/preparation-development.md (nearest text at :377-384 says nothing about this; grep over docs/ finds no mention of _uses_custom_object_state or the prefix rule) and/or a line in the _GuardPickler docstring at aot.py:103. Optionally union __slots__ into the state so the strip is complete. Refuted sub-claim to discard: "a recipe class with a custom __setstate__ expecting its own __getstate__ shape will raise at load" — no setter is emitted, so it cannot occur.

Candidate Subtract / Simplify 1 — replace the 53 added lines with ~20 that assert the strip

Deduplicates: subtractive #1, simplicity #3, conventions nits 3a/3b, architecture S2, and the un-asserted-test half of B2. Reuses the file's own helper at :91-100 (_roundtrip_guard, which builds _GuardPickler and does pickle.loads) and the injected-module idiom at :212-214: 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()) Replacement (~20 lines, still fails without the line-42 fix because the fall-through reaches super().reducer_override and pickles the unpicklable handle): class _RecipePrepared: module = "hyperflare_recipes.components.synthetic"

    def __init__(self, scale):
        self.scale = scale
        self.compiled_handle = _UnpicklableHandle()     # reuse :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})
    assert type(restored) is _RecipePrepared
    assert restored.scale == 3
    assert isinstance(restored.compiled_handle, _Missing)

Drops, all verifiably redundant: the compile/serialize block (:288-296) duplicating :236-244; guard invalidation (: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); and the unrestored global mutation at :283 (candidate blocker only because it currently leaks; monkeypatch.setattr fixes it). Do NOT carry the shallow version of this finding ("test is low-value") — the test is valuable and discriminating; it is the shape that must shrink so the assertion can be added.

Candidate Nit 1 — one pass over the PR description (merged: all prose lenses)

Evidence paragraph reports no pass counts/skips and no negative control; the end-to-end claim names no command, core, or revision (and the "154 multimodal graphs" figure is not in the published body), so AGENTS.md:103-112 ("baseline or reference, configuration, result") is unmet; test_core_boundary.py is listed without saying what it establishes (it only AST-scans imports, per tests/preparation/test_core_boundary.py:28-36); section 7 poses the rebuild_manifest.py:365 question as merge logistics rather than a stated reason. One edit: add the pre-change failure as baseline (revert line 42, show the test failing), state counts, say what test_core_boundary establishes, and either state the reason :365 is out of scope or cross-reference SF2. Caveats paragraph can then be deleted.

Candidate Nit 2 — two small fidelity gaps in the fixture (low)

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). Both vanish if Sub1 is taken with pickle.PicklingError.

Dropped as noise (do not re-report)

#3 [high] CORRECTION — SF2 reachability (supersedes that paragraph in entry 2)

CORRECTION to entry 2 ("CANDIDATE BRIEF"), the SF2 paragraph. Entry 2 says the legacy weight_views path is covered by an in-repo caller whose "RuntimeCore export path needs no GPU". That is WRONG — I checked helios/tests/runtime_core_fixture.py:100-170 and it is CUDA-only (tensors built with device="cuda" at :131-139, cuda.cuFuncGetName/cuFuncGetParamInfo at :100-119, torch.cuda.CUDAGraph / capture_graph at :150-167).

Corrected statement to use:

Everything else in entries 1 and 2 stands as written.

#4 [high] CORRECTION — replace-test sketch in entry 2 is buggy (guard_tree_values)

HIGH — supersedes the code block in entry 2 under "Candidate Subtract / Simplify 1". The sketch I put in that brief, and the nearly identical sketches proposed by the subtractive lens and the simplicity lens, are BUGGY. Do not let the adjudicator adopt them verbatim.

Why: _GuardPickler.reducer_override builds state as state = {key: value if id(value) in self.guard_tree_values else _Missing('unguarded attribute') for key, value in vars(obj).items()} # aot.py:158-160 So EVERY attribute whose value is not itself in guard_tree_values becomes _Missing — including scale, a plain int. With guard_tree_values={id(prepared): prepared}, prepared.scale is NOT guarded, so restored.scale is a _Missing instance and assert restored.scale == 3 fails. The subtractive lens's "~19 lines, still pins the fix" sketch (assert restored.scale == 3) and the simplicity lens's ~12-line version (assert restored.scale == 3) both carry this defect. The existing test at tests/preparation/test_guard_code.py:118-124 gets it right — it puts the guarded value in the dict explicitly: guard_tree_values={id(tensor): tensor, id(guarded_scale): guarded_scale} and only asserts _Missing for the deliberately unguarded unguarded.

CORRECTED replacement test (~20 lines, CPU-only, still fails on main because the fall-through at aot.py:166 reaches super().reducer_override, whose default reduction pickles vars(obj) including the unpicklable handle):

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)

Key deltas vs. what I sent before: id(prepared.scale): prepared.scale added to guard_tree_values so the guarded attribute survives (this is the assertion that proves guessing-vs-stripping); _Missing already imported at test file line 14; monkeypatch.setitem alone sets module identity (no class mutation, no leaked global — the class-body __module__ at module scope is now the single source of truth and is NOT overwritten in the test body, unlike the PR's :283).

Residual risk to flag to the adjudicator: _roundtrip_guard bypasses the torch.compile/serialize pipeline, so it does not by itself prove type(compiled).serialize no longer raises. That is already proven by the sibling test at :232-249 for the pipeline shape; if maintainers want the recipe object inside a compiled graph, the fallback is to keep the PR's compile block and only add the missing _Missing assertion. Either path closes the B2 gap; the corrected sketch is preferred under the subtraction rule.

#6 [high] Research summary

Produced a deduplicated, code-grounded candidate brief for PR #574 in the scratchpad (entries 1–5), reduced from six lens reports to 2 blockers, 3 should-fix, 1 candidate-subtract and 2 nits, with exact file:line quotes opened and checked by me rather than relayed.

Structure. Entry 1 is the verified ground truth (diff, the predicate, both pickler call sites, rebuild_manifest.py, the test file, plus which lens claims I confirmed or refuted). Entry 2 is the brief itself, organised as requested. Entries 3 and 4 are corrections that supersede specific paragraphs of entry 2; entry 5 records provenance caveats.

What I found beyond merging. I opened every cited site, which changed the brief materially in four places. The production change is a genuine one-token widening with exactly two call sites and no format or ABI change, so the PR's central claim holds and hyperflare_recipes appears exactly once under ignition/. The real gap is that the new 53-line test never asserts the stripping it is named for, while the file's own idiom at :118-124 does. I refuted two upstream claims outright: the "custom __setstate__ breaks at load" hypothesis cannot occur because no state-setter is emitted (aot.py:165 is a 3-tuple returned unchanged), and the simplicity lens's "drop the module-prefix clause entirely" would put object.__new__ reduction onto third-party classes — the exact thing the allowlist prevents.

Two self-corrections the adjudicator needs. I had initially asserted the legacy weight_views path was CPU-covered; helios/tests/runtime_core_fixture.py:100-170 shows the only caller is CUDA-only and passes raw tensors that never reach the prefix clause, so entry 3 downgrades that finding from a proven weight-loss bug to a duplication/drift request. More importantly, entry 4 records that the replacement-test sketch I passed downstream — copied from both the subtractive and simplicity lenses — is buggy: reducer_override turns every attribute absent from guard_tree_values into _Missing, so assert restored.scale == 3 fails unless scale is added to the dict. I supplied the corrected version.

Noise filtered. No lens cited red CI-infra checks, so nothing to drop there; the only PR discussion was the automated case-file notice, with no injection attempt. Mechanical description notes are merged into a single nit. Two upstream "expand the tests" requests were folded into the subtraction item per the prefer-subtraction rule.

Residual judgment calls flagged, not resolved: whether to generalise the predicate versus documenting a stopgap; whether to adopt the subtraction (which dissolves the assertion blocker) or repair the test in place. I noted that the "test fails on main" claim is unrun lens consensus — neither the lenses nor I executed pytest — so the requested CPU run also settles that.

#7 [high] Report inputs — PR metadata, verbatim description, governing rule text

Identifier block for the report header (all from read_item 574):

VERBATIM PR description — quote from this, do not paraphrase:

Why

After model recipes moved from ignition. into the external hyperflare_recipes package, _uses_custom_object_state (ignition/preparation/forward_metadata.py) still only matched ('ignition.', 'b12x.'). Any non-nn.Module object under hyperflare_recipes.* holding an unpicklable compiled handle (e.g., Triton CompiledKernel) crashes aot_forward guard serialization with PicklingError.

What Changed

Benefit & Evidence

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.

Discord: woooflet

DESCRIPTION ACCURACY NOTES worth one line in the report:

VERBATIM policy lines the candidates rest on: AGENTS.md:188-193 —

#5 [medium] Provenance caveats — unrun claims behind B1 and the description nit

Two provenance caveats the adjudicator should weigh, neither of which needs more research:

  1. "The new test fails on main and passes with the fix" (correctness lens, "Verified positives") is a BEHAVIOURAL claim from three lenses, none of whom ran pytest — and neither did I. It is plausible (without 'hyperflare_recipes.' the object falls through aot.py:166 to super().reducer_override, whose default reduction pickles vars(obj) including _UnpicklableHandle, whose __reduce__ raises at tests/preparation/test_guard_code.py:253-254), but it is unrun. Candidate Blocker 1's requested pytest run settles it in one command and should be treated as the settlement, not a restatement of the caveat.

  2. The PR description's end-to-end evidence ("4-Spark TP4 Inkling 2 Small exports") is unverifiable from this repository: no hyperflare_recipes code exists here (search_code over hyperflare_recipes/ returns no matches, and test_core_boundary.py:40 asserts the package is absent). So no lens, nor I, could confirm that PreparedResidualMix-style objects actually reach the widened branch. This is a coverage-limits note, not a defect claim — keep it attached to the description nit, not to a blocker.