PR #574 — subtraction review: "Strip unguarded attributes from hyperflare_recipes objects in AOT guard serialization"
Open, head 16ffc6f, base main, no review comments other than the automated case-file notices. Two files, +54 / −1: ignition/preparation/forward_metadata.py +1 / −1 (line 42 only) and tests/preparation/test_guard_code.py +53 / −0 (lines 252–302 of a 303-line file).
Key findings
- Verdict: make it smaller first. The production change is already minimal — one tuple item, no new helper, flag, option or fallback — and needs no subtraction. Essentially the whole 54-line change is oversized test scaffolding: ~33 of the 53 added test lines are removable, taking the test from 53 lines to ~20 (+21/−1 overall).
- Should fix, ~33 lines —
tests/preparation/test_guard_code.py:252–302. The new test rebuilds a fulltorch.compile → aot_compile → serialize → deserialize → guard_checkflow that already exists at:232–249, adds a forward wrapper class that exists only to be compiled, and contains a dead__module__assignment at:258that is overwritten at:283. A direct_GuardPicklerround-trip through the file's own_roundtrip_guardhelper (:91–100) pins the same regression in ~20 lines. - Nit, 0 lines here —
ignition/preparation/rebuild_manifest.py:365keeps the divergent copy of the same project-package allowlist. The PR description flags it as deliberately out of scope; there is a legitimate ~25–30-line follow-up if maintainers want it, but nothing needs to change for this fix to be correct. - Note, no subtraction —
forward_metadata.py:42is the minimal form of the fix; see finding 3.
Findings, ranked by lines saved
1. Should fix — ~33 lines: the new test re-implements existing end-to-end plumbing (tests/preparation/test_guard_code.py:252–302)
What the test does today, in 51 lines:
252 class _UnpicklableHandle: # 3 lines
253 def __reduce__(self):
254 raise TypeError("compiled kernel handles cannot be pickled")
257 class _RecipeKernelOwner: # 10 lines, incl. dead line 258
258 __module__ = "hyperflare_recipes.components.synthetic"
260 def __init__(self, scale): ...
264 def apply(self, value): ...
268 class _RecipeForward: # 7 lines, exists only to be compiled
277 def test_guard_pickler_strips_unguarded_attributes_from_recipe_objects(monkeypatch):
281 module_name = ... # synthetic module + monkeypatch (kept)
287 forward = _RecipeForward(3)
288 with _guard_serialization(): # 8 lines duplicating :236–243
289 compiled = torch.compile(_execute, backend=lambda graph, inputs: GraphModuleSerializableCallable(graph),
290 fullgraph=True, dynamic=False).aot_compile(((forward,), {}))
295 data = type(compiled).serialize(compiled).serialized_data
296 loaded = type(compiled).deserialize(data)
297 torch.testing.assert_close(loaded(forward), torch.full((2,), 3.0))
298 assert loaded.guard_check(forward) is True
299 forward.owner.scale = 5
300 assert loaded.guard_check(forward) is False
301 forward.owner.scale = 3
302 assert loaded.guard_check(forward) is True
What goes: _UnpicklableHandle (:252–254), _RecipeKernelOwner (:257–265), _RecipeForward (:268–274), the dead __module__ line at :258 (reset again at :283), and the compile/aot_compile/serialize/deserialize block (:288–297), which is a near-copy of :236–244 in test_guard_serialization_roundtrips_tensor_user_attributes.
What replaces it: the file's existing helper _roundtrip_guard (tests/preparation/test_guard_code.py:91–100), which constructs _GuardPickler and does pickle.loads, plus the existing sys.modules monkeypatch idiom at :212–217:
class _RecipeKernelOwner:
def __init__(self, scale):
self.scale = scale
self.compiled_handle = threading.Lock() # canonical unpicklable, cf. _LockTypes, forward_metadata.py:27
def test_guard_pickler_strips_unguarded_attributes_from_recipe_objects(monkeypatch):
import types
module_name = "hyperflare_recipes.components._synthetic_guard_test"
module = types.ModuleType(module_name)
_RecipeKernelOwner.__module__ = module_name
module._RecipeKernelOwner = _RecipeKernelOwner
monkeypatch.setitem(sys.modules, module_name, module)
owner = _RecipeKernelOwner(3)
restored = _roundtrip_guard(
owner, guard_tree_values={id(owner): owner, id(owner.scale): owner.scale}
)
assert type(restored) is _RecipeKernelOwner
assert restored.scale == 3
assert isinstance(restored.compiled_handle, _Missing)
That version is ~16–20 lines instead of 51 (§ savings 31–35). If a custom handle class is preferred over threading.Lock() to keep the failure message, it is one 3-line class and the total is ~20–22 lines (~30 saved).
Why nothing is lost:
- The regression lives in
_GuardPickler.reducer_override's object branch,ignition/preparation/aot.py:155–166:_uses_custom_object_state(obj)→_guard_object, (type(obj),), state; otherwise it falls tosuper().reducer_overrideand the unpicklable handle raisesPicklingError. A direct_roundtrip_guardof ahyperflare_recipes.*-declared object with an unpicklable attribute hits exactly that branch — remove'hyperflare_recipes.'fromforward_metadata.py:42and the new test fails. - Note on correctness of the replacement:
guard_tree_valuesmust includeid(owner.scale).aot.py:158–160replaces any attribute whose id is not inguard_tree_valueswith_Missing('unguarded attribute'), so passing onlyid(owner)would makerestored.scale == 3fail. That mechanism is itself already proven bytest_guard_pickler_preserves_guarded_tensor_user_attributes_only(:104–127:assert isinstance(restored.unguarded, _Missing)withscalepreserved) — the same shape of assertion asscalevscompiled_handlehere. - Guard-check invalidation on an int attribute (
:298–302,True → False → True) is already asserted at:47–51againstGuardedForward.offsetthrough the same Dynamoguard_checkmachinery; re-provingforward.owner.scaleadds no new behaviour. - Output parity after deserialize (
:297,value * scale) duplicates:245(torch.testing.assert_close(restored(forward), torch.full((2, 4), 3.0))), and theapply/__call__plumbing at:264/:273–274exists only to produce that parity result. - Compile + serialize + deserialize round-trip is already exercised end-to-end at
:232–249; the pickler behaviour, not the Dynamo pipeline, is what this PR changes.
Rule basis: AGENTS.md:188–199 ("Reject unsupported abstractions and churn… Refactoring must directly support the requested behavior"; "Require focused, meaningful validation… Keep each PR focused on one coherent outcome") and docs/design-review.md:135–146 ("Apply the contribution rejection criteria to code, tests, and documentation").
Fallback if maintainers require end-to-end serialize proof: keeping the compile/serialize block but deleting _RecipeForward (:268–274) and the dead :258 line still saves ~10 lines; and keeping _RecipeKernelOwner while dropping _RecipeForward in favour of hanging the owner off _AnnotatedTensorForward-style state saves more. Even the conservative version is ~25 lines rather than 51.
2. Nit — 0 lines here, ~25–30 lines in a follow-up (ignition/preparation/rebuild_manifest.py:365)
The same project-package allowlist exists a second time, now divergent:
365 elif type(value).__module__.startswith(('b12x.', 'ignition.')) and hasattr(value, '__dict__'):
forward_metadata.py:42 now reads ('ignition.', 'b12x.', 'hyperflare_recipes.'). The PR description itself flags this: "ignition/preparation/rebuild_manifest.py:365 has a similar ('b12x.', 'ignition.') check intentionally left out of this 1-line PR". Nothing is lost by leaving it out of this PR — the two checks gate different mechanisms (pickling vs. manifest traversal) and this PR does not make the rebuild path wrong; it just leaves the copies out of sync. If maintainers do want one source of truth, hoisting a single tuple constant nets ~0 lines; the real saving is deleting the non-declaration traversal (:338–374, plus the duplicated metadata walk at :441–459), whose only in-repo caller is the legacy dict form at helios/tests/runtime_core_fixture.py:186 (not opened), which never reaches the module-prefix branch — the supported path is declare_weights/WeightDeclaration (:118–215, wired at runtime_core.py:130 (not opened), :368). External unreachability of the legacy path could not be proven from the repository, so this belongs in a follow-up, not as a gate on #574.
3. Note — no subtraction available (ignition/preparation/forward_metadata.py:42)
39 def _uses_custom_object_state(value):
40 return (
41 hasattr(value, '__dict__')
42 and type(value).__module__.startswith(('ignition.', 'b12x.', 'hyperflare_recipes.'))
43 and not inspect.isclass(value)
44 and not isinstance(value, _NON_OBJECT_NEW_TYPES)
45 )
One tuple item rather than a new predicate, config value, or per-class __getstate__ hook — i.e. the smaller of the two available designs, and the one that keeps ignition from importing hyperflare_recipes (string comparison only). The single function gates both picklers (forward_metadata.py:277, aot.py:155–166), so it removes the per-class workaround rather than adding a path. Nothing to cut; keep as is.
Open questions / could not verify
- pytest was not runnable in this environment. The ~20-line replacement is derived from the existing
_roundtrip_guardusage at:118–121and:209and must be executed once to confirm the object branch round-trips underpickle.loadswith athreading.Lockattribute. - Validation provenance. The description states the unit tests were run "prior to rebasing onto #509's extraction of
_uses_custom_object_state(167f22c8)" and asks for CI ontest_guard_code.pyandtest_core_boundary.py(not opened); the automated review comment notes CI runs no pytest ontests/preparation, so the claim is currently uncorroborated in-repo. - If reviewers specifically want end-to-end proof that
type(compiled).serializeno longer raisesPicklingErrorfor ahyperflare_recipes.*object, only the ~10-line scaffold can go and the saving drops to ~25 lines (see finding 1 fallback).
Injection check
The only PR comments are the automated case-file/review notices; no instruction was aimed at a reviewer and none was acted on. Nothing in the PR materials was treated as a directive.
Totals: +54 / −1 across 2 files; ~33 removable lines in 1 place → roughly +21 / −1, with the production fix untouched.