Skip to content

fix(vars): resolve composed references safely - #12248

Open
0718lol wants to merge 8 commits into
promptfoo:mainfrom
0718lol:fix/resolve-variables-ordering
Open

0718lol wants to merge 8 commits into
promptfoo:mainfrom
0718lol:fix/resolve-variables-ordering

Conversation

@0718lol

@0718lol 0718lol commented Nov 8, 2026 •

Copy link
Copy Markdown

Summary

Variable composition can stop at an undefined placeholder and leave later, defined placeholders unresolved. Resolve all defined references while preserving undefined placeholders for the final template render.

Fixes #12240.

Behavior

  • Hello {{undefined_var}} and {{name}}, with name: Alice, becomes Hello {{undefined_var}} and Alice.
  • Identify cyclic variable dependencies before expansion and recheck when replacements form new placeholders. Self-references, mutual cycles, and aliases leading to cycles stay unresolved while unrelated defined variables still resolve.
  • Resolve ordinary aliases before inserting skipped values. {{prefix}} {{payload}}, with prefix: '{{greeting}}', now produces the greeting followed by the literal payload. Template expressions inside skipped payloads remain untouched.
  • Preserve literal dollar-sign sequences and existing object/Date coercion. Each resolution phase retains a five-iteration bound and stops when values no longer change.

Validation

  • Added 13 regression cases covering repeated self-references, mutual cycles, cycles assembled from replacement fragments, ordinary aliases next to skipped payloads in either order, indirect skipped aliases, and preservation without an external bookkeeping set.
  • A bounded standalone check against the reviewed commit raises RangeError: Invalid string length for { a: '{{a}}{{a}}' }; the patched resolver leaves the value unchanged. A second bounded check confirms fragment-assembled cycles also stop expanding instead of raising RangeError.
  • Relevant evaluator suites: 796 passed across 32 files.
  • Full backend suite on Node 24.22.2: 39,552 passed, 10 skipped across 1,093 files.
  • npm run tsc, npm run l, npm run f, and git diff --check passed. Lint reports only existing complexity warnings in unchanged functions.
  • Built the CLI with tsdown and postbuild, then ran four local echo evaluations with --no-cache. Exported JSON confirms all four passed with no errors: partial substitution after an undefined reference, ordinary context next to a literal skipped payload, bounded cyclic composition, and a cycle assembled from replacement fragments.

Disclosure

Prepared with AI assistance. The regression tests and CLI checks reported above were executed locally.

resolveVariables() matched only the first {{ \w+ }} placeholder per pass
(regex without the g flag). When that first placeholder referenced an
undefined variable, no replacement happened in the pass, the do-while
loop ended, and every later placeholder in the same string was silently
left unresolved - even when its variable was defined. The behavior was
order-dependent: 'Hello {{ undefined_var }} and {{ name }}' kept the
literal '{{ name }}', while 'Hello {{ name }} and {{ undefined_var }}'
resolved the first placeholder.

Substitute every placeholder whose variable is defined in one pass with
a global regex and a function replacer (keeps $&/$'/$` literals and
skipped-var bookkeeping); placeholders whose variable is undefined stay
untouched for the final nunjucks render, as before.

Fixes promptfoo#12240
@0718lol
0718lol requested review from a team and mldangelo-oai as code owners November 8, 2026 18:44
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T17:46:18.083811Z d6af38f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.83%. Comparing base (0c123d8) to head (d6af38f).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #12248   +/-   ##
=======================================
  Coverage   89.82%   89.83%           
=======================================
  Files        1054     1054           
  Lines       93222    93285   +63     
  Branches    33119    33134   +15     
=======================================
+ Hits        83736    83799   +63     
  Misses       9486     9486           
Flag Coverage Δ
backend 90.54% <100.00%> (+<0.01%) ⬆️
site 53.49% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a874e42563

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/evaluatorHelpers.ts Resolved
Comment thread src/evaluatorHelpers.ts Resolved
@0718lol 0718lol changed the title fix(vars): resolve defined placeholders after an unresolved one fix(vars): resolve composed references safely Nov 9, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8705192914

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/evaluatorHelpers.ts Resolved

@promptfoo-scanner promptfoo-scanner 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.

👍 All Clear

Reviewed changes to variable resolution and prompt rendering behavior, plus related tests. The updates improve placeholder handling and cycle detection without adding new tools or expanding capabilities. Based on the diff, no medium-or-higher LLM security issues were identified.

Minimum severity threshold: 🟡 Medium | To re-scan after changes, comment @promptfoo-scanner
Learn more


Was this helpful?  👍 Yes  |  👎 No 

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5ee4014412

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/evaluatorHelpers.ts
const value = variables[key] as string;
let referencesSkipped = false;
// A replacer function keeps `$&`, `$'` and `` $` `` in the value literal.
const newValue = value.replace(regex, (placeholder: string, varName: string) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Cap acyclic fan-out before global replacement

Even though the new scans block cycles, an acyclic fan-out such as a0: '{{a1}}{{a1}}' through a32 with final a32: 'x' leaves cyclicVars empty, so this global replacement attempts to expand the compact map to 2^32 characters within the five passes; even depth 24 materializes 16,777,216 characters. The old one-match-per-key loop stayed bounded, so a generated or untrusted vars file can now throw RangeError or exhaust the evaluator before any downstream prompt-length check runs; enforce an expansion/output budget before constructing newValue.

AGENTS.md reference: AGENTS.md:L370-L372

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in b05ddd1. Both substitution phases share a cumulative expansion budget of 8,388,608 UTF-16 code units. Each replacement checks its contribution before the expanded string is assembled. Exceeding the budget produces an evaluation error that names the variable. I verified the 32-level acyclic case in both input orders and checked that the CLI reports the limit in its exported result. The regression tests also cover repeated skipped payloads.

Comment thread src/evaluatorHelpers.ts Outdated
if (!resolveSkipped && newValue.includes('{{')) {
// Replacement fragments can assemble placeholders absent from the
// original value, so check the updated dependency graph as well.
cyclicVars = findCyclicVariables(variables, ordinaryVars, regex);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid rebuilding the full graph for every replacement

When a vars map contains many values like {{known}} {{missing}}, each successful substitution leaves the pre-existing {{missing}} text and therefore invokes findCyclicVariables once for every entry even though no dependency edge was introduced. Since each invocation scans every variable, resolution becomes quadratic per eval (for example, 2,000 such columns cause 2,000 full graph builds); update only the changed dependencies or distinguish newly assembled placeholders from pre-existing unresolved ones.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in b05ddd1. The resolver caches each variable's direct dependencies and updates only the changed entry. It reruns cycle detection when a substitution introduces a dependency that was neither present in the original value nor inherited from an inlined alias. In the 2,000-column reproduction, full cycle checks dropped from 2,001 to one with identical output. The fragment-assembled cycle tests also pass.

@promptfoo-scanner promptfoo-scanner 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.

👍 All Clear

Reviewed changes to variable resolution and prompt rendering paths that feed into provider.callApi. The PR adds cycle detection and expansion limits, and adjusts how skipped variables are handled. No LLM security-relevant capabilities (tools, external I/O, execution sinks) were added or modified. As a result, no actionable LLM security vulnerabilities were identified.

Minimum severity threshold: 🟡 Medium | To re-scan after changes, comment @promptfoo-scanner
Learn more


Was this helpful?  👍 Yes  |  👎 No 

@promptfoo-scanner promptfoo-scanner 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.

👍 All Clear

Reviewed changes to variable resolution and prompt rendering logic, plus associated tests. The updates add bounds and cycle detection and adjust how unresolved/skip variables are handled. Based on the diff, there are no new LLM-integrated capabilities, tools, or execution sinks that create security risk. No LLM security vulnerabilities were identified.

Minimum severity threshold: 🟡 Medium | To re-scan after changes, comment @promptfoo-scanner
Learn more


Was this helpful?  👍 Yes  |  👎 No 

@promptfoo-scanner promptfoo-scanner 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.

👍 All Clear

Reviewed variable substitution and prompt construction changes, along with related tests that exercise evaluate/renderPrompt flows. The PR adds cycle detection, own-property checks, and bounded expansion, which are defensive. Based on the diff, there are no new LLM security risks involving tool execution, data exfiltration, or secrets exposure.

Minimum severity threshold: 🟡 Medium | To re-scan after changes, comment @promptfoo-scanner
Learn more


Was this helpful?  👍 Yes  |  👎 No 

This branch has not been deployed

No deployments
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.

Unresolved variable preceding defined variable silently halts substitution in resolveVariables

2 participants