Skip to content

Fix: variable in doc generator - #14180

Merged
asiroliu merged 3 commits into
infiniflow:mainfrom
Magicbook1108:doc_generator
Apr 20, 2026
Merged

asiroliu merged 3 commits into
infiniflow:mainfrom
Magicbook1108:doc_generator

Conversation

@Magicbook1108

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fix: variable in doc generator

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Apr 17, 2026
@Magicbook1108 Magicbook1108 added the ci Continue Integration label Apr 17, 2026
@Magicbook1108
Magicbook1108 marked this pull request as draft April 17, 2026 03:17
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Apr 17, 2026
@Magicbook1108
Magicbook1108 marked this pull request as ready for review April 17, 2026 03:17
@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 949346a8-f32c-4195-b443-c448bbf6341f

📥 Commits

Reviewing files that changed from the base of the PR and between 4de3fd3 and cb2ff0d.

📒 Files selected for processing (1)
  • agent/component/invoke.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • agent/component/invoke.py

📝 Walkthrough

Walkthrough

Template/variable resolution was refactored: docs_generator.py now prefers kwargs["content"] and performs unconditional regex-based substitution with explicit handling for None, partial, and exceptions; invoke.py centralizes template rendering and applies it to args, headers, and URLs, and consolidates request building/execution and response formatting.

Changes

Cohort / File(s) Summary
Docs generator variable resolution
agent/component/docs_generator.py
Refactored _resolve_content to prefer kwargs["content"] when param content is empty; replaced two-phase resolution with unconditional re.sub callback; treat canvas None as ""; expand partial by concatenation and return resolved string; use _stringify_message_value(..., fallback_to_str=True); return error tokens on exceptions; removed get_kwargs post-processing.
Invoke: centralized template resolution & request flow
agent/component/invoke.py
Introduced header-specific Invoke.header_variable_ref_patt and multiple helpers: _resolve_variable_value, _render_template, _resolve_template_text, _resolve_header_text, _resolve_arg_value, _build_request_args, _build_url, _build_headers, _build_proxies, _send_request, _format_response. Centralized {...} substitution for values, headers, and URLs; added partial handling (concatenate chunks, persist via set_input_value); unified request building and sending, JSON vs form handling, retry tracking, and optional HTML cleaning.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Invoke
  participant Canvas
  participant HTTP as "External API"
  participant Parser as "HtmlParser"

  Client->>Invoke: call _invoke(kwargs)
  Invoke->>Canvas: _resolve_variable_value / get_variable_value
  Canvas-->>Invoke: variable values (str, None, partial, error)
  Invoke->>Invoke: _render_template / _resolve_template_text (values, headers, url)
  Invoke->>HTTP: _send_request(url, args, headers, proxies)
  HTTP-->>Invoke: response
  alt html_cleaning_enabled
    Invoke->>Parser: _format_response -> clean HTML
    Parser-->>Invoke: cleaned text
  end
  Invoke-->>Client: formatted response or error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hop through templates, stitch fragments tight,
I turn partial crumbs into one shining bite.
When None hides quiet, I leave an empty space,
If errors shout, I show their face —
A rabbit's refactor, bounding light. 🥕

🚥 Pre-merge checks | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete; it only states the title again without explaining the problem being solved or providing context about the bug. Expand the description under 'What problem does this PR solve?' to explain the actual variable-related bug, its impact, and how it was fixed.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Fix: variable in doc generator' is vague and lacks specificity about what variable issue was fixed or which aspect of the doc generator was affected. Provide a more specific title that describes the actual issue fixed, such as 'Fix variable resolution in docs generator' or 'Fix content variable handling in doc generator'.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@agent/component/docs_generator.py`:
- Around line 152-174: Repeated placeholder refs are re-resolved each time
inside the _replace_variable callback which can re-consume partial producers and
slow or make output inconsistent; add a local cache dict in docs_generator.py
used by _replace_variable (keyed by the match group string) to store the
resolved string/value so that on subsequent matches you return the cached result
instead of calling self._canvas.get_variable_value again; ensure you still
handle None, partial (consume it once and cache the resulting string), call
self._stringify_message_value for non-partial values, and preserve the existing
exception handling and fallback behavior.
- Around line 149-150: The runtime `content` value is being pulled with a
truthiness chain (self._param.content or kwargs.get("content", "") or "") which
drops valid falsy values (0/False) and leaves non-string types unnormalized
before calls to len(...) and re.sub(...); change the logic that sets `content`
so you first determine presence (e.g. check `"content" in kwargs` or `is not
None` for self._param.content) and then coerce the chosen value to a string
(e.g. use str(value) or "" for None) so `content` is always a string before the
logging call (logging.info(..., len(content))) and subsequent processing in this
module (references: variable `content`, attributes `self._param.content`,
kwargs.get("content"), and the logging.info call).
🪄 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: 57d3ea87-6fec-43c5-acbc-601ccb3c1965

📥 Commits

Reviewing files that changed from the base of the PR and between 0df5d83 and 63d89d4.

📒 Files selected for processing (1)
  • agent/component/docs_generator.py

Comment on lines +149 to 150
content = self._param.content or kwargs.get("content", "") or ""
logging.info("Starting document generation, content length: %s chars", len(content))

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.

⚠️ Potential issue | 🟠 Major

Normalize runtime content before treating it as a string.

Line 149 now pulls kwargs["content"] through a truthiness chain, which silently drops valid values like 0/False and passes non-string payloads straight into Line 150/169. That means upstream list/dict/partial content can now either disappear or fail during len(...) / re.sub(...) instead of being rendered.

Possible fix
-        content = self._param.content or kwargs.get("content", "") or ""
+        raw_content = self._param.content if self._param.content != "" else kwargs.get("content", "")
+        if isinstance(raw_content, partial):
+            content = "".join(raw_content())
+        else:
+            content = self._stringify_message_value(raw_content, fallback_to_str=True)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@agent/component/docs_generator.py` around lines 149 - 150, The runtime
`content` value is being pulled with a truthiness chain (self._param.content or
kwargs.get("content", "") or "") which drops valid falsy values (0/False) and
leaves non-string types unnormalized before calls to len(...) and re.sub(...);
change the logic that sets `content` so you first determine presence (e.g. check
`"content" in kwargs` or `is not None` for self._param.content) and then coerce
the chosen value to a string (e.g. use str(value) or "" for None) so `content`
is always a string before the logging call (logging.info(..., len(content))) and
subsequent processing in this module (references: variable `content`, attributes
`self._param.content`, kwargs.get("content"), and the logging.info call).

Comment on lines +152 to +174
if content:
def _replace_variable(match_obj: re.Match[str]) -> str:
match = match_obj.group(1)
try:
var_value = self._canvas.get_variable_value(match)
if var_value is None:
continue
return ""
if isinstance(var_value, partial):
resolved_content = ""
for chunk in var_value():
resolved_content += chunk
content = content.replace("{" + match + "}", resolved_content)
else:
content = content.replace("{" + match + "}", str(var_value))
return resolved_content
return self._stringify_message_value(var_value, fallback_to_str=True)
except Exception as e:
logging.warning("Error resolving variable %s: %s", match, str(e))
content = content.replace("{" + match + "}", f"[ERROR: {str(e)}]")
return f"[ERROR: {str(e)}]"

if content:
try:
content, _ = self.get_kwargs(content, kwargs)
except Exception as e:
logging.warning("Error processing content with get_kwargs: %s", str(e))

if not content:
content = kwargs.get("content", "")
content = re.sub(
self.variable_ref_patt,
_replace_variable,
content,
flags=re.DOTALL,
)

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.

⚠️ Potential issue | 🟠 Major

Cache repeated placeholder resolutions.

This re.sub callback resolves the same placeholder every time it appears, so repeated refs like {foo@bar} will hit self._canvas.get_variable_value(...) multiple times and can re-consume partial producers multiple times. Message._stream already caches by variable name, and without that here the same document can become slower or inconsistent when a ref is repeated.

Possible fix
         if content:
+            cache: dict[str, str] = {}
+
             def _replace_variable(match_obj: re.Match[str]) -> str:
                 match = match_obj.group(1)
+                if match in cache:
+                    return cache[match]
                 try:
                     var_value = self._canvas.get_variable_value(match)
                     if var_value is None:
-                        return ""
+                        cache[match] = ""
+                        return ""
                     if isinstance(var_value, partial):
                         resolved_content = ""
                         for chunk in var_value():
                             resolved_content += chunk
+                        cache[match] = resolved_content
                         return resolved_content
-                    return self._stringify_message_value(var_value, fallback_to_str=True)
+                    resolved = self._stringify_message_value(var_value, fallback_to_str=True)
+                    cache[match] = resolved
+                    return resolved
                 except Exception as e:
                     logging.warning("Error resolving variable %s: %s", match, str(e))
                     return f"[ERROR: {str(e)}]"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@agent/component/docs_generator.py` around lines 152 - 174, Repeated
placeholder refs are re-resolved each time inside the _replace_variable callback
which can re-consume partial producers and slow or make output inconsistent; add
a local cache dict in docs_generator.py used by _replace_variable (keyed by the
match group string) to store the resolved string/value so that on subsequent
matches you return the cached result instead of calling
self._canvas.get_variable_value again; ensure you still handle None, partial
(consume it once and cache the resulting string), call
self._stringify_message_value for non-partial values, and preserve the existing
exception handling and fallback behavior.

@codecov

codecov Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.66%. Comparing base (f906a20) to head (cb2ff0d).
⚠️ Report is 24 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14180   +/-   ##
=======================================
  Coverage   96.66%   96.66%           
=======================================
  Files          10       10           
  Lines         690      690           
  Branches      108      108           
=======================================
  Hits          667      667           
  Misses          8        8           
  Partials       15       15           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
agent/component/invoke.py (1)

127-127: Minor inconsistency: str(value) vs _stringify_message_value.

The docs_generator.py implementation uses self._stringify_message_value(var_value, fallback_to_str=True) which may handle complex types (lists, dicts) differently than str(value). For HTTP request contexts this may be acceptable, but consider whether consistent behavior across components is desired.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@agent/component/invoke.py` at line 127, The current return uses plain
str(value) which is inconsistent with docs_generator.py and may handle complex
types differently; replace the direct str(value) in agent/component/invoke.py
with a call to the existing helper self._stringify_message_value(value,
fallback_to_str=True) (or ensure you use that helper from the same class/module)
so serialization of lists/dicts and other complex types matches
docs_generator.py's behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@agent/component/invoke.py`:
- Line 118: The code uses kwargs.get(match,
self._canvas.get_variable_value(match)) which evaluates get_variable_value()
even when match is present in kwargs, causing exceptions; change the logic to
check membership first (e.g., if match in kwargs: value = kwargs[match] else:
value = self._canvas.get_variable_value(match)) or retrieve with
kwargs.get(match) and call _canvas.get_variable_value(match) only when that
result is None, updating the assignment around the value variable accordingly.

---

Nitpick comments:
In `@agent/component/invoke.py`:
- Line 127: The current return uses plain str(value) which is inconsistent with
docs_generator.py and may handle complex types differently; replace the direct
str(value) in agent/component/invoke.py with a call to the existing helper
self._stringify_message_value(value, fallback_to_str=True) (or ensure you use
that helper from the same class/module) so serialization of lists/dicts and
other complex types matches docs_generator.py's behavior.
🪄 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: d2e25f94-05a8-4dbc-9f60-324026a4125b

📥 Commits

Reviewing files that changed from the base of the PR and between 63d89d4 and 4de3fd3.

📒 Files selected for processing (1)
  • agent/component/invoke.py

Comment thread agent/component/invoke.py Outdated
def replace_variable(match_obj):
match = match_obj.group(1)
try:
value = kwargs.get(match, self._canvas.get_variable_value(match))

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.

⚠️ Potential issue | 🟠 Major

Bug: kwargs.get() with exception-raising default causes incorrect behavior.

Python evaluates the default argument before dict.get() checks if the key exists. Since get_variable_value raises an exception when a component is not found (see agent/canvas.py:201), this will raise an exception even when match is present in kwargs, causing the exception handler to return [ERROR: ...] instead of the actual kwargs value.

🐛 Proposed fix
-                value = kwargs.get(match, self._canvas.get_variable_value(match))
+                if match in kwargs:
+                    value = kwargs[match]
+                else:
+                    value = self._canvas.get_variable_value(match)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
value = kwargs.get(match, self._canvas.get_variable_value(match))
if match in kwargs:
value = kwargs[match]
else:
value = self._canvas.get_variable_value(match)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@agent/component/invoke.py` at line 118, The code uses kwargs.get(match,
self._canvas.get_variable_value(match)) which evaluates get_variable_value()
even when match is present in kwargs, causing exceptions; change the logic to
check membership first (e.g., if match in kwargs: value = kwargs[match] else:
value = self._canvas.get_variable_value(match)) or retrieve with
kwargs.get(match) and call _canvas.get_variable_value(match) only when that
result is None, updating the assignment around the value variable accordingly.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Apr 20, 2026
@asiroliu
asiroliu merged commit d053317 into infiniflow:main Apr 20, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 20, 2026
JasleenKaurSethi pushed a commit to stackhpc/ragflow that referenced this pull request Apr 28, 2026
### What problem does this PR solve?

Fix: variable in doc generator

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants