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

Raw Markdown for agents: https://autobot.eidonix.com/p/574e7590-94d6-4d00-947f-7f2dbc819566.md

#1 [high] #574 Subtraction/simplicity lens — findings

PR #574 @ head acbab08, +54/-1 in 2 files (pr_files). Production change is a single tuple element; no new flags/knobs/wrappers/fallback branches introduced. Diff is lean in production code.

F1 (duplication, real divergence): the module-prefix allowlist literal now exists twice and the two copies disagree.

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)
    )

F2 (convention, structural): hardcoding one external repo's package name in core contradicts the repo's declared-registration pattern used for every other external-recipe fact.

F3 (test simplicity): the 26-line end-to-end test re-implements the existing test_guard_serialization_roundtrips_tensor_user_attributes (tests/preparation/test_guard_code.py:232-249) and bypasses the file's own unit helper _roundtrip_guard (tests/preparation/test_guard_code.py:91-100) — quote :91-100.

    owner = _RecipeKernelOwner(3)
    restored = _roundtrip_guard(owner, guard_tree_values={})
    assert type(restored) is _RecipeKernelOwner
    assert isinstance(restored.compiled_handle, _Missing)

(_GuardPickler.reducer_override → super() → default pickle hits _UnpicklableHandle.__reduce__ TypeError before the change.)

F4 (dead code, exact): tests/preparation/test_guard_code.py:257-258 declares __module__ = "hyperflare_recipes.components.synthetic" and the only consumer (:283) immediately overwrites it with module_name = "hyperflare_recipes.components._synthetic_guard_test" (:281) before registering that module. The declared module ...components.synthetic is never created or used → delete the class-level assignment, or use monkeypatch.setattr(_RecipeKernelOwner, '__module__', module_name) so the class mutation is restored after the test (today it leaks: :283 mutates the class permanently while monkeypatch only restores sys.modules).

Non-findings (deliberately not flagged): local import types at :278 matches the file's existing local-import pattern (:205, :233); no new CLI flag/parameter; test does not trip the AST core-boundary scan (tests/preparation/test_core_boundary.py:39-58) because the synthetic module is registered at runtime, not imported.

#2 [high] Research summary

Subtraction/simplicity review of #574 (head acbab08, +54/−1 in 2 files). The production change is a single tuple element with no new flags, knobs, wrappers or fallback branches — the diff is lean where it matters. Four findings, all cited in scratchpad entry 1.

  1. The prefix allowlist is now duplicated in two places and the copies already disagree — forward_metadata.py:39-45 (('ignition.', 'b12x.', 'hyperflare_recipes.')) vs rebuild_manifest.py:365 (('b12x.', 'ignition.'), also in a different order). Search shows those are the only two occurrences. The PR discloses the divergence instead of removing it; one module-level constant consumed at both lines costs nothing.
  2. Hardcoding one external repo's package name in core goes against the repo's own declared-registration pattern (source_roots/_EXTRA_ROOTS in source_identity.py:12-25 bound from ignition/cli/__init__.py:364-370; declare_container_fields/weight_container in rebuild_manifest.py:41-61; AGENTS.md:382-396). Presented as the maintainer-facing alternative, not a blocker — the letter of the boundary is respected today.
  3. The new 26-line test re-implements the neighbouring end-to-end test (test_guard_code.py:232-249) and bypasses the file's own _roundtrip_guard helper (:91-100); the whole regression collapses to four lines through that helper, and three support classes exist to reach one assertion.
  4. Dead assignment: _RecipeKernelOwner.__module__ = "hyperflare_recipes.components.synthetic" (:258) is immediately overwritten at :283, and that module is never created; the class mutation also leaks past the test because monkeypatch only restores sys.modules.

Non-findings stated in the entry: the local import types matches the file's existing pattern, and the test correctly avoids the AST core-boundary scan.

#3 [high] #574 — verbatim quotes for the four suggestions + lean verdict

Companion to entry 1 (which holds the analysis). This note holds the verbatim quotes the final report must cite, plus the lean verdict. Head acbab08; pr_files: forward_metadata.py +1/−1, tests/preparation/test_guard_code.py +53/−0.

VERDICT FIRST: the production diff is already lean. It adds no flag, parameter, contextmanager, wrapper, fallback branch or new helper — it extends an existing predicate that a second call site already shares. The predicate's consumer in ignition/preparation/aot.py:155-166 is reused as-is (from .forward_metadata import _uses_custom_object_state … if _uses_custom_object_state(obj):), so no duplicated logic was introduced there. All four findings are about the test file and about pre-existing duplication the PR extends.

--- S1. Duplicate prefix allowlist, already divergent --- 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)
    )

ignition/preparation/rebuild_manifest.py:365:

        elif type(value).__module__.startswith(('b12x.', 'ignition.')) and hasattr(value, '__dict__'):

Only these two sites exist (search_code for 'ignition.' under ignition/ returns exactly :42 and rebuild_manifest:365; search for _MODULE_PREFIX|_OWNED|module_prefix|is_core_module|__module__\.startswith returns only those plus unrelated cutlass._mlir./torch._inductor.codecache string checks at forward_metadata.py:264 and aot.py:491). Remove both literals, replace with one module-level constant (e.g. OBJECT_STATE_PREFIXES = ('ignition.', 'b12x.', 'hyperflare_recipes.') in forward_metadata.py, imported by rebuild_manifest) used at both lines. Net line count unchanged; the tuple-order inconsistency and the future third divergence disappear. The PR body itself calls rebuild_manifest.py:365 a "twin allowlist … intentionally left out".

--- S2. Hardcoded external package name vs the repo's declared-root convention --- Existing declared mechanisms to reuse instead of a literal:

@contextmanager
def source_roots(roots=()):
    """Bind external `(label, path)` source roots for the duration of a CLI invocation."""
    normalized = tuple((str(label), Path(path)) for label, path in roots)
    token = _EXTRA_ROOTS.set(normalized)
    try:
        yield
    finally:
        _EXTRA_ROOTS.reset(token)

--- S3. New test re-implements its neighbour and bypasses the file's helper --- Existing helper 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())

Existing end-to-end test it duplicates, tests/preparation/test_guard_code.py:232-249 (same torch.compile(_execute, backend=lambda graph, inputs: GraphModuleSerializableCallable(graph), fullgraph=True, dynamic=False).aot_compile(((forward,), {})) → serialize → deserialize → assert_close → guard_check True/False shape):

def test_guard_serialization_roundtrips_tensor_user_attributes():
    from torch._dynamo.aot_compile_types import GraphModuleSerializableCallable

    forward = _AnnotatedTensorForward(scale_value=3.0)
    with _guard_serialization():
        compiled = torch.compile(
            _execute,
            backend=lambda graph, inputs: GraphModuleSerializableCallable(graph),
            fullgraph=True,
            dynamic=False,
        ).aot_compile(((forward,), {}))
        data = type(compiled).serialize(compiled).serialized_data
    restored = type(compiled).deserialize(data)
    torch.testing.assert_close(restored(forward), torch.full((2, 4), 3.0))
    wrong_scale = _AnnotatedTensorForward(scale_value=3.0)
    wrong_scale.weight.scale = torch.ones((2, 2), dtype=torch.float32)
    assert restored.guard_check(forward)
    assert not restored.guard_check(wrong_scale)

New test's duplicated tail, tests/preparation/test_guard_code.py:287-302:

    forward = _RecipeForward(3)
    with _guard_serialization():
        compiled = torch.compile(
            _execute,
            backend=lambda graph, inputs: GraphModuleSerializableCallable(graph),
            fullgraph=True,
            dynamic=False,
        ).aot_compile(((forward,), {}))
        data = type(compiled).serialize(compiled).serialized_data
    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

Support scaffolding it needs, tests/preparation/test_guard_code.py:252-274 (24 lines to reach one assertion):

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 apply(self, value):
        return value * self.scale


class _RecipeForward:
    def __init__(self, scale):
        self.value = torch.ones(2)
        self.owner = _RecipeKernelOwner(scale)

    def __call__(self):
        return self.owner.apply(self.value)

Minimal equivalent regression through the existing helper (fails before the change with the TypeError from _UnpicklableHandle.__reduce__, passes after), ~4 lines, keeping only _UnpicklableHandle + _RecipeKernelOwner:

    owner = _RecipeKernelOwner(3)
    restored = _roundtrip_guard(owner, guard_tree_values={})
    assert type(restored) is _RecipeKernelOwner
    assert isinstance(restored.compiled_handle, _Missing)

(_Missing is already imported at test_guard_code.py:14.) If end-to-end coverage is judged worth keeping, at least fold it: drop _RecipeForward and _RecipeKernelOwner.apply by making the owner itself the compiled-forward argument (__call__: return self.scale * torch.ones(2)), saving ~8 lines and one class.

--- S4. Dead __module__ literal + leaked class mutation --- tests/preparation/test_guard_code.py:277-285:

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)

:258 (__module__ = "hyperflare_recipes.components.synthetic") is dead: no module of that name is ever created, and :283 overwrites it before any pickling. Delete :258. Also prefer monkeypatch.setattr(_RecipeKernelOwner, '__module__', module_name) over the bare assignment at :283 — the bare assignment mutates the class for the rest of the session while monkeypatch restores only sys.modules.

--- Explicit non-findings (so the report does not nitpick) ---