Skip to content

jinja

jinja

Jinja template validation checks.

Validates Jinja2 template syntax and detects undefined variables that would cause runtime errors.

Classes

JinjaSyntaxCheck

Check for Jinja template syntax errors (V001).

Attempts to parse templates and reports syntax errors with line numbers and context. This catches issues like: - Unclosed blocks ({% if ... without {% endif %}) - Unclosed expressions ({{ ... without }}) - Invalid syntax inside blocks

Methods:
check
check(config, config_path, raw_yaml)

Check Jinja syntax in templates.

Source code in src/marianne/validation/checks/jinja.py
def check(
    self,
    config: JobConfig,
    config_path: Path,
    raw_yaml: str,
) -> list[ValidationIssue]:
    """Check Jinja syntax in templates."""
    issues: list[ValidationIssue] = []
    env = jinja2.Environment()

    # Check inline template
    if config.prompt.template:
        template_issues = self._check_template(
            config.prompt.template,
            "prompt.template",
            find_line_in_yaml(raw_yaml, "template:"),
            env,
        )
        issues.extend(template_issues)

    # Check external template file
    if config.prompt.template_file:
        template_path = resolve_path(config.prompt.template_file, config_path)
        if template_path.exists():
            try:
                template_content = template_path.read_text()
                template_issues = self._check_template(
                    template_content,
                    f"template_file ({template_path.name})",
                    None,
                    env,
                )
                issues.extend(template_issues)
            except Exception as e:  # noqa: BLE001 — template read failure is appended to returned validation issues
                issues.append(
                    ValidationIssue(
                        check_id=self.check_id,
                        severity=self.severity,
                        message=f"Could not read template file: {e}",
                        suggestion=f"Check file permissions for {template_path}",
                    )
                )

    return issues

JinjaUndefinedVariableCheck

Check for undefined template variables (V101).

Warns about variables used in templates that aren't defined in the config's variables section or the built-in sheet context. Uses fuzzy matching to suggest corrections for typos.

Methods:
check
check(config, config_path, raw_yaml)

Check for undefined variables in templates.

Source code in src/marianne/validation/checks/jinja.py
def check(
    self,
    config: JobConfig,
    config_path: Path,
    raw_yaml: str,
) -> list[ValidationIssue]:
    """Check for undefined variables in templates."""
    issues: list[ValidationIssue] = []
    env = jinja2.Environment()

    # Collect all defined variables
    defined_vars = set(self.BUILTIN_VARIABLES)
    defined_vars.update(config.prompt.variables.keys())
    # A declared loop index is emitted bare and under `loops.<index>`.
    defined_vars.update(loop.index for loop in (config.sheet.loops or {}).values())

    # Check inline template
    if config.prompt.template:
        var_issues = self._check_undefined_vars(
            config.prompt.template,
            "prompt.template",
            defined_vars,
            env,
        )
        issues.extend(var_issues)

    # Check external template file
    if config.prompt.template_file:
        template_path = resolve_path(config.prompt.template_file, config_path)
        if template_path.exists():
            try:
                template_content = template_path.read_text()
                var_issues = self._check_undefined_vars(
                    template_content,
                    f"template_file ({template_path.name})",
                    defined_vars,
                    env,
                )
                issues.extend(var_issues)
            except Exception as exc:  # noqa: BLE001 — template read failure is appended to returned validation issues
                issues.append(ValidationIssue(
                    check_id="V101",
                    severity=ValidationSeverity.WARNING,
                    message=f"Cannot read template file '{template_path.name}' "
                            f"for undefined variable check: {exc}",
                    suggestion="Ensure the template file is readable.",
                ))

    return issues

FanOutStringFilterCheck

Detect dict[X | string] on int-normalized variable dicts (V102, #132).

A per-instance dict with int-like string keys ({"1": ...}) has its keys normalized to integers at render time (_normalize_dict_keys). A template that subscripts it with dict[instance | string] re-stringifies the int instance to "1", which no longer matches the int key 1 → UndefinedError on every fan-out instance.

Detection is CORRELATED, not pure-AST: | string is correct for genuinely string-keyed dicts, so the check fires ONLY when the subscripted base Name resolves to a prompt.variables dict whose keys are ALL integers after normalization (int, or int-normalizable strings). This gives zero false positives — a string index never matches an all-int-keyed dict. The filtered Name is not restricted: the dict's key types are the precondition, and | string always produces a string index regardless of what it filters.

Methods:
check
check(config, config_path, raw_yaml)

Flag dict[X | string] where dict has all-int-normalizable keys.

Source code in src/marianne/validation/checks/jinja.py
def check(
    self,
    config: JobConfig,
    config_path: Path,
    raw_yaml: str,
) -> list[ValidationIssue]:
    """Flag `dict[X | string]` where dict has all-int-normalizable keys."""
    issues: list[ValidationIssue] = []
    env = jinja2.Environment()
    variables = config.prompt.variables

    sources: list[tuple[str, str]] = []
    if config.prompt.template:
        sources.append((config.prompt.template, "prompt.template"))
    if config.prompt.template_file:
        template_path = resolve_path(config.prompt.template_file, config_path)
        if template_path.exists():
            try:
                sources.append(
                    (template_path.read_text(), f"template_file ({template_path.name})")
                )
            except Exception:  # noqa: BLE001 — unreadable file is V101's concern
                pass

    seen: set[str] = set()
    for template_str, source_name in sources:
        try:
            ast = env.parse(template_str)
        except jinja2.TemplateSyntaxError:
            continue  # Syntax errors are reported by V001.
        for getitem in ast.find_all(jinja2_nodes.Getitem):
            if not isinstance(getitem.node, jinja2_nodes.Name):
                continue
            if not self._chain_has_string_filter(getitem.arg):
                continue
            var_name = getitem.node.name
            value = variables.get(var_name)
            if not isinstance(value, dict) or not self._all_keys_int(value):
                continue
            key = f"{source_name}:{var_name}"
            if key in seen:
                continue
            seen.add(key)
            issues.append(
                ValidationIssue(
                    check_id=self.check_id,
                    severity=ValidationSeverity.WARNING,
                    message=(
                        f"'{var_name}[... | string]' will fail at render time: "
                        f"{var_name}'s int-like keys are normalized to integers, "
                        f"but '| string' produces a string index that never "
                        f"matches them — UndefinedError on every fan-out instance."
                    ),
                    line=find_line_in_yaml(raw_yaml, "| string"),
                    context=f"{source_name}: {var_name}[... | string]",
                    suggestion=(
                        f"Remove '| string' — use {var_name}[instance] directly; "
                        f"the engine normalizes the dict's keys to int to match "
                        f"the int fan-out variable."
                    ),
                    metadata={"variable": var_name},
                )
            )
    return issues

BashArrayLengthCheck

Detect bash ${#...} length syntax in templates (V305, #362).

Jinja2 tokenizes the literal {# as a comment opener. Bash array/string length expansion (${#ARR[@]}, ${#var}) contains {#, so Jinja silently consumes everything from {# to the next #} — truncating the rendered prompt mid-token. The cli instrument then runs a broken script and dies with a bare "Exit code 2" and no stderr. There is no legitimate ${# in a Jinja template (it always opens a comment), so this scan is zero-false- positive and blocks validation. Recommends a length-free idiom.

Methods:
check
check(config, config_path, raw_yaml)

Scan prompt.template and template_file for the ${# collision.

Source code in src/marianne/validation/checks/jinja.py
def check(
    self,
    config: JobConfig,
    config_path: Path,
    raw_yaml: str,
) -> list[ValidationIssue]:
    """Scan prompt.template and template_file for the `${#` collision."""
    issues: list[ValidationIssue] = []
    sources: list[tuple[str, str]] = []
    if config.prompt.template:
        sources.append((config.prompt.template, "prompt.template"))
    if config.prompt.template_file:
        template_path = resolve_path(config.prompt.template_file, config_path)
        if template_path.exists():
            try:
                sources.append(
                    (template_path.read_text(), f"template_file ({template_path.name})")
                )
            except Exception:  # noqa: BLE001 — unreadable file is V101's concern
                pass

    for template_str, source_name in sources:
        if "${#" not in template_str:
            continue
        issues.append(
            ValidationIssue(
                check_id="V305",
                severity=self.severity,
                message=(
                    f"{source_name} contains bash '${{#...}}' length syntax. "
                    "Jinja reads the '{#' as a comment opener and silently "
                    "deletes the template from there to the next '#}', "
                    "truncating the rendered prompt — the cli instrument then "
                    "fails with a bare 'Exit code 2' and no stderr."
                ),
                line=find_line_in_yaml(raw_yaml, "${#"),
                context=source_name,
                suggestion=(
                    "Avoid '${#...}'. For array length use "
                    "`printf '%s\\n' \"${ARR[@]:-}\" | grep -c .` or "
                    "`find DIR -name PAT | wc -l`; for empty-check use "
                    "`[ -z \"${ARR[0]:-}\" ]`."
                ),
            )
        )
    return issues

Functions: