AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Mustache Inverted Section Nested In Same-Key Section Misrenders Or Raises IndexError

The mustache renderer in langchain-core miscounts section nesting when an inverted section with the same key is nested inside a regular list section. This leads to silently wrong output (e.g., '[[]' instead of '[a][b]') or an IndexError. The depth counter used to handle nested regular sections only increments for 'section' tokens, not for 'inverted section' tokens, causing the inner closing tag to be misinterpreted as the outer section's end.

highConfidence 95%LangChainAffected V1.6.3

Origin Analysis

In langchain_core/utils/mustache.py, the rendering loop that gathers tokens for a list section tracks nesting depth with a counter. The counter is incremented only for tokens of type ('section', key) but decremented for every token of type ('end', key). Since an inverted section with the same key (`{{^key}}...{{/key}}`) uses the same end tag but does not increment the counter, the inner `{{/key}}` falsely satisfies the outer section's closure condition. This truncates the loop body and leaves an unmatched end token, causing a pop from an empty scope stack (IndexError) or wrong rendering of the remaining tokens.
1. Create a ChatPromptTemplate with mustache template format.\n2. Use template: "{{#items}}[{{^items}}none{{/items}}{{name}}]{{/items}}" and invoke with items=[{'name':'a'},{'name':'b'}]. Observe output '[[]' instead of '[a][b]'.\n3. Use template: "{{#items}}{{^items}}none{{/items}}{{/items}}Done" and invoke with items=[{'name':'a'},{'name':'b'}]. Observe IndexError: list index out of range.\n4. Directly call langchain_core.utils.mustache.render with the same templates to see the same behavior.

Fixing Code Block

Edge Case Audit

The fix should be safe for standard mustache rendering, but it may alter behavior for templates that previously relied on the bug (though such templates are rare and likely unintended). To avoid regressions, add unit tests for nested regular and inverted sections, including mixed same-key and different-key nesting. If the fix is rolled out, monitor for any templates that produce different output; a rollback can be performed by reverting this single-line change. It is also recommended to verify that other token types (e.g., comments, partials) are not inadvertently included in the depth counting.

Ecosystem Topology