Skip to content

feat(llm): forward session/user to upstream providers as the user field - #16429

Closed
ondery wants to merge 7 commits into
infiniflow:mainfrom
ondery:feat/forward-session-to-llm
Closed

ondery wants to merge 7 commits into
infiniflow:mainfrom
ondery:feat/forward-session-to-llm

Conversation

@ondery

@ondery ondery commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

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 to user_id) to the
provider using the OpenAI-standard user request field, which OpenAI- and
OpenRouter-compatible backends include in the request body.

Type of change

  • New Feature (non-breaking change which adds functionality)

How it works

  1. common/llm_request_context.py (new) — a ContextVar that holds the
    per-request {session_id, user_id}, with set/reset helpers and
    current_llm_user() (prefers session_id, falls back to user_id).
  2. agent/canvas.py — Canvas.run() installs the request context for the
    duration of the run and resets it in a finally (so it never leaks to later
    calls in the same task). The original body is delegated to _run_impl().
  3. rag/llm/chat_model.py — LiteLLMBase._construct_completion_args sets the
    user field from the active request context. This is the single point all
    LiteLLM provider calls (OpenAI, OpenRouter, Anthropic, Gemini, DeepSeek, …) go
    through, so it covers plain, streaming and tool-calling paths. A
    caller-supplied user still takes precedence.
  4. api/db/services/canvas_service.py — forwards session_id into the run
    kwargs.

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 Agent
component, and nested sub-agents). A run-scoped ContextVar is the least-invasive
way 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

  • No wire-format or API change for clients; only an extra user field is added to
    the provider request when a session/user is known.
  • If no request context is active (non-agent flows, background jobs), behavior is
    unchanged.
  • Providers that ignore the user field are unaffected.

Notes

  • Scope is intentionally limited to the agent (canvas) path, which is the common
    case. The same set_llm_request_context(...) helper can be wired into the
    dialog/chat path in a follow-up if desired.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 28, 2026
@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

A new common/llm_request_context.py module uses Python contextvars to carry session_id and user_id per canvas run. Canvas.run now sets and resets that context while propagating it into executor threads, canvas_service.completion forwards session_id, and LiteLLMBase uses the active context to populate the outgoing user field.

Changes

LLM Request Context Propagation

Layer / File(s) Summary
llm_request_context module
common/llm_request_context.py
Defines the request context variable plus helpers to set, reset, and read the active upstream user identifier.
Canvas context lifecycle and session forwarding
agent/canvas.py, api/db/services/canvas_service.py
Canvas.run installs request context, streams through _run_impl, resets in finally, propagates context into executor threads, and completion(...) forwards session_id into run_kwargs.
LiteLLM user field population
rag/llm/chat_model.py
LiteLLMBase._construct_completion_args conditionally sets completion_args["user"] from current_llm_user() when no user key is already present.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Poem

A rabbit hops through context threads,
Carrying session IDs with care;
From canvas run to LLM beds,
The user field lands right there 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: forwarding session/user identifiers to upstream providers as the user field.
Description check ✅ Passed The description includes the problem, context, how it works, compatibility notes, and scope, which satisfies and exceeds the template's summary requirement.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

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

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 08c807a and 3577cb2.

📒 Files selected for processing (4)
  • agent/canvas.py
  • api/db/services/canvas_service.py
  • common/llm_request_context.py
  • rag/llm/chat_model.py

Comment thread agent/canvas.py Resolved
Comment thread common/llm_request_context.py Resolved
Comment thread rag/llm/chat_model.py Resolved
@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 Jun 28, 2026
@yuzhichang
yuzhichang force-pushed the main branch 2 times, most recently from 78db4e9 to f86a0e7 Compare June 29, 2026 01:47

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2cf03a3 and d77675d.

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

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2cf03a3 and d77675d.

📒 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

Copilot AI review requested due to automatic review settings July 1, 2026 06:44

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

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 win

Narrow the deepcopy fallbacks in agent/canvas.py:128,141. except Exception triggers Ruff BLE001 here; catch the specific copy/serialization errors you expect, or add # noqa: BLE001 with 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 win

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b13e567b-c245-4c55-92f9-c22b00ef2a7d

📥 Commits

Reviewing files that changed from the base of the PR and between 4977842 and 49ea733.

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

Copilot AI 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.

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 forwarded user.
  • 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 user field from the active context (unless the caller explicitly supplied user), and forwards session_id into 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.

Comment thread rag/llm/chat_model.py Resolved

Copilot AI 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.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Comment thread common/llm_request_context.py Resolved
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 2, 2026
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]>
@ondery
ondery force-pushed the feat/forward-session-to-llm branch from 4ecc7df to d2833bf Compare July 7, 2026 07:20
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 7, 2026
@ondery

ondery commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

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.

@ondery ondery closed this Jul 7, 2026
@ondery
ondery deleted the feat/forward-session-to-llm branch July 7, 2026 12:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

💞 feature Feature request, pull request that fullfill a new feature. 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