Repository navigation
fix(agent): allow underscores in variable_ref_patt component_id (#16758) - #16792
Conversation
…niflow#16758) The regex used by `ComponentBase.variable_ref_patt` (and its twin in `agent.canvas.Graph.get_value_with_variable`) restricted the `cpn_id` half of `cpn_id@var_nm` template refs to `[a-zA-Z:0-9]+`. That character class drops underscores, so any frontend-emitted component id like `userfillup_abc`, `retrieval_xyz`, `llm_0`, `message_0` failed to match. The variable was then left literal in the resolved prompt, and downstream components (LLM agents, retrieval filters, message templates) ignored the value entirely. This is exactly the "unconsidered await response" symptom in infiniflow#16758: Begin(Task) -> Await response -> Agent -> Message The user types into the Await-response form; the variable is wired into the Agent's user prompt as `{userfillup_xxx@line}`. Because the regex never matched, the placeholder reached the LLM verbatim and the Agent answered only its system-prompt directive. Widen `cpn_id` from `[a-zA-Z:0-9]+` to `[a-zA-Z0-9_]+` and add `{line}` (no cpn_id) remains unrecognised so it stays literal until the user wires it up. This matches the existing VARIABLE_REF_PATTERN shape used by `agent.dsl_migration` for the same purpose. Add `test_variable_ref_pattern_unit.py` to pin: - underscored cpn_id@var_nm matches - legacy ids (begin/retrieval), sys.* and env.* still match - get_input_elements_from_text surfaces the value of an underscored `cpn_id@var_nm` reference - string_format substitutes an underscored `cpn_id@var_nm` token - bare `{line}` (no cpn_id prefix) remains unmatched by design Fixes infiniflow#16758 Co-authored-by: Cursor <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughPlaceholder matching for ChangesVariable Reference Regex Fix
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
agent/canvas.py (1)
202-205: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCentralize the regex pattern instead of duplicating it.
The pattern string is identical to
ComponentBase.variable_ref_pattinagent/component/base.py:357. Hardcoding a copy means future regex updates must be applied in two places — if one is missed,get_value_with_variableandComponentBase.get_input_elements_from_textwill silently disagree on which placeholders are valid. Reference the canonical class attribute instead.As a secondary note,
re.compileis called on every invocation. Pre-compiling once (or referencing a pre-compiled class attribute) avoids redundant work.♻️ Proposed refactor: reference canonical pattern and pre-compile
def get_value_with_variable(self, value: str) -> Any: - # `cpn_id` allows underscores so genuine component ids emitted by - # the frontend (e.g. `userfillup_abc`, `retrieval_xyz`) are recognised. - pat = re.compile(r"\{* *\{([a-zA-Z0-9_]+@[A-Za-z0-9_.-]+|sys\.[A-Za-z0-9_.]+|env\.[A-Za-z0-9_.]+)\} *\}*") + from agent.component.base import ComponentBase + pat = re.compile(ComponentBase.variable_ref_patt, flags=re.IGNORECASE | re.DOTALL) out_parts = [] last = 0Alternatively, add a pre-compiled class attribute to
ComponentBase:# In agent/component/base.py, ComponentBase class body: + _variable_ref_re = re.compile(variable_ref_patt, flags=re.IGNORECASE | re.DOTALL)Then reference
ComponentBase._variable_ref_refrom both call sites.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/canvas.py` around lines 202 - 205, `get_value_with_variable` is duplicating the placeholder regex instead of using the canonical pattern from `ComponentBase.variable_ref_patt`, so update it to reference the shared source of truth and avoid drift with `ComponentBase.get_input_elements_from_text`. Also avoid compiling the regex on every call by using a pre-compiled shared attribute (for example on `ComponentBase`) or another module-level cached regex, and have `get_value_with_variable` use that symbol directly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@agent/component/base.py`:
- Around line 354-357: The template-ref regex in `base.py` is too restrictive
for component IDs because `variable_ref_patt` now excludes colon-bearing
`cpn_id` values. Update the pattern used for `cpn_id@var_nm` matching so it
still accepts IDs like `Browser:BusyHatsSink` and `UserFillUp:Menu`, or add a
backward-compatible migration path before tightening the grammar. Keep the
`variable_ref_patt` logic aligned with existing template and DSL fixtures so
these refs continue to resolve instead of staying literal.
---
Nitpick comments:
In `@agent/canvas.py`:
- Around line 202-205: `get_value_with_variable` is duplicating the placeholder
regex instead of using the canonical pattern from
`ComponentBase.variable_ref_patt`, so update it to reference the shared source
of truth and avoid drift with `ComponentBase.get_input_elements_from_text`. Also
avoid compiling the regex on every call by using a pre-compiled shared attribute
(for example on `ComponentBase`) or another module-level cached regex, and have
`get_value_with_variable` use that symbol directly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e943a80f-903f-4cb3-ae0d-0e01256650f8
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pytest/testcases/test_web_api/test_canvas_app/test_variable_ref_pattern_unit.py
Follow-up to infiniflow#16758 and addresses two review notes from CodeRabbit on infiniflow#16792: 1. **Data Integrity (Major): the previous fix at 16f3c97 widened `cpn_id` from `[a-zA-Z:0-9]+` to `[a-zA-Z0-9_]+`, dropping colon support. Colon-bearing cpn_ids remain in active use across the codebase** — `UserFillUp:CateInput@text`, `UserFillUp:CodeInput@x`, `UserFillUp:LoopInput@value`, `Retrieval:KBSearch@formalized_content`, `CodeExec:Double@result`, `Browser:BusyHatsSink@content` — scattered across `internal/agent/dsl/testdata/all.json` and other test fixtures/templates. Narrowing would leave all those refs literal at runtime. Reopen the character class to `[a-zA-Z0-9_:]+`. This is a strict superset of both the legacy shape (`[a-zA-Z:0-9]+`) and the underscore-only fix, and matches the `cpn_id` half of `agent.dsl_migration.VARIABLE_REF_PATTERN` (`[A-Za-z0-9:_-]+`). 2. **Maintainability (Trivial): the pattern string was duplicated between `ComponentBase.variable_ref_patt` (used in several places via `re.compile/re.finditer/re.search`) and the inline `re.compile(...)` in `agent.canvas.Graph.get_value_with_variable`. Future regex tweaks would have to be applied at both sites — a `git grep` for either literal divergence would have missed this. Add a pre-compiled sibling `ComponentBase.variable_ref_patt_re` (and the same for `iteration_alias_patt`) and have `Graph.get_value_with_variable` reference the class attribute directly. The pre-compile also drops the per-call `re.compile` cost on the inline canvas helper. Test pinning: see `test_variable_ref_patt_re_matches_variable_ref_patt` which rebuilds the regex from the source string and asserts the same matches / flags. Tests ----- `test_variable_ref_pattern_unit.py` now covers: - underscored cpn_ids (existing infiniflow#16758 regression) - **colon-bearing cpn_ids** (new — `UserFillUp:CateInput@text`, `Retrieval:KBSearch@formalized_content`, mixed id) - Verified to fail against the underscore-only intermediate state with `"colon-bearing cqn_id lost its support"` so the regression is pinned going forward. - legacy ids (`begin`, `retrieval`, `sys.*`, `env.*`) - pre-compiled regex agrees with the source pattern (closes CR's "centralize the regex" note) - helper methods still use the regex end-to-end - bare `{line}` remains unmatched by design Local results: 7 passed in the targeted unit file; 11 passed across the related canvas_app suite (`test_fillup_unit.py`, `test_iterationitem_unit.py`, the new file). Stil resolves infiniflow#16758. Co-authored-by: Cursor <[email protected]>
|
Thanks for the review feedback! Both points from CodeRabbit are addressed in 3babb31 (follow-up commit to 1. Major — "Keep The earlier commit at
Restored the character class to Added a dedicated 2. Trivial — "Centralize the regex pattern instead of duplicating it" Two changes:
The Tests Still resolves #16758. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
agent/component/base.py (1)
490-490: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winUse the pre-compiled regexes instead of raw pattern strings.
Lines 490, 526, and 540 still call
re.search(self.variable_ref_patt, v)/re.finditer(self.variable_ref_patt, txt, ...)/re.finditer(self.iteration_alias_patt, txt, ...)with the raw pattern string, bypassing the pre-compiledvariable_ref_patt_reanditeration_alias_patt_rethat were added to prevent drift and avoid recompilation overhead.canvas.py:get_value_with_variablealready uses the pre-compiled form — these call sites should be consistent.♻️ Proposed refactor
- elif isinstance(v, str) and re.search(self.variable_ref_patt, v): + elif isinstance(v, str) and self.variable_ref_patt_re.search(v):- for r in re.finditer(self.variable_ref_patt, txt, flags=re.IGNORECASE | re.DOTALL): + for r in self.variable_ref_patt_re.finditer(txt):- for r in re.finditer(self.iteration_alias_patt, txt, flags=re.IGNORECASE | re.DOTALL): + for r in self.iteration_alias_patt_re.finditer(txt):Also applies to: 526-526, 540-540
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/component/base.py` at line 490, Update the remaining regex call sites in `BaseComponent` to use the pre-compiled patterns instead of the raw pattern strings. In the branches using `re.search(self.variable_ref_patt, v)` and the `re.finditer(...)` calls for variable refs and iteration aliases, switch to `self.variable_ref_patt_re` and `self.iteration_alias_patt_re` so the behavior matches `canvas.py:get_value_with_variable` and avoids recompilation/drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@agent/component/base.py`:
- Line 490: Update the remaining regex call sites in `BaseComponent` to use the
pre-compiled patterns instead of the raw pattern strings. In the branches using
`re.search(self.variable_ref_patt, v)` and the `re.finditer(...)` calls for
variable refs and iteration aliases, switch to `self.variable_ref_patt_re` and
`self.iteration_alias_patt_re` so the behavior matches
`canvas.py:get_value_with_variable` and avoids recompilation/drift.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: aa34a57a-2363-4809-8ac1-d7e3e8d990c9
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pytest/testcases/test_web_api/test_canvas_app/test_variable_ref_pattern_unit.py
🚧 Files skipped from review as they are similar to previous changes (1)
- agent/canvas.py
Follow-up to 3babb31, closing CodeRabbit's nitpick on infiniflow#16792: > Lines 490, 526, and 540 still call > re.search(self.variable_ref_patt, v) / > re.finditer(self.variable_ref_patt, txt, ...) / > re.finditer(self.iteration_alias_patt, txt, ...) > with the raw pattern string, bypassing the pre-compiled > variable_ref_patt_re and iteration_alias_patt_re All three call sites in `agent/component/base.py` now reference the pre-compiled regex objects directly — no more per-call recomputation or hand-rolled flags: - 490: `self.variable_ref_patt_re.search(v)` - 526: `self.variable_ref_patt_re.finditer(txt)` - 540: `self.iteration_alias_patt_re.finditer(txt)` Worth flagging two subtle behavior alignments that come along for the ride (would have shown up as latent bugs anyway): 1. Line 490 used to call `re.search(self.variable_ref_patt, v)` with **no flags** — i.e. case-sensitive. All other template ref resolution paths in this module (and canvas.py) use `re.IGNORECASE`. Switched to the pre-compiled regex, which now resolves `{USERFILLUP_ABC@LINE}` the same way the helper methods do. 2. `re.DOTALL` had no effect on the previous `re.search` call (the pattern never contained `.`), but the swap to the canonical pre-compiled regex makes it match everywhere else `variable_ref_patt` is used — the source of truth's behavior is now uniform. Out of scope ------------ `agent/component/docs_generator.py:186`, `agent/component/message.py:193`, and `agent/tools/retrieval.py:145` also pass `self.variable_ref_patt` (or a freshly compiled copy) into `re.sub` / `re.finditer`. CR's nitpick + AI prompt explicitly scoped this change to `BaseComponent`, and each of those callers passes a distinct flag set (`re.DOTALL` / no flags), so wiring them up to the pre-compiled regex would change observable behavior (case sensitivity, dot-newline match) beyond what the nitpick asked for. Left for a separate PR if maintainers want uniform case-insensitivity across all template-resolution paths. Tests ----- Re-ran the targeted unit file + related canvas_app tests: test_fillup_unit.py 3 passed test_iterationitem_unit.py 1 passed test_variable_ref_pattern_unit.py 7 passed --------------------------------------------- 11 passed in 0.41s No behavior change in the covered paths; `test_variable_ref_patt_re_matches_variable_ref_patt` still pins the source-pattern / pre-compiled-regex contract. Still resolves infiniflow#16758. Co-authored-by: Cursor <[email protected]>
|
Quick follow-up on the line-490/526/540 nitpick ("Use the pre-compiled regexes instead of raw pattern strings"). All three call sites in
Two behavior-alignment observations worth flagging since they now come along for the ride:
Tests: 11/11 passed locally across the targeted unit file + the related canvas_app suite. Left intentionally out of scope (different
Happy to follow up on those as a separate change if maintainers want uniform case-insensitivity across all template-resolution paths. Still resolves #16758. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16792 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…flow#16758) (infiniflow#16792) Port the workflow variable reference regex fix from Python PR infiniflow#16792 to Go. The Python PR widened cpn_id in variable_ref_patt from [a-zA-Z:0-9]+ to [a-zA-Z0-9_:] (adding underscore support for frontend ids like userfillup_abc, retaining colon for legacy DSL ids like UserFillUp:CateInput). Go's internal/agent/runtime/template.go::VarRefPattern already used [a-zA-Z:0-9_]+ (equivalent to [a-zA-Z0-9_:]+), so no regex change is needed. This commit: - Updates the Go comment to reflect Python alignment (removes the stale deviation note). - Adds comprehensive tests in internal/agent/canvas/variable_test.go pinning underscore-bearing, colon-bearing, and legacy cpn_ids, bare {line} non-match, and end-to-end ResolveTemplate/ExtractRefs resolution. All canvas + runtime package tests pass.
Summary
ComponentBase.variable_ref_patt(and its duplicate inagent.canvas.Graph.get_value_with_variable) is the regex the canvas runtime uses to findcpn_id@var_nmtemplate refs in component prompts.The
cpn_idhalf was constrained to[a-zA-Z:0-9]+, which silently dropped underscores. Component ids emitted by the frontend all contain underscores (userfillup_abc,retrieval_xyz,llm_0,message_0, …), so any template ref like{userfillup_abc@line}failed to match. The placeholder then leaked through to the LLM verbatim, and the Agent answered only its system-prompt directive.This is exactly the "unconsidered await response" symptom in #16758:
Widen
cpn_idfrom[a-zA-Z:0-9]+to[a-zA-Z0-9_]+. Bare{line}(no cpn_id) remains unrecognised so it stays literal until the user wires it up — matching the existingVARIABLE_REF_PATTERNshape used byagent.dsl_migrationfor the same purpose.Changes
agent/component/base.py— fixvariable_ref_pattclass attribute.agent/canvas.py— same fix applied to the inline regex insideGraph.get_value_with_variable(kept as the literal regex to avoid coupling the two unrelated sites).test/testcases/test_web_api/test_canvas_app/test_variable_ref_pattern_unit.py— new regression test pinning both the regex shape and end-to-end resolution.Regression coverage
All five regression tests fail against the pre-fix regex (verified via
git stashround trip — drop fix, tests fail, restore fix, tests pass).The two targeted existing tests in the same directory (
test_fillup_unit.py,test_iterationitem_unit.py) continue to pass.Repro before the fix
Repro after the fix
Fixes #16758
Test plan
test_fillup_unit.py(existing sibling suite) still passestest_iterationitem_unit.py(existing sibling suite) still passes