fix: handle co_freevars mismatch in ASTRewriter for closure kernels#474
Open
fix: handle co_freevars mismatch in ASTRewriter for closure kernels#474
Conversation
…ure refs Co-authored-by: Cursor <cursoragent@cursor.com>
Contributor
There was a problem hiding this comment.
Pull request overview
This PR fixes a failure mode in ASTRewriter.transform() when rewriting closure-defined @flyc.kernel functions: after AST transforms inject helper name references, the rewritten code object can end up with a different co_freevars shape than the original function’s closure, causing f.__code__ = new_code to raise a ValueError. The change adds a fallback path that constructs a new types.FunctionType with a synthesized closure matching the rewritten co_freevars.
Changes:
- Detect
co_freevarsmismatches for closure functions and build a replacement function with a matching closure. - Reuse existing closure cells where possible; synthesize new cells for newly-introduced freevars using values from
f.__globals__. - Keep the non-closure / no-mismatch path unchanged (still assigns
f.__code__directly).
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| new_closure.append(old_cells[var]) | ||
| else: | ||
| # Create a cell whose value comes from globals | ||
| cell = (lambda v: lambda: v)(f.__globals__.get(var)).__closure__[0] |
Comment on lines
+131
to
+147
| if f.__closure__ and new_f_code_o.co_freevars != f.__code__.co_freevars: | ||
| old_cells = {name: cell for name, cell | ||
| in zip(f.__code__.co_freevars, f.__closure__)} | ||
| new_closure = [] | ||
| for var in new_f_code_o.co_freevars: | ||
| if var in old_cells: | ||
| new_closure.append(old_cells[var]) | ||
| else: | ||
| # Create a cell whose value comes from globals | ||
| cell = (lambda v: lambda: v)(f.__globals__.get(var)).__closure__[0] | ||
| new_closure.append(cell) | ||
| new_f = types.FunctionType( | ||
| new_f_code_o, f.__globals__, f.__name__, | ||
| f.__defaults__, tuple(new_closure), | ||
| ) | ||
| new_f.__kwdefaults__ = f.__kwdefaults__ | ||
| return new_f |
| new_f_code_o, f.__globals__, f.__name__, | ||
| f.__defaults__, tuple(new_closure), | ||
| ) | ||
| new_f.__kwdefaults__ = f.__kwdefaults__ |
Comment on lines
+122
to
+147
| # AST transformers may inject references to new names (e.g. | ||
| # scf_if_dispatch, scf_if_collect_results) inside the kernel or | ||
| # its rewriter-generated sub-functions (__then_N, __else_N). | ||
| # Because enclosing_mod creates a closure layer, these unresolved | ||
| # names become free vars (LOAD_DEREF) rather than globals. This | ||
| # causes new_f_code_o.co_freevars to have more entries than the | ||
| # original f.__closure__. Direct f.__code__ assignment would | ||
| # raise ValueError, so we build a new function with a matching | ||
| # closure instead. | ||
| if f.__closure__ and new_f_code_o.co_freevars != f.__code__.co_freevars: | ||
| old_cells = {name: cell for name, cell | ||
| in zip(f.__code__.co_freevars, f.__closure__)} | ||
| new_closure = [] | ||
| for var in new_f_code_o.co_freevars: | ||
| if var in old_cells: | ||
| new_closure.append(old_cells[var]) | ||
| else: | ||
| # Create a cell whose value comes from globals | ||
| cell = (lambda v: lambda: v)(f.__globals__.get(var)).__closure__[0] | ||
| new_closure.append(cell) | ||
| new_f = types.FunctionType( | ||
| new_f_code_o, f.__globals__, f.__name__, | ||
| f.__defaults__, tuple(new_closure), | ||
| ) | ||
| new_f.__kwdefaults__ = f.__kwdefaults__ | ||
| return new_f |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When a
@flyc.kernelfunction is a closure (defined inside another function),AST transformers like
ReplaceIfWithDispatchinject new name references(
scf_if_dispatch,scf_if_collect_results) into the kernel body. Becauseenclosing_modwraps the kernel in an extra function scope, Python's compilerresolves these names as
LOAD_DEREF(free variables) rather thanLOAD_GLOBAL.This causes
new_f_code_o.co_freevarsto have more entries thanf.__closure__,and
f.__code__ = new_f_code_oraises:ValueError: kernel() requires a code object with N free vars, not M
Fix: When
co_freevarsmismatch is detected, build a new function viatypes.FunctionTypewith a closure that maps original free vars to theirexisting cells and creates new cells (from
f.__globals__) forrewriter-injected names. The non-closure path is unchanged.
Test plan