Skip to content

jinja: support block set capture and replace filters - #677

Merged
juliankang4 merged 2 commits into
midagedev:mainfrom
Burntgogi:feat/issue632-jinja
Oct 22, 2026
Merged

juliankang4 merged 2 commits into
midagedev:mainfrom
Burntgogi:feat/issue632-jinja

Conversation

@Burntgogi

@Burntgogi Burntgogi commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Refs #632. CPU-only common Jinja change; no Flint inference/serve registration.

Change

  • Extend the existing set AST/parser/renderer with block capture, local capture scope, namespace targets, nested captures and loop-control/error propagation.
  • Add replace(old, new, count=None), positional/keyword binding, Python string conversion and Unicode/empty-pattern behavior. Invalid arguments remain named errors.
  • Keep the original Flint template unchanged; no family-specific renderer. Update the crate documentation and add behavioral regressions.

Executed verification

Linux x86_64, Intel i5-12600K, 64 GiB, no NVIDIA; nightly-2026-08-28, RUSTFLAGS=-C target-cpu=native. Base 40fec96.

  • cargo test -p bloomery-jinja: 34 passed.
  • cargo clippy -p bloomery-jinja --all-targets -- -D warnings: passed.
  • cargo fmt -p bloomery-jinja; bash tools/check-comments.sh: passed.
  • External Rust smoke executable rendered the exact 2328-byte RecursiveSI/flint template at 2a247be0c0aec895ccb0ac7ca92229ec6df37288, SHA256 7940f4ffa3275c36caa4a582f845aaad79da11018b3961e8fbcad6ae29733466. Compared 51 contexts byte-for-byte with Jinja2 3.1.2 (HF trim/lstrip/loopcontrols and json.dumps filter): zero differences. Cases include empty/system/developer/user/assistant histories, generation suffix on/off, tool preamble placement, wrapped/unwrapped functions, raw-string versus JSON arguments, reasoning history, NUL/think removal and role-marker escaping.

No CUDA, inference, performance, HTTP seat or whole-model parity claim.

Review correction (690feb7)

R14: replace/default/split now share one allocation-free, reference-retaining bind_args owner for positional slots, keyword lookup and duplicate rejection. All three callers migrated; no legacy binder remains. Excess-arity coverage remains as behavior/named-callee assertions rather than re-pinning two/2 or three/3 message spelling.

Re-executed cargo test -p bloomery-jinja (34 pass), clippy --all-targets -D warnings, formatting, comment check, and all 51 original-template/Jinja2 contexts (zero differences).

Actual before/after consumer smoke, exact base40fec962613b9f08e8318f7a53c133d4f58e65e8 versus corrected implementation:

capture BEFORE rc1: block set is not supported: set x
capture AFTER rc0: "é🙂"
replace BEFORE rc1: |replace takes no arguments
replace AFTER rc0: "xbc"
original Flint BEFORE rc1: block set is not supported: set tool_preamble
original Flint AFTER: all 51 Jinja2 contexts match

These are executed external smoke outputs, not a claim that the new unit tests were present on the old commit.

@github-actions github-actions Bot added the model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja label Oct 22, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: MUST_FIX: the new filter adds another owner of positional and keyword argument binding.

Must fix

1. Share argument binding with the existing filters (R14)

crates/jinja/src/lib.rs:2560 repeats the positional-slot binding, keyword lookup and duplicate-argument rejection in default_filter:2624 and split:2379. This is the same argument-binding rule, with different parameter names.

Kind B. Consolidating these copies now keeps later argument-validation fixes in one owner. The fix replaces 44 lines with a 20-line helper and three calls.

Add:

fn bind_args<'a, const N: usize>(
    callee: &str,
    names: [&str; N],
    args: &'a [V],
    kwargs: &'a [(&str, V)],
) -> Result<[Option<&'a V>; N], TemplateError> {
    if args.len() > N {
        return err(format!("{callee} takes at most {N} arguments"));
    }
    let mut slots = std::array::from_fn(|i| args.get(i));
    for (k, v) in kwargs {
        let Some(i) = names.iter().position(|n| n == k) else {
            return err(format!("{callee} takes no argument {k}"));
        };
        if slots[i].replace(v).is_some() {
            return err(format!("{callee}: {k} given twice"));
        }
    }
    Ok(slots)
}

Replace lines 2556–2570 in replace_filter with:

    let slots = bind_args("|replace", ["old", "new", "count"], args, kwargs)?;

Replace lines 2620–2633 in default_filter with:

    let slots = bind_args("|default", ["default_value", "boolean"], args, kwargs)?;

Replace lines 2375–2389 in the split method arm with:

            let given = bind_args("split()", ["sep", "maxsplit"], args, kwargs)?;

Keep the arity assertions. Replace their case rows at lines 3089 and 3140 respectively with:

            ("{{ 'a'|replace('a','b',1,2) }}", "at most 3"),
            ("{{ u|default(1, true, 2) }}", "at most 2"),

Checked

Duplicates: 7 new items checked; the binding copies above remain.
Complexity: replace_filter combines binding, conversion and replacement; share the binding as above. NodeParser::statement adds capture parsing/validation; Renderer::node adds capture execution. Filter and macro_def add single dispatch/refusal branches.
Silent failure: 3 sites followed. Negative counts intentionally replace all matches; closing-tag lookup follows a parser-proven index; capture errors reach render() after scope/output restoration.
Tests: static mutation checks for all 5 new tests: remove the capture frame (1768), swallow loop flow (1773), omit closing-tag validation (521), drop the replacement count limit (2600), or accept duplicate arguments (2567). Each makes its corresponding assertion fail. Tests were not executed here.
Gates: no existing pins, thresholds or cases moved.
Escape catalog: no patterns matched.
Performance: request template formatting; no decode loop, prefill loop or kernel changed.

Notes

The PR body reports passing runs but provides no FAIL-first output for the new tests.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@Burntgogi

Copy link
Copy Markdown
Contributor Author

Addressed the R14 must-fix in 690feb7: a single bind_args owner now handles replace/default/split; every caller migrated, no compatibility copy. Arity rejection coverage is retained without pinning numeric-versus-word message spelling. Re-ran all34 Jinja tests, all-target clippy -D warnings, formatting/comment checks and the exact original-template51-context Jinja2 differential; all pass.

Also added executed exact-base fail-before/pass-after consumer output to the PR body: block capture and argument-taking replace fail on40fec96 and render the expected strings on the corrected head; the original Flint template fails at tool_preamble on the base and matches Jinja2 on the corrected head. This is explicitly smoke evidence, not retroactively claimed failing-unit-test output.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the last review:

  • Must-fix 1: fixed. bind_args:2540 replaces the three reviewed binding copies.
  • Earlier evidence note: the PR body now includes before/after consumer outputs.

Verdict: CLEAN: the correction shares argument binding and preserves argument rejection.

Checked

Duplicates: 2 new items checked. The three reviewed callers share one binder. Dryer reported 0 candidate pairs.
Complexity: replace_filter delegates binding. The flagged NodeParser::statement, Renderer::node, filter and macro_def have no branch growth in this increment.
Silent failure: 3 binder error paths followed through all 3 callers to render(). Excess, unknown and duplicate arguments return named errors.
Tests: static mutation checks. Removing the arity guard at lib.rs:2546 makes the new test's expect_err fail for each callee. Accepting duplicate bindings at :2555 breaks retained replace/default/split assertions. Tests were not executed here.
Gates: no pins moved. The replace/default excess-arity cases moved into the shared behavioral test; split coverage was added.
Adversarial: empty argument lists preserve defaults or required-argument errors; exact arity fills valid slots; repeated keywords fail before a result escapes.
Escape catalog: no patterns matched.
Performance: common chat-template formatting; the binder retains references in a stack array.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4
juliankang4 merged commit 010729e into midagedev:main Oct 22, 2026
7 checks passed
@juliankang4

Copy link
Copy Markdown
Collaborator

@Burntgogi Thanks for the contribution. The review is done, so I'm merging this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants