Skip to content

fix(eager): preserve parent state read by a deferred aliased import - #3

Closed
AlpriElse wants to merge 6 commits into
masterfrom
mirror/eager-deferred-import-parent-state
Closed

AlpriElse wants to merge 6 commits into
masterfrom
mirror/eager-deferred-import-parent-state

Conversation

@AlpriElse

@AlpriElse AlpriElse commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Touches the same code as HubSpot#1369, but fixes a different problem.

Context

EagerImportTag handles {% import 'lib' as x %} in eager execution mode.

When the import is inside a deferred block, such as {% if deferred %}, and lib defines a macro, the import can't be inlined. It's written back out as a raw {% import %} tag, which runs again when the output is fully rendered later.

Problem

When the import was left as a raw tag, the parent template's state that lib reads, such as earlier set tags and macros defined in the parent, wasn't kept in the eager output.

On the second render pass, lib saw those as undefined.

EagerImportTag throws away the child's render in this case and calls AliasedEagerImportingStrategy.handleDeferredTemplateFile. That method records only the path expression and the alias. Nothing recorded which parent variables the child reads, so they were never written out in front of the import. include and from ... import aren't affected, because they inline the child's render instead of running it again.

Broken Examples

{#
  lib:
    {% macro mm(p) %}[]{% endmacro %}
    {% set v = x + 1 %}
#}
{% set x = 5 %}{% if deferred %}{% import 'lib' as lib %}{{ lib.v }}{% endif %}
{#
  evaluates to: 1  (x is undefined on the second pass, and undefined + 1 = 1)
  expected:     6
#}

{#
  lib:
    {% macro mm(p) %}[]{% endmacro %}
    {% set v = m(0) %}
#}
{% macro m(p) %}[{{ p }}]{% endmacro %}{% if deferred %}{% import 'lib' as lib %}{{ lib.v }}{% endif %}
{#
  fails with:   "Could not resolve function 'm'"
  expected:     [0]
#}

What this PR Does

When the import of a macro-defining template is deferred, EagerImportTag now collects the candidate names (variables and macros) that the imported template's source references. When it returns the raw import, it writes the parent's variables and macros among those names in front of it, using EagerReconstructionUtils.hydrateReconstructionFromContextBeforeDeferring and a DeferredToken. EagerPrintTag and EagerForTag already use this pattern. Eager output for the first example:

{% set x = 5 %}{% if deferred %}{% set current_path = '' %}{% import 'lib' as lib %}{{ lib.v }}{% endif %}

Only EagerImportTag changes; the importing strategies and shared eager utilities don't. No existing test expectations change.

Tests

  • New in EagerImportTagTest. All three fail on master and pass with this change:
    • itPreservesParentVariableReadByDeferredImportWithMacro (fixture macro-and-set-reading-parent-var.jinja): a parent variable.
    • itPreservesParentMacroCalledByDeferredImportWithMacro (fixture macro-and-set-calling-parent-macro.jinja): a parent macro.
    • itPreservesParentCallerMacroCalledByDeferredImportWithMacro (fixture macro-and-set-calling-parent-caller-macro.jinja): a parent macro that uses caller(), called with {% call %}. Rebuilding it registers a deferred placeholder caller, as EagerCallTag does, so {{ caller() }} is kept.
  • The second pass runs in a fresh default-mode interpreter with the eager pass's config, so nothing from the eager pass leaks in.
  • The eager, import, call and macro test classes (Eager*Test, NonRevertingEagerTest, *Import*Test, DeferredTest, *Call*Test, *Macro*Test) all pass (834 tests). The full mvn verify passes (2252 tests).
  • This branch merges cleanly with fix(eager): keep nested import alias paths consistent with flattened parent imports HubSpot/jinjava#1369, which also changes aliased imports. With both changes, the same test classes pass (836 tests).

Results

The same templates as the Broken Examples above:

{# Example 1 #}
{% set x = 5 %}{% if deferred %}{% import 'lib' as lib %}{{ lib.v }}{% endif %}

{# Example 2 #}
{% macro m(p) %}[{{ p }}]{% endmacro %}{% if deferred %}{% import 'lib' as lib %}{{ lib.v }}{% endif %}
Example Before After
1 1 6
2 FATAL: Could not resolve function 'm' [0]

🤖 Generated with Claude Code

AlpriElse and others added 6 commits November 24, 2026 00:03
When an aliased import inside a deferred block (or one whose child has
deferred nodes) is left as a raw import tag for the next pass, the
parent's variables and macros that the imported template reads were not
reconstructed, so the second pass saw them as undefined. Collect the
words the imported template uses and reconstruct/defer them in front of
the deferred import tag, as other deferred tags do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…edImport

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The second pass used jinjava.newInterpreter(), whose config has the test
base's legacy overrides, while the eager pass used its own. Build both
from one config method that only differs in execution mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…erred import

When an aliased import of a macro-defining template is deferred, the parent
macros the imported template reads are reconstructed in front of it. A
parent macro that uses caller(), called by the imported template with
{% call %}, failed to reconstruct: caller() couldn't be resolved, which is
a FATAL error, and the rebuilt macro lost its {{ caller() }}.

Like EagerCallTag, register a deferred placeholder caller macro in a
temporary scope while reconstructing, so caller() stays in the macro.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment on lines +783 to +794
public void itPreservesParentCallerMacroCalledByDeferredImportWithMacro() {
setupResourceLocator();
String firstPassResult = interpreter.render(
"{% macro k(p) %}<{{ p }}:{{ caller() }}>{% endmacro %}{% if deferred %}" +
"{% import 'macro-and-set-calling-parent-caller-macro.jinja' as lib %}{{ lib.v }}" +
"{% endif %}"
);
assertThat(interpreter.getErrors()).isEmpty();
RenderResult secondPass = renderSecondPassInDefaultMode(firstPassResult);
assertThat(secondPass.getErrors()).isEmpty();
assertThat(secondPass.getOutput()).isEqualTo("<0:x>");
}

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

initial fix caused a regression for this edge case

Build Eager pass Second pass
master no errors FATAL Could not resolve function 'k'
With initial fix FATAL Could not resolve function 'caller' no errors, but <0:> instead of <0:x>
With the follow-up commit caller() fix (4c86aedc) no errors <0:x> (correct)

Honestly, haven't touched this codebase in a looong time, so I don't remember the semantics and consequences around messing with the scope stack

I have a feeling a better solution here would be to "detect" that a {% call %} is in the import and just deny list it from eager execution by throwing DeferredValueException 🤷

gonna surrender this one and close this pr out

@AlpriElse AlpriElse closed this Nov 24, 2026
@AlpriElse
AlpriElse deleted the mirror/eager-deferred-import-parent-state branch November 24, 2026 11:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant