Repository navigation
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughA new ChangesLLM Request Context Propagation
Estimated code review effort: 3 (Moderate) | ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 3
🤖 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/canvas.py`:
- Around line 381-395: The request context set in canvas.run() is not
propagating into worker threads used by _run_impl() via loop.run_in_executor(),
so LiteLLM calls can lose the session/user forwarding. Update the execution path
around _run_impl() and _run_batch() so the current context is explicitly carried
into the thread pool (for example by capturing and running the callable inside
the copied context) before cpn.invoke() is executed, while keeping the existing
reset_llm_request_context() cleanup in run().
In `@common/llm_request_context.py`:
- Around line 34-54: The new request-context helpers are silent, so add
helper-level logging in set_llm_request_context and reset_llm_request_context to
make context install/reset and the ValueError fallback traceable. Log at debug
for successful install/reset and warning for the failed-reset fallback, but do
not include raw session_id or user_id values; use the function names and the
llm_request_context ContextVar to locate the changes.
In `@rag/llm/chat_model.py`:
- Around line 2073-2080: The `chat_model.py` `completion_args["user"]`
precedence check is using truthiness, so a caller-supplied empty string can be
overwritten by `current_llm_user()`. Update the logic around
`current_llm_user()` to test for key presence in `completion_args` instead of
`get("user")` truthiness, so any explicit `user` override from the caller is
preserved exactly as provided.
🪄 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: 4db19322-fe62-4da5-b0e7-9fa3afccea95
📒 Files selected for processing (4)
agent/canvas.pyapi/db/services/canvas_service.pycommon/llm_request_context.pyrag/llm/chat_model.py
78db4e9 to
f86a0e7
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/canvas.py`:
- Around line 459-463: The debug logging in Canvas methods is serializing raw
workflow payloads, including inputs, component arguments, outputs, and error
text, which should not be emitted. Update the logging in the Canvas flow paths
(including the workflow start and the other affected debug sites) to log only
safe metadata such as component names, counts, keys, or status fields, and avoid
passing full dictionaries or json.dumps of user content. Keep the observability
for the new flow by using the existing _logger debug calls in Canvas, but guard
them so they only include non-sensitive summaries instead of raw payload values.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 1
🤖 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/canvas.py`:
- Around line 459-463: The debug logging in Canvas methods is serializing raw
workflow payloads, including inputs, component arguments, outputs, and error
text, which should not be emitted. Update the logging in the Canvas flow paths
(including the workflow start and the other affected debug sites) to log only
safe metadata such as component names, counts, keys, or status fields, and avoid
passing full dictionaries or json.dumps of user content. Keep the observability
for the new flow by using the existing _logger debug calls in Canvas, but guard
them so they only include non-sensitive summaries instead of raw payload values.
🪄 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: 075365ac-01be-42fa-adf9-d08febe2913a
📒 Files selected for processing (1)
agent/canvas.py
🛑 Comments failed to post (1)
agent/canvas.py (1)
459-463: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Avoid logging raw workflow and component payloads.
These debug logs serialize inputs, component arguments, outputs, and error text. Those values can contain user prompts, document text, file metadata, or secrets, and
json.dumps(... )[:500]still materializes the full payload before truncation. Log metadata/keys instead, guarded behind debug checks.Safer logging shape
- _logger.debug( - "[Canvas] Workflow started. Path: %s, Inputs: %s", - [self.get_component_name(c) for c in self.path], - json.dumps(kwargs.get("inputs", {}), ensure_ascii=False, default=str)[:500], - ) + if _logger.isEnabledFor(logging.DEBUG): + inputs = kwargs.get("inputs") or {} + input_summary = list(inputs.keys())[:20] if isinstance(inputs, dict) else type(inputs).__name__ + _logger.debug( + "[Canvas] Workflow started. Path: %s, Input summary: %s", + [self.get_component_name(c) for c in self.path], + input_summary, + ) @@ - _logger.debug( - "[Canvas] Invoking component '%s' (%s) with inputs: %s", - self.get_component_name(self.path[i - 1]), - cpn.component_name, - json.dumps(call_kwargs, ensure_ascii=False, default=str)[:500], - ) + if _logger.isEnabledFor(logging.DEBUG): + input_summary = list(call_kwargs.keys())[:20] if isinstance(call_kwargs, dict) else type(call_kwargs).__name__ + _logger.debug( + "[Canvas] Invoking component '%s' (%s) with input summary: %s", + self.get_component_name(self.path[i - 1]), + cpn.component_name, + input_summary, + ) @@ - _logger.debug( - "[Canvas] Component '%s' (%s) finished. Outputs: %s, Error: %s", - self.get_component_name(cpn_obj._id), - self.get_component_type(cpn_obj._id), - json.dumps(outputs, ensure_ascii=False, default=str)[:500], - cpn_obj.error(), - ) + if _logger.isEnabledFor(logging.DEBUG): + output_summary = list(outputs.keys())[:20] if isinstance(outputs, dict) else type(outputs).__name__ + _logger.debug( + "[Canvas] Component '%s' (%s) finished. Output summary: %s, Has error: %s", + self.get_component_name(cpn_obj._id), + self.get_component_type(cpn_obj._id), + output_summary, + bool(cpn_obj.error()), + )This keeps the new-flow observability without emitting raw payloads. As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 513-518, 529-535
🧰 Tools
🪛 ast-grep (0.44.0)
[info] 461-461: use jsonify instead of json.dumps for JSON output
Context: json.dumps(kwargs.get("inputs", {}), ensure_ascii=False, default=str)
Note: [CWE-116] Improper Encoding or Escaping of Output.(use-jsonify)
🤖 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 459 - 463, The debug logging in Canvas methods is serializing raw workflow payloads, including inputs, component arguments, outputs, and error text, which should not be emitted. Update the logging in the Canvas flow paths (including the workflow start and the other affected debug sites) to log only safe metadata such as component names, counts, keys, or status fields, and avoid passing full dictionaries or json.dumps of user content. Keep the observability for the new flow by using the existing _logger debug calls in Canvas, but guard them so they only include non-sensitive summaries instead of raw payload values.Source: Coding guidelines
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
agent/canvas.py (1)
126-143: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winNarrow the
deepcopyfallbacks inagent/canvas.py:128,141.except Exceptiontriggers Ruff BLE001 here; catch the specific copy/serialization errors you expect, or add# noqa: BLE001with a short rationale if the blanket fallback is intentional.🤖 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 126 - 143, The broad exception handlers around the deepcopy fallbacks in Graph.__str__ are too generic and trigger BLE001. Update the two try/except blocks that copy dsl[k] and cpn[c] to catch only the specific copy/serialization errors you expect, or add a targeted noqa comment with a brief rationale if the blanket fallback is intentional. Keep the existing warning behavior and shallow-reference fallback in place.Sources: Coding guidelines, Linters/SAST tools
🧹 Nitpick comments (1)
agent/canvas.py (1)
397-409: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd non-sensitive logging for the new context lifecycle.
This new per-run LLM context flow has no log signal. Add debug-level logs using presence flags only; avoid logging raw
session_id/user_id.As per coding guidelines,
**/*.py: Add logging for new flows.Suggested logging shape
async def run(self, **kwargs): + session_id = kwargs.get("session_id") + user_id = kwargs.get("user_id") + logging.debug( + "Canvas.run: installing LLM request context (has_session_id=%s, has_user_id=%s)", + session_id is not None, + user_id is not None, + ) _req_ctx_token = set_llm_request_context( - session_id=kwargs.get("session_id"), - user_id=kwargs.get("user_id"), + session_id=session_id, + user_id=user_id, ) try: async for ev in self._run_impl(**kwargs): yield ev finally: reset_llm_request_context(_req_ctx_token) + logging.debug("Canvas.run: reset LLM request context")🤖 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 397 - 409, Add debug-level logging around the new per-run LLM context lifecycle in run: log when the context is being set and when it is reset, but only using presence flags (for example, whether session_id/user_id were provided) and never the raw values. Place the logs near set_llm_request_context and reset_llm_request_context so the flow is traceable, and keep the logging non-sensitive and minimal.Source: Coding guidelines
🤖 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.
Outside diff comments:
In `@agent/canvas.py`:
- Around line 126-143: The broad exception handlers around the deepcopy
fallbacks in Graph.__str__ are too generic and trigger BLE001. Update the two
try/except blocks that copy dsl[k] and cpn[c] to catch only the specific
copy/serialization errors you expect, or add a targeted noqa comment with a
brief rationale if the blanket fallback is intentional. Keep the existing
warning behavior and shallow-reference fallback in place.
---
Nitpick comments:
In `@agent/canvas.py`:
- Around line 397-409: Add debug-level logging around the new per-run LLM
context lifecycle in run: log when the context is being set and when it is
reset, but only using presence flags (for example, whether session_id/user_id
were provided) and never the raw values. Place the logs near
set_llm_request_context and reset_llm_request_context so the flow is traceable,
and keep the logging non-sensitive and minimal.
There was a problem hiding this comment.
Pull request overview
This PR adds run-scoped propagation of the originating session_id (falling back to user_id) into upstream LLM provider requests using the OpenAI-standard user field, enabling provider-side logs/analytics to be correlated back to the originating chat session/user.
Changes:
- Introduces a
ContextVar-backed request context (session_id/user_id) with helpers to set/reset it and compute the forwardeduser. - Wraps
Canvas.run()to install/reset the context for the duration of an agent run, and propagates context into thread-pool executed sync components. - Populates LiteLLM provider call arguments with the
userfield from the active context (unless the caller explicitly supplieduser), and forwardssession_idinto canvas run kwargs from the API layer.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
rag/llm/chat_model.py |
Adds user field injection into LiteLLM completion args based on the active LLM request context (caller override preserved). |
common/llm_request_context.py |
New module providing a ContextVar for {session_id, user_id} and helpers to set/reset and compute the forwarded user. |
api/db/services/canvas_service.py |
Passes session_id into the agent run kwargs so the agent run can install the request context. |
agent/canvas.py |
Installs/resets LLM request context for the run, and copies contextvars into worker threads for sync component execution. |
Install a run-scoped ContextVar in Canvas.run and populate LiteLLM completion args with the OpenAI-standard user field so upstream providers can correlate requests back to the originating session or user. - common/llm_request_context.py: set/reset helpers and current_llm_user() - agent/canvas.py: install context for the run and copy it into sync executor threads - rag/llm/chat_model.py: honor explicit caller user overrides by key presence - test/unit_test/common/test_llm_request_context.py: precedence and lifecycle coverage Co-authored-by: Cursor <[email protected]>
4ecc7df to
d2833bf
Compare
|
Closing as superseded by #16502, which already includes this session/user forwarding change (plus additional review fixes and unit tests). No further action needed here. |
What problem does this PR solve?
Today, when an agent run calls an upstream LLM provider, the request carries no
identifier tying it back to the chat session that produced it. As a result,
provider-side activity (for example OpenRouter's request logs / analytics, or
OpenAI's abuse monitoring) cannot be correlated with the originating session or
user.
This PR forwards the originating
session_id(falling back touser_id) to theprovider using the OpenAI-standard
userrequest field, which OpenAI- andOpenRouter-compatible backends include in the request body.
Type of change
How it works
common/llm_request_context.py(new) — aContextVarthat holds theper-request
{session_id, user_id}, withset/resethelpers andcurrent_llm_user()(preferssession_id, falls back touser_id).agent/canvas.py—Canvas.run()installs the request context for theduration of the run and resets it in a
finally(so it never leaks to latercalls in the same task). The original body is delegated to
_run_impl().rag/llm/chat_model.py—LiteLLMBase._construct_completion_argssets theuserfield from the active request context. This is the single point allLiteLLM provider calls (OpenAI, OpenRouter, Anthropic, Gemini, DeepSeek, …) go
through, so it covers plain, streaming and tool-calling paths. A
caller-supplied
userstill takes precedence.api/db/services/canvas_service.py— forwardssession_idinto the runkwargs.
Why a ContextVar
LLM calls in an agent run originate from many places that each build their own
LLMBundle(e.g. cross-language translation / keyword helpers, the Agentcomponent, and nested sub-agents). A run-scoped
ContextVaris the least-invasiveway to make the originating identifier available at the single provider chokepoint
without threading it through every call signature. Nested agents run in the same
async context and thread-pool tools inherit a copied context, so they are covered
too.
Behavior / compatibility
userfield is added tothe provider request when a session/user is known.
unchanged.
userfield are unaffected.Notes
case. The same
set_llm_request_context(...)helper can be wired into thedialog/chat path in a follow-up if desired.