#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.
- ignition/preparation/forward_metadata.py:39-45 — quote:
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 — quote:
elif type(value).__module__.startswith(('b12x.', 'ignition.')) and hasattr(value, '__dict__'):Search confirms only these two sites (search_code 'ignition\.'→ only :42 and rebuild_manifest:365; note the tuple order is already inconsistent: ('ignition.','b12x.') vs ('b12x.','ignition.')). PR body itself discloses rebuild_manifest:365 as a "twin allowlist … intentionally left out". Concrete simplification: hoist one module-level constant (e.g. in forward_metadata.py or a small shared module)EXTERNAL_OBJECT_STATE_PREFIXES = ('ignition.', 'b12x.', 'hyperflare_recipes.')and use it at both sites — same line count as today, removes the divergence. No such constant exists yet (searched_MODULE_PREFIX|_OWNED|module_prefix→ no match).
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.
- Declared mechanisms that already exist:
ignition/preparation/source_identity.py:12-25(_EXTRA_ROOTSContextVar +source_rootscontextmanager), bound fromignition/cli/__init__.py:364-370(main(argv=None, *, recipes=(), prog="ignition", source_roots=())→with active_recipes(recipes), bind_source_roots(source_roots):);ignition/preparation/rebuild_manifest.py:41-61(declare_container_fields/weight_containerregister external container types by exact type key); AGENTS.md:382-396 ("external recipe repositories can pass their ownRecipetuples directly toignition.cli.main(...)"; "Coreignitionmust never importhyperflare_recipesor introduce a plugin discovery framework"). - If maintainers reject the literal, the smallest viable shape is one more item bound by
ignition.cli.main(e.g.object_state_prefixes=()feeding a ContextVar defaulted to('ignition.', 'b12x.')), consumed by both F1 sites — deletes the hardcoded name and fixes rebuild_manifest:365 for free. Frame as option, not blocker; core-boundary letter is respected today (string compare, no import).
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.
- New test tests/preparation/test_guard_code.py:287-302 repeats:
torch.compile(...backend=lambda g,i: GraphModuleSerializableCallable(g)...).aot_compile(((forward,), {}))→serialize→deserialize→ assert_close → guard_check True/False. 3 support classes (_UnpicklableHandle:252,_RecipeKernelOwner:257-265,_RecipeForward:268-274) = 24 lines to reach one assertion. - Minimal equivalent (fails pre-change with TypeError from
_UnpicklableHandle, passes post-change):
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.)
- If end-to-end coverage is deliberate, at minimum
_RecipeForward.value/applyare redundant (self.owner.apply(self.value)can beself.owner.scale * torch.ones(2), folding_RecipeKernelOwner.__call__in and droppingapplyand_RecipeForward's separate role).
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.
- The prefix allowlist is now duplicated in two places and the copies already disagree —
forward_metadata.py:39-45(('ignition.', 'b12x.', 'hyperflare_recipes.')) vsrebuild_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. - Hardcoding one external repo's package name in core goes against the repo's own declared-registration pattern (
source_roots/_EXTRA_ROOTSinsource_identity.py:12-25bound fromignition/cli/__init__.py:364-370;declare_container_fields/weight_containerinrebuild_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. - 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_guardhelper (:91-100); the whole regression collapses to four lines through that helper, and three support classes exist to reach one assertion. - 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 becausemonkeypatchonly restoressys.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:
- ignition/preparation/source_identity.py:17-25:
@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)
- ignition/cli/init.py:364-370 (
main(argv=None, *, recipes=(), prog="ignition", source_roots=())→with active_recipes(recipes), bind_source_roots(source_roots):). - ignition/preparation/rebuild_manifest.py:41-45 (
declare_container_fields(type_key, field_names, *, tuned=())) and :49-61 (weight_container→declare_container_fields(f'{cls.__module__}.{cls.__qualname__}', names, tuned=tuned)). - AGENTS.md:384-396: "external recipe repositories can pass their own
Recipetuples directly toignition.cli.main(...)" … "Coreignitionmust never importhyperflare_recipesor introduce a plugin discovery framework." Concrete alternative if maintainers object to the literal: one more kwarg onmain(e.g.object_state_prefixes=()) feeding a ContextVar defaulted to('ignition.', 'b12x.'), consumed by the S1 constant's two sites — removes the hardcoded name and repairs rebuild_manifest:365 in the same stroke. State as an option/decision for maintainers, NOT as a blocker: the boundary is respected literally (string comparison, no import — verified,hyperflare_recipesappears in core only at forward_metadata.py:42).
--- 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) ---
- Local
import typesat test_guard_code.py:278 matches the file's own existing pattern (:205, :233) — do not flag. - No formatting/naming nits;
_RecipeKernelOwner/_RecipeForwardnaming is clear. - The synthetic-module approach is correct and does not trip tests/preparation/test_core_boundary.py:39-58 (runtime
sys.modulesregistration, not an AST import). - No pure-correctness claims here; the
_ForwardPicklersecond-consumer question and the wrong167f22c8citation belong to the Correctness lens / dossier, not this one.