Subtraction, Simplicity & Conventions review — PR #574
Head acbab08; diff +54/−1 in 2 files (pr_files): ignition/preparation/forward_metadata.py +1/−1, tests/preparation/test_guard_code.py +53/−0.
Key findings
- The production diff is already lean. It adds no flag, parameter, config knob, wrapper, fallback branch or new helper. It extends an existing predicate that a second consumer already imports (
aot.py:155-166uses_uses_custom_object_stateas-is), so no logic was duplicated there. Nothing to delete in the production file. All findings below are about the test file and about pre-existing duplication the PR extends rather than removes. - S1 (highest value): the module-prefix allowlist now exists twice and the two copies already disagree —
forward_metadata.py:42vsrebuild_manifest.py:365. One module-level constant used at both sites costs zero net lines and removes the divergence the PR body merely discloses. - S2: hardcoding one external repo's package name in core runs against the repo's own declared-registration convention (
source_roots/_EXTRA_ROOTS,declare_container_fields). Presented as a maintainer decision, not a blocker — the letter of the core boundary is respected (string compare, no import). - S3: the new 26-line end-to-end test re-implements its neighbour
test_guard_serialization_roundtrips_tensor_user_attributesand bypasses the file's own_roundtrip_guardhelper, using three support classes to reach one assertion. The regression itself is ~4 lines through the existing helper. - S4: dead assignment + leaked class mutation —
_RecipeKernelOwner.__module__ = "hyperflare_recipes.components.synthetic"at:258is overwritten at:283before any pickling and that module is never created; the bare assignment at:283mutates the class for the rest of the session whilemonkeypatchrestores onlysys.modules.
No correctness bugs are claimed here (Correctness lens owns those); where a workaround should be deleted rather than patched, it is marked so.
S1 — Duplicated prefix allowlist, already divergent (high value)
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__'):
Searching for 'ignition.' under ignition/ returns exactly these two occurrences; no shared constant exists (_MODULE_PREFIX|_OWNED|module_prefix|is_core_module match nothing). The two literals already diverge twice over: different membership (the new one has hyperflare_recipes.) and different order (('b12x.', 'ignition.') vs ('ignition.', 'b12x.')), which signals they were edited independently and will keep drifting.
Concrete simplification: declare one module-level constant in forward_metadata.py, e.g.
OBJECT_STATE_PREFIXES = ('ignition.', 'b12x.', 'hyperflare_recipes.')
use it at forward_metadata.py:42, and import it in rebuild_manifest.py in place of the literal at :365. Net line count is unchanged; the order inconsistency and the third divergence disappear. The PR body itself calls rebuild_manifest.py:365 a "twin allowlist … intentionally left out", so the divergence is knowingly introduced — hoisting converts a disclosure into a fix for the same edit cost.
Note: this is a maintainability/duplication finding, not a bug report. Whether rebuild_manifest.py:365 should accept hyperflare_recipes. is a behavioural question for the Correctness lens; S1 is only about the literal existing twice.
S2 — Hardcoded external package name vs the repo's declared-root convention (medium value, decision for maintainers)
The repo already carries a declared-registration mechanism for every other external-recipe fact, so a bare 'hyperflare_recipes.' literal in core is the structurally inconsistent choice:
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)
- Bound from the public entry point,
ignition/cli/__init__.py:364-370:def 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(type_key, field_names, *, tuned=())andweight_containerregistering external container types by exact 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."
Concrete alternative if maintainers object to the literal: one more keyword on main (e.g. object_state_prefixes=()) feeding a ContextVar defaulted to ('ignition.', 'b12x.'), consumed by the S1 constant's two sites. That removes the hardcoded external name and repairs rebuild_manifest.py:365 in the same stroke.
Not a blocker: the boundary is satisfied literally today — hyperflare_recipes appears in core only as a string at forward_metadata.py:42, and nothing is imported. Frame this as the one design decision the PR leaves open, which its own body already raises.
S3 — The new test duplicates its neighbour and bypasses the file's own helper (high value)
The file already has the helper the new test needs, 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())
It is used 11 times in this file (:118, 126, 150, 156, 162, 169, 194-196, 209, 217) and not once by the new test.
The new tail, tests/preparation/test_guard_code.py:287-302, is a near-verbatim copy of the neighbouring test at :232-249 (torch.compile(_execute, backend=lambda graph, inputs: GraphModuleSerializableCallable(graph), fullgraph=True, dynamic=False).aot_compile(((forward,), {})) → serialize → deserialize → assert_close → guard_check True/False):
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, tests/preparation/test_guard_code.py:252-274 — 24 lines and three classes 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)
Concrete minimal equivalent through the existing helper (fails before the change at _UnpicklableHandle.__reduce__'s TypeError via super().reducer_override at aot.py:166, passes after), keeping only _UnpicklableHandle and _RecipeKernelOwner (_Missing is already imported at :14):
owner = _RecipeKernelOwner(3)
restored = _roundtrip_guard(owner, guard_tree_values={})
assert type(restored) is _RecipeKernelOwner
assert isinstance(restored.compiled_handle, _Missing)
That deletes _RecipeForward, _RecipeKernelOwner.apply, and the duplicated compile/serialize block: ~40 of the 53 added lines.
If end-to-end coverage is judged worth keeping, at least fold the scaffolding: drop _RecipeForward and _RecipeKernelOwner.apply by making the owner itself the compiled-forward argument (def __call__(self): return self.scale * torch.ones(2)), saving ~8 lines and one class with no loss of coverage.
S4 — Dead __module__ literal and a leaked class mutation (small, exact)
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)
- Dead:
:258(__module__ = "hyperflare_recipes.components.synthetic") is overwritten at:283before any pickling, and no module namedhyperflare_recipes.components.syntheticis ever created or registered. Delete line 258. - Leaked mutation:
:283assigns to the class directly, so_RecipeKernelOwner.__module__stayshyperflare_recipes.components._synthetic_guard_testfor the rest of the session whilemonkeypatchrestores only thesys.modulesentry. Replace:283withmonkeypatch.setattr(_RecipeKernelOwner, '__module__', module_name)— same line count, self-restoring, consistent with themonkeypatchalready taken as the fixture argument.
Non-findings (deliberately not flagged)
- The production change adds no knob or branch.
forward_metadata.py:42is a tuple element; there is no new flag, parameter, ContextVar, wrapper function or fallback. The predicate's other consumer,aot.py:155-166, imports and reuses it unchanged, so the PR introduced no duplicated logic there. - Local
import typesattest_guard_code.py:278matches this file's own established pattern (:205,:233) — a repo convention, not a violation. - The synthetic-module technique is sound and idiomatic and does not trip the AST-based core-boundary scan (
tests/preparation/test_core_boundary.py:39-58) because registration happens at runtime viasys.modules, not via an import statement. - No formatting, naming or docstring nits;
_RecipeKernelOwner/_RecipeForwardnames are clear, and the test's True/False/True guard sequence at:298-302is a legitimate assertion, not padding (it is the duplication around it that S3 targets). - Out of scope for this lens: the
_ForwardPicklersecond-consumer question, the undeclaredrebuild_manifest.py:365behaviour change, the misattributed167f22c8citation in the body, and the stale Caveats paragraph belong to Correctness/Process, not Subtraction. They are recorded in the dossier.
Open questions
- Do maintainers want a
hyperflare_recipes.prefix in core at all, or a caller-declared root (S2) that would also settlerebuild_manifest.py:365? This is the one decision the diff defers. - Is the end-to-end compile path in the new test deliberate (i.e. reviewers specifically want proof the AOT export completes for a recipe-owned object), or is the pickler-level assertion sufficient? The answer decides whether S3 reduces the test to 4 lines or merely folds its scaffolding by ~8.
- If
rebuild_manifest.py:365is meant to gain the prefix too, S1's constant should land in this PR while the context is fresh; if it is meant to stay narrower, a comment at:365should say why the two allowlists differ.
What could not be found
- No shared module-prefix constant exists anywhere in the repo to reuse today; S1 proposes creating one rather than pointing at an existing abstraction.
- No evidence in the diff or the conversation of any new CLI surface, so no fallback/flag removal opportunity beyond those listed.