Skip to content

feat(agent): report accurate aggregated token usage and propagate session/user + input/output to Langfuse for agent runs - #16420

Merged
yuzhichang merged 15 commits into
infiniflow:mainfrom
ondery:main
Jul 2, 2026

Conversation

@ondery

@ondery ondery commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Briefly describe what this PR aims to solve. Include background context that will help reviewers understand the purpose of the PR.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Other (please describe):

Summary

Agent (Canvas) runs previously did not surface token usage in the SSE stream, and RAGFlow's own Langfuse generations for agent runs were missing the prompt/completion split and the session/user correlation. This made it impossible for an external caller (or Langfuse) to reconcile an agent turn's cost with the upstream provider (e.g. OpenRouter), because a single turn can issue several distinct LLM calls (query rewriting / cross-language translation, multi-round tool reasoning, nested sub-agents, and the final answer).

This PR introduces a per-run token usage sink so that every LLM call in a run is aggregated and reported once, and enriches Langfuse generations with the prompt/completion split plus session/user attributes.

What changes

1. Per-run token usage sink (common/token_utils.py)

  • Adds two contextvars: token_usage_sink (a mutable per-run accumulator) and langfuse_run_attrs (session_id/user_id for the run).
  • Adds record_run_token_usage(...) (thread-safe via a lock, because thread_pool_exec copies the context into worker threads that share the sink dict) and usage_from_response(...) which extracts a {prompt_tokens, completion_tokens, total_tokens} split from OpenAI/OpenRouter-style responses.

2. Provider layer captures the prompt/completion split (rag/llm/chat_model.py)

  • LiteLLMBase and Base now store self.last_usage (prompt/completion/total) for the most recent chat call, in both the plain and tool-calling paths.
  • Streaming requests set stream_options.include_usage = True (LiteLLM path) so the authoritative usage arrives on the final chunk; this is read even on the usage-only chunk that carries no choices.
  • Fixes a multi-round accounting bug in *_with_tools: token totals were overwritten by each round (total_tokens = tol) instead of accumulated, undercounting multi-round tool conversations. Each round is now committed to a running aggregate.

3. LLMBundle reports usage once, per call (api/db/services/llm_service.py)

  • New _report_usage(total_tokens) records the call's usage into the active run sink and returns the prompt/completion/total split for Langfuse. The split is only used when it is consistent with the authoritative total; otherwise only the total is reported.
  • All three chat entry points (async_chat, async_chat_streamly, async_chat_streamly_delta) now emit usage_details with input/output/total instead of total-only.
  • _start_langfuse_observation now applies session_id/user_id from the per-run context (langfuse_run_attrs) so agent-run generations are correctly grouped, even though agent LLMBundles are constructed without those attributes.

4. Canvas installs the sink and emits the aggregate (agent/canvas.py)

  • Canvas.run() installs a fresh token_usage_sink and langfuse_run_attrs (from user_id/session_id) at the start of every turn.
  • message_end now includes an aggregated usage object: {prompt_tokens, completion_tokens, total_tokens, calls} covering all LLM calls in the run.

5. Pass session id into the run (api/db/services/canvas_service.py)

  • completion() forwards session_id to Canvas.run() for Langfuse session correlation.

Why a context variable

LLM calls in an agent run originate from many places that each build their own LLMBundle (e.g. cross_languages/keyword_extraction helpers, the Agent component, and nested sub-agents invoked as tools). A run-scoped context variable is the only non-invasive chokepoint that captures all of them exactly once, including nested agents (which run in the same async context) and thread-pool tools (the executor copies the context).

Behavior / compatibility

  • No public API or wire-format removal: message_end gains an additional optional usage field; existing consumers are unaffected.
  • When a provider does not return authoritative usage, behavior falls back to the previous token estimate (total only, no split).
  • Non-agent flows (Dataflow Pipeline, sync Graph.run) are untouched.

Testing

  • Simple agent answer: message_end.usage.total_tokens matches provider usage.
  • Agent with cross-language retrieval: aggregate equals the sum of both provider calls.
  • Tool-calling agent (multi-round): total accumulates across rounds.
  • Nested agent (agent-as-tool): sub-agent tokens included in the parent run total.
  • Langfuse: agent generations show input/output split and are grouped by session/user.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 💞 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

Adds per-run token aggregation with shared context state, updates chat model usage tracking, normalizes Langfuse reporting, installs run context in canvas execution, and forwards aggregated usage through agent completion events.

Changes

Token Usage Tracking and Langfuse Attribution

Layer / File(s) Summary
Context-variable token sink
common/token_utils.py
Adds context variables for per-run token aggregation and Langfuse run attributes, a lock for sink updates, a token usage accumulator, and response usage normalization helpers.
OpenAI-style usage aggregation
rag/llm/chat_model.py
Initializes last_usage on the OpenAI-style client, resets streaming state, captures provider usage on non-stream calls, and aggregates usage across tool-calling and streaming rounds.
LiteLLM usage aggregation
rag/llm/chat_model.py
Initializes last_usage on the LiteLLM client, resets streaming state, requests authoritative stream usage, and aggregates usage across tool-calling and streaming rounds.
Langfuse usage reporting
api/db/services/llm_service.py
Propagates session and user attributes into Langfuse observations, resets stale model usage before calls, and replaces direct token totals with normalized usage payloads in chat and streaming methods.
Canvas run context and totals
agent/canvas.py, api/db/services/canvas_service.py
Installs per-run token and Langfuse context in Canvas.run(), propagates sync executor context, emits aggregated usage on terminal workflow_finished events, and passes session_id into canvas completion runs.
Completion event usage forwarding
api/apps/restful_apis/agent_api.py
Includes workflow_finished in the completion event filter, captures its usage separately in non-streaming completion aggregation, and attaches that usage to the final response payload.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 I hopped through tokens, one by one,
A run-wide tally now is spun.
The canvas hums, the sessions glow,
And Langfuse sees the usage flow.
With twitchy ears and carrot cheer,
I count the bytes and save them here!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.82% 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 clearly summarizes the main change: aggregated token usage reporting and Langfuse session/user propagation for agent runs.
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.
Description check ✅ Passed The PR description follows and exceeds the repository template with clear summary, context, change details, compatibility notes, and testing.

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

🧹 Nitpick comments (1)
common/token_utils.py (1)

65-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log token aggregation failures instead of silently swallowing them.

A malformed sink or unexpected token value currently disables run usage tracking with no trace. Add low-volume debug logging in this exception path.

Proposed fix
+import logging
 import contextvars
 import os
 import threading
...
-    except Exception:
-        pass
+    except Exception:
+        logging.debug("Failed to record run token usage", exc_info=True)

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@common/token_utils.py` around lines 65 - 66, The token aggregation logic in
token_utils is silently swallowing unexpected errors, which hides malformed sink
or token value issues and disables usage tracking without any trace. Update the
except Exception path to emit low-volume debug logging with enough context to
identify the failing aggregation/input, then keep the fallback behavior
unchanged so the flow still degrades safely. Use the existing token aggregation
helper in common/token_utils and add logging consistent with the Python logging
guidelines for new flows.

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.

Inline comments:
In `@agent/canvas.py`:
- Around line 887-895: The run-scoped usage in _build_message_end() is being
attached to every message_end event, which can cause cumulative double counting
across multi-message graphs. Update the usage emission logic in
Canvas._build_message_end so it only includes _run_token_usage on a single final
event, or move this data to a dedicated run-level payload; use the existing
_run_token_usage and message_end handling to locate the change.
- Around line 388-391: The run aggregate is missing token usage from sync
executor work because `run_in_executor` drops the current context. Update the
executor path in `canvas.py` so the callable submitted from the run setup
inherits the active context, using `contextvars.copy_context().run(...)` around
the target (or switching that path to `asyncio.to_thread`) so `token_usage_sink`
and `langfuse_run_attrs` remain available to LLMBundle calls inside sync
components.
- Around line 388-401: Reset the run-scoped ContextVars in Canvas.run when the
stream finishes by storing the tokens returned from token_usage_sink.set(...)
and langfuse_run_attrs.set(...), then resetting both in a finally block. This
fixes the stale per-run state so later LLM calls in the same request do not keep
writing into the previous _run_token_usage or inherit old user_id/session_id
values. Use the existing Canvas.run setup around token_usage_sink and
langfuse_run_attrs as the place to make the change.

In `@rag/llm/chat_model.py`:
- Around line 427-428: The Base tool-call paths are still discarding the
prompt/completion usage split and only storing totals in last_usage. Update the
non-streaming and streaming branches in chat_model.py’s Base tool-call handling
to use usage_from_response(response) for the normal response path, and enable
stream_options.include_usage for the streaming path instead of estimating from
deltas. Make sure the affected tool-call flow methods and the last_usage
assignment preserve prompt_tokens, completion_tokens, and total_tokens
consistently.

---

Nitpick comments:
In `@common/token_utils.py`:
- Around line 65-66: The token aggregation logic in token_utils is silently
swallowing unexpected errors, which hides malformed sink or token value issues
and disables usage tracking without any trace. Update the except Exception path
to emit low-volume debug logging with enough context to identify the failing
aggregation/input, then keep the fallback behavior unchanged so the flow still
degrades safely. Use the existing token aggregation helper in common/token_utils
and add logging consistent with the Python logging guidelines for new flows.
🪄 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: b5444b85-3ca5-490b-bb59-5e972dbb74a4

📥 Commits

Reviewing files that changed from the base of the PR and between f90be41 and c955988.

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

Comment thread agent/canvas.py Resolved
Comment thread agent/canvas.py Resolved
Comment thread agent/canvas.py Resolved
Comment thread api/db/services/llm_service.py Resolved
Comment thread rag/llm/chat_model.py Resolved
@ondery

ondery commented Jun 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @coderabbitai 🙏 — all five actionable comments plus the nitpick are addressed (replies inline on each thread). Summary:

  1. run_in_executor context loss — sync components now run inside a copied context (contextvars.copy_context().run(...)), so the usage sink / Langfuse attrs propagate.
  2. Run-scoped ContextVars not reset — run() now sets them with reset tokens and tears them down in a finally, always installing a fresh (empty-ok) context per run.
  3. Cumulative usage on every message_end — moved to a single run-level payload on workflow_finished (forwarded through the session path).
  4. Stale last_usage — added _reset_last_usage() called before every chat/stream invocation.
  5. Base tool-call split — non-streaming now keeps the prompt/completion split; streaming captures it opportunistically (rationale on the thread re: not forcing stream_options.include_usage on the raw client).
  6. Nitpick — silent failure in record_run_token_usage — now logs at debug with exc_info while preserving the safe fallback.

@coderabbitai

coderabbitai Bot commented Jun 28, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@ondery Thanks for the detailed follow-up — these changes address the concerns I raised. The context propagation, per-run ContextVar cleanup, run-level usage emission, last_usage reset, and the safer usage accounting/logging all sound good.

🐇✨


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
rag/llm/chat_model.py (3)

559-573: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Include reasoning deltas in fallback token estimates.

When provider usage is absent, reasoning chunks yield _reasoning, but the fallback estimate only counts delta.content, which is often empty for reasoning deltas.

Proposed fix
-                        if not _u["total_tokens"]:
-                            round_estimate += num_tokens_from_string(delta.content)
+                        if not _u["total_tokens"]:
+                            round_estimate += num_tokens_from_string(_reasoning or delta.content)
🤖 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 `@rag/llm/chat_model.py` around lines 559 - 573, The fallback token estimate in
the streaming branch of chat_model.py is skipping reasoning-only chunks because
it only counts delta.content. Update the logic around the _reasoning handling in
the streaming loop to include reasoning text when usage data is missing, so
round_estimate reflects both delta.content and the reasoning delta source used
to build the emitted <think> block.

224-260: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Preserve authoritative usage in this streaming path. Usage-only final chunks are skipped here, so last_usage stays zero and the method keeps returning estimated totals instead of the provider’s split/usage values. Mirror the handling used in the later streaming implementation and read usage_from_response(resp) before the choices guard.

🤖 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 `@rag/llm/chat_model.py` around lines 224 - 260, The streaming path in
async_chat_streamly is ignoring provider usage on final usage-only chunks, so
last_usage stays zero and estimated token totals are returned instead of
authoritative values. Update the streaming loop in async_chat_streamly to read
usage_from_response(resp) before the choices check, and when usage is present,
populate self.last_usage from it and avoid skipping that chunk; mirror the
handling used in the later streaming implementation so split usage values are
preserved.

174-176: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Avoid sharing last_usage across overlapping calls LLMBundle._report_usage() reads mutable instance state after the await, so concurrent calls on the same model instance can report the wrong prompt/completion split. Thread the usage through the return value or keep the bundle run-scoped.

🤖 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 `@rag/llm/chat_model.py` around lines 174 - 176, The mutable last_usage state
on ChatModel is shared across overlapping chat calls, which can cause
LLMBundle._report_usage() to read the wrong token split after await. Update the
ChatModel chat path so usage is returned with each call instead of stored on the
instance, and adjust LLMBundle and any related call sites to consume that
per-call usage data; use the ChatModel and LLMBundle._report_usage symbols to
locate the affected flow.
🤖 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 405-415: The cleanup fallback in the finally block silently clears
ContextVar state when reset() raises ValueError, so add debug logging with
exc_info=True before the fallback set(None) calls. Update the exception handlers
around token_usage_sink.reset(sink_token) and
langfuse_run_attrs.reset(attrs_token) in canvas.py to log the reset failure
context so disconnect/finalization attribution gaps are traceable. Keep the
existing fallback behavior, but make the fallback path observable through debug
logs.

In `@api/apps/restful_apis/agent_api.py`:
- Around line 559-562: The streaming filter in agent_api.py is forwarding the
entire workflow_finished payload via the event handling around yield ans, which
exposes Canvas.workflow_finished internals. Update the workflow_finished branch
to emit only a sanitized run-level usage payload, preserving message/message_end
behavior while stripping data.inputs and full data.outputs from the completion
stream.

---

Outside diff comments:
In `@rag/llm/chat_model.py`:
- Around line 559-573: The fallback token estimate in the streaming branch of
chat_model.py is skipping reasoning-only chunks because it only counts
delta.content. Update the logic around the _reasoning handling in the streaming
loop to include reasoning text when usage data is missing, so round_estimate
reflects both delta.content and the reasoning delta source used to build the
emitted <think> block.
- Around line 224-260: The streaming path in async_chat_streamly is ignoring
provider usage on final usage-only chunks, so last_usage stays zero and
estimated token totals are returned instead of authoritative values. Update the
streaming loop in async_chat_streamly to read usage_from_response(resp) before
the choices check, and when usage is present, populate self.last_usage from it
and avoid skipping that chunk; mirror the handling used in the later streaming
implementation so split usage values are preserved.
- Around line 174-176: The mutable last_usage state on ChatModel is shared
across overlapping chat calls, which can cause LLMBundle._report_usage() to read
the wrong token split after await. Update the ChatModel chat path so usage is
returned with each call instead of stored on the instance, and adjust LLMBundle
and any related call sites to consume that per-call usage data; use the
ChatModel and LLMBundle._report_usage symbols to locate the affected flow.
🪄 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: 2500281f-1bde-4403-ab17-f05914f55cd2

📥 Commits

Reviewing files that changed from the base of the PR and between c955988 and 3e88ed5.

📒 Files selected for processing (5)
  • agent/canvas.py
  • api/apps/restful_apis/agent_api.py
  • api/db/services/llm_service.py
  • common/token_utils.py
  • rag/llm/chat_model.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • common/token_utils.py
  • api/db/services/llm_service.py

Comment thread agent/canvas.py Resolved
Comment thread api/apps/restful_apis/agent_api.py Resolved
@yuzhichang
yuzhichang force-pushed the main branch 2 times, most recently from 78db4e9 to f86a0e7 Compare June 29, 2026 01:47
@yuzhichang
yuzhichang requested review from Copilot and yuzhichang July 1, 2026 02:55
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 1, 2026

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 token accounting for Agent (Canvas) executions so that token usage from all underlying LLM calls in a single agent turn is aggregated and reported once, and improves Langfuse correlation/usage reporting (prompt vs completion split + session/user propagation) for agent runs.

Changes:

  • Introduces contextvar-based per-run usage accumulation (token_usage_sink) plus a helper to extract prompt/completion/total usage from provider responses.
  • Captures prompt/completion/total usage in the provider layer (including streaming + multi-round tool loops) and reports it via LLMBundle to both Langfuse and the active run sink.
  • Installs the per-run sink/attrs in Canvas.run() and emits aggregated usage on the terminal event; forwards session_id into Canvas runs for correct Langfuse grouping.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
rag/llm/chat_model.py Captures and aggregates per-call usage (incl. streaming and multi-round tool calls) into last_usage.
common/token_utils.py Adds run-scoped contextvars, sink recording, and usage_from_response() extraction helper.
api/db/services/llm_service.py Records per-call usage into the run sink and enriches Langfuse usage_details + session/user propagation.
api/db/services/canvas_service.py Passes session_id into Canvas.run() for run-level correlation.
api/apps/restful_apis/agent_api.py Attempts to forward only run-level usage for workflow_finished in session completion flows and attaches usage to non-stream final response.
agent/canvas.py Installs/reset run-scoped sink/attrs, propagates context into executor threads, and emits aggregated run usage on workflow_finished.

Comment thread api/apps/restful_apis/agent_api.py Resolved
Comment thread agent/canvas.py Resolved
Comment thread agent/canvas.py Resolved
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).

Co-authored-by: yzc <[email protected]>

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 1, 2026
@yuzhichang yuzhichang added the ci Continue Integration label Jul 1, 2026
ondery and others added 4 commits July 1, 2026 09:22
…code)

Copilot review: in the streaming session-completion path, "workflow_finished"
was listed in the broad `event in [...]` branch that does `yield ans; continue`,
so the dedicated block that forwards only the aggregated usage (stripping the
terminal inputs/outputs payload) was unreachable. The full workflow_finished
payload was therefore streamed, contradicting the code's own comment.

Drop "workflow_finished" from the broad branch so it falls through to the
usage-only block, which now also logs and continues. message/message_end/
user_inputs behaviour is unchanged.

Co-authored-by: Cursor <[email protected]>
@codecov

codecov Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (42a0faa) to head (6a0b040).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16420   +/-   ##
=======================================
  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.
📢 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.

@yuzhichang
yuzhichang merged commit 742188c into infiniflow:main Jul 2, 2026
3 checks passed
JinHai-CN pushed a commit that referenced this pull request Jul 2, 2026
### Summary

Port the following PRs to GO in this PR

#16420
#13295
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
### Summary

Port the following PRs to GO in this PR

infiniflow#16420
infiniflow#13295
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
### Summary

Port the following PRs to GO in this PR

infiniflow#16420
infiniflow#13295
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 💞 feature Feature request, pull request that fullfill a new feature. lgtm This PR has been approved by a maintainer size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants