Add template_mismatch_policy for render-time {{field}} mismatches#1958
Open
dmontagu wants to merge 2 commits into
Open
Add template_mismatch_policy for render-time {{field}} mismatches#1958dmontagu wants to merge 2 commits into
dmontagu wants to merge 2 commits into
Conversation
Implements item C of #1950: a configurable render-time policy for what happens when `TemplateVariable.get(inputs)` is called against a template that references a `{{field}}` not declared in the variable's `inputs_type`. Closes the asymmetry Alex flagged on `templates-and-composition.md:36` (composition warned, render path silently substituted empty). `template_mismatch_policy: Literal['warn', 'error', 'ignore']`: - `'warn'` (default): emit a `RuntimeWarning` and render the missing field as the empty string (Handlebars' default behaviour). - `'error'`: raise `TemplateInputsMismatchError` instead of rendering. - `'ignore'`: render silently, no warning. Configurable at three levels with explicit precedence: 1. Per-variable via `var()` / `template_var()`'s `template_mismatch_policy` argument. **Variable-level wins**, even when relaxing — set this when one specific variable should opt out of (or into) strict enforcement without affecting siblings. 2. Per-Logfire-instance via `VariablesOptions.template_mismatch_policy` or `LocalVariablesOptions.template_mismatch_policy`. 3. Falls back to `'warn'` when nothing is set. The two options classes carry the field independently (they're peers, not subclasses of each other), so a `LocalVariablesOptions`-driven test/dev rig can be strict while production `VariablesOptions` stays lenient (or vice versa). `TemplateVariable._check_template_fields` runs every `{{field}}` reference in the post-composition serialized value through `pydantic_handlebars.check_template_compatibility` against `get_template_inputs_schema()`. Any error-severity issue triggers the policy. For `'error'`, we raise a new `TemplateInputsMismatchError(Exception)` rather than a `HandlebarsError`. The SDK's normal composition-failure fallback (`Variable._resolve`'s outer `except Exception`) catches HandlebarsError-and-friends to degrade gracefully to the code default; the `'error'` policy is explicitly opt-in *loud* mode, so we route past the fallback. A dedicated `except TemplateInputsMismatchError: raise` in `_resolve` lets it escape to the caller. `extract_template_strings` (previously `_extract_template_strings` in `template_validation`) is promoted to public so the runtime check can share the same JSON-walker the push-time validator uses; the function is still small and dependency-free. Eight new cases in `TestTemplateMismatchPolicy`: - Default policy is `'warn'`, fires on mismatch, silent when inputs satisfy. - Per-variable `'error'` raises `TemplateInputsMismatchError`. - Per-variable `'ignore'` renders silently. - Instance-level `'error'` raises. - Instance-level `'error'` + variable `'ignore'` → renders silently (variable-level relaxes). - Instance-level `'warn'` + variable `'error'` → raises (variable-level escalates). - Instance-level `'warn'` + variable `'ignore'` → renders silently.
Contributor
There was a problem hiding this comment.
4 issues found across 7 files
Confidence score: 4/5
- This PR looks safe to merge with minimal risk: all reported findings are documentation mismatches rather than runtime code defects.
- The most significant issue is in
logfire/_internal/main.py, where docs say'error'mode raisesHandlebarsRuntimeErrorbut behavior raisesTemplateInputsMismatchError, which could lead callers to catch the wrong exception. - Similar exception-type and API-surface doc drift in
logfire/variables/variable.pyandlogfire/_internal/config.pymay confuse integration/error-handling expectations, but impact appears limited to guidance text. - Pay close attention to
logfire/_internal/main.py,logfire/variables/variable.py,logfire/_internal/config.py- align documented exceptions andvar()vstemplate_var()policy support to prevent user confusion.
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Collaborator
|
coverage will likely be resolved by #1957 |
`'error'` mode raises `TemplateInputsMismatchError` (defined in
`logfire/variables/variable.py`), not `HandlebarsRuntimeError`. Three
spots referenced the wrong exception:
- `_internal/main.py` `template_var` `Raises:` clause
- `variables/variable.py` `TemplateVariable.get` `Raises:` clause
- `_internal/config.py` `TemplateMismatchPolicy` type alias docstring
Also clarify in `TemplateMismatchPolicy` and the field-level
docstrings that plain `var()` doesn't accept the policy — only
`template_var()` does. Plain `Variable` doesn't render `{{...}}`
templates so the policy doesn't apply.
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.
Third in the #1950 series, stacked on #1953. Implements item C: a configurable render-time policy for
TemplateVariable.get(inputs)when the resolved template references a{{field}}the inputs don't declare. Closes the asymmetry Alex flagged ontemplates-and-composition.md:36(composition warned, render path silently substituted empty).New knob
template_mismatch_policy: Literal['warn', 'error', 'ignore']:'warn'(default): emit aRuntimeWarningand render the missing field as the empty string (Handlebars' default behaviour).'error': raiseTemplateInputsMismatchErrorinstead of rendering.'ignore': render silently, no warning.Three configuration levels, variable wins
template_var(..., template_mismatch_policy='error'). Variable-level wins, even when relaxing — set this when one specific variable should opt out of (or into) strict enforcement without affecting siblings.VariablesOptions.template_mismatch_policyorLocalVariablesOptions.template_mismatch_policy(the two carry the field independently — they're peers, not subclasses of each other).'warn'when nothing is set.Why a dedicated exception type
For
'error', we raise a newTemplateInputsMismatchError(Exception)rather than aHandlebarsError. The SDK's normal composition-failure fallback (Variable._resolve's outerexcept Exception) catchesHandlebarsErrorand friends to degrade gracefully to the code default — but the'error'policy is explicitly opt-in loud mode, so we route past that fallback. A dedicatedexcept TemplateInputsMismatchError: raisein_resolvelets the exception escape to the caller.Tests
Eight new cases in
TestTemplateMismatchPolicy:'warn', fires on mismatch, silent when inputs satisfy.'error'raisesTemplateInputsMismatchError.'ignore'renders silently.'error'raises.'error'+ variable'ignore'→ renders silently (variable-level relaxes).'warn'+ variable'error'→ raises (variable-level escalates).'warn'+ variable'ignore'→ renders silently.Series
Next: PR 4 (misrender retention parity — item F), then PR 5 (internal cleanups — items G and H).