Skip to content

Go: add context to lots of interface - #17253

Merged
JinHai-CN merged 13 commits into
infiniflow:mainfrom
JinHai-CN:fix574
Jul 22, 2026
Merged

JinHai-CN merged 13 commits into
infiniflow:mainfrom
JinHai-CN:fix574

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

No description provided.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 22, 2026 10:23
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR threads context.Context through the entire model-driver abstraction: the ModelDriver interface and Embedder/RerankModel/TTSDispatcher contracts now require ctx as the first parameter. All ~70 provider implementations (OpenAI, Anthropic, Bedrock, Google, etc.) are updated to match, mostly at the signature level with many still using internal context.Background() timeouts. Downstream, ingestion parsers, the chat pipeline, model service, retrieval/rerank/embedding helpers, and HTTP handlers now capture and forward request-scoped contexts into these driver calls. Tests are updated to pass ctx instead of nil.

Changes

Context Propagation

Layer / File(s) Summary
Core contract
internal/entity/models/types.go, internal/agent/audio/tts_dispatch.go
ModelDriver, RerankModel, and TTSDispatcher interfaces updated to require ctx context.Context as the first parameter.
Provider drivers (70+ files)
internal/entity/models/*.go (302ai, aliyun, anthropic, bedrock, google, openai, xai, zhipu-ai, etc.) and their *_test.go
Every ModelDriver implementation's chat/embed/rerank/transcribe/TTS/OCR/parse/list/balance/task methods gain a leading ctx parameter; several CheckConnection implementations now forward ctx into ListModels/Balance.
Orchestration wiring
internal/entity/models/chat_tools.go, internal/entity/models/llm.go
Tool-calling loops and the Eino chat model wrapper pass ctx into ChatWithMessages/ChatStreamlyWithSender.
Ingestion/parser dispatch
internal/ingestion/component/*.go
Vision/media/PDF dispatch helpers, parser dispatch, tokenizer Embedder, and task embedder pass ctx into driver calls.
Document parsers
internal/parser/parser/*.go
ParseResultProducer.ParseWithResult and all format-specific parsers (PDF, DOCX, XLSX, audio, etc.) gain a ctx parameter.
Service layer
internal/service/*.go, internal/service/{chunk,dataset,graph,file,nlp}/*.go
Chat pipeline, model service, citation insertion, dataset/embedding, graph retrieval, memory, and reranker services thread ctx into driver/embedder calls.
HTTP handlers
internal/handler/*.go
Handlers capture c.Request.Context() and forward it into service calls (chat audio, providers, chunk, dataset, searchbot).

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Handler
  participant ChatPipelineService
  participant ModelProviderService
  participant ModelDriver
  Handler->>ChatPipelineService: AsyncChat(ctx, ...)
  ChatPipelineService->>ModelProviderService: Chat(ctx, ...)
  ModelProviderService->>ModelDriver: ChatWithMessages(ctx, ...)
Loading

Possibly related PRs

  • infiniflow/ragflow#17171: Both PRs touch the FunASR model driver: the retrieved PR introduces internal/entity/models/funasr.go, and this PR updates those same FunASR driver method contracts to accept and propagate context.Context.
  • infiniflow/ragflow#17242: Both PRs modify internal/entity/models/jina.go's JinaModel.Rerank (this PR changes its ctx-aware signature/wiring, the retrieved PR changes the top_n default logic), so they overlap at the same function.

Suggested labels: go
Suggested reviewers: haruko386, lobster-0429

Poem

A rabbit hopped through every file,
ctx in paw, with a determined smile,
Threading context through drivers galore,
From chat to embed to the OCR core,
No more nil, no more forgotten trace—
Cancellation now has its rightful place! 🐇✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning No PR description was provided, so the required Summary section and project context are missing. Add a Summary section that briefly explains the goal of the context propagation changes and any background reviewers need to understand the PR.
Docstring Coverage ⚠️ Warning Docstring coverage is 10.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title matches the main change: adding context parameters across many interfaces, even if phrased awkwardly.

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.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Jul 22, 2026
@JinHai-CN JinHai-CN added ci Continue Integration and removed ci Continue Integration labels Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
putComment timed out

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

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

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

⚠️ Outside diff range comments (7)
internal/entity/models/gpustack.go (1)

55-110: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Preserve the caller’s context on outbound requests.

ChatWithMessages accepts ctx but drops it by rooting new timeouts at context.Background() or by creating requests without a context, so cancellation and deadlines never reach the provider calls in internal/entity/models/gpustack.go, internal/entity/models/groq.go, internal/entity/models/huaweicloud.go, internal/entity/models/huggingface.go, internal/entity/models/hunyuan.go, internal/entity/models/jiekouai.go, and internal/entity/models/jina.go. Pass the incoming ctx through context.WithTimeout and http.NewRequestWithContext instead.

🤖 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 `@internal/entity/models/gpustack.go` around lines 55 - 110, Preserve the
caller’s context when creating outbound requests: in ChatWithMessages and the
corresponding request flows in internal/entity/models/gpustack.go (55-110),
internal/entity/models/groq.go (128-152), internal/entity/models/huaweicloud.go
(177-216), internal/entity/models/huggingface.go (52-126),
internal/entity/models/hunyuan.go (54-106), internal/entity/models/jiekouai.go
(65-130), and internal/entity/models/jina.go (58-113), derive timeouts with
context.WithTimeout(ctx, ...) rather than context.Background() and pass that
derived context to http.NewRequestWithContext, ensuring caller cancellation and
deadlines reach provider calls.
internal/entity/models/astraflow.go (1)

71-123: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Propagate the caller context into every outbound request.

The new ctx contract is currently signature-only: these paths derive contexts from context.Background() or create requests without ctx. Client disconnects and upstream cancellation therefore do not stop provider calls, streams, OCR polling, or result downloads.

  • internal/entity/models/astraflow.go#L71-L123: derive timeout contexts from ctx; use ctx for stream, embed, rerank, and TTS requests.
  • internal/entity/models/avian.go#L117-L141: derive chat, stream, and list-model timeout contexts from ctx.
  • internal/entity/models/baidu.go#L53-L152: derive chat, stream, embed, rerank, OCR, and list-model timeout contexts from ctx.
  • internal/entity/models/bedrock.go#L508-L543: derive non-stream chat, list-model, and embed contexts from ctx, as the stream path already does.
  • internal/entity/models/modelscope.go#L144-L169: derive non-stream and list contexts from ctx; make the stream idle-cancellation context a child of ctx.
  • internal/entity/models/moonshot.go#L61-L149: derive all HTTP timeout contexts from ctx.
  • internal/entity/models/openai.go#L61-L145: use ctx for chat, stream, embed, list, ASR, and TTS requests instead of background contexts.
  • internal/entity/models/openrouter.go#L57-L124: derive all HTTP timeout contexts from ctx.
  • internal/entity/models/orcarouter.go#L51-L112: derive chat, stream, TTS, and list-model timeout contexts from ctx.
  • internal/entity/models/paddleocr.go#L119-L158: derive the OCR operation deadline from ctx so cancellation terminates polling and download requests.
🤖 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 `@internal/entity/models/astraflow.go` around lines 71 - 123, Propagate caller
cancellation through all provider operations. In
internal/entity/models/astraflow.go lines 71-123, update
AstraflowModel.ChatWithMessages and its stream, embed, rerank, and TTS request
paths to derive timeout contexts from ctx and attach ctx to requests. Apply the
same context propagation in internal/entity/models/avian.go lines 117-141,
baidu.go lines 53-152, bedrock.go lines 508-543, modelscope.go lines 144-169,
moonshot.go lines 61-149, openai.go lines 61-145, openrouter.go lines 57-124,
orcarouter.go lines 51-112, and paddleocr.go lines 119-158; preserve the
existing timeout behavior while making the modelscope idle-cancellation context
a child of ctx and ensuring OCR polling and downloads stop when ctx is canceled.
internal/entity/models/stepfun.go (1)

56-109: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Propagate the caller context into these HTTP requests. Using context.Background() (or omitting a context) breaks ModelDriver cancellation and deadlines, so canceled calls keep running until the provider timeout. Derive each WithTimeout/NewRequestWithContext from ctx in these chat/stream/list/TTS paths.

🤖 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 `@internal/entity/models/stepfun.go` around lines 56 - 109, Propagate the
caller’s ctx through every affected HTTP request instead of replacing it with
context.Background(). Update the timeout and request construction in
StepFunModel.ChatWithMessages, and apply the same change to the chat, stream,
list, or TTS paths in internal/entity/models/togetherai.go (130-154),
tokenhub.go (62-119), tokenpony.go (55-107), upstage.go (55-111), vllm.go
(56-136), volcengine.go (76-186), voyage.go (66-102), and xai.go (66-125),
deriving each WithTimeout/NewRequestWithContext from the incoming context while
preserving the existing provider timeout behavior.

Sources: Coding guidelines, Learnings

internal/service/graph/search_test.go (1)

347-360: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Update the test call for the new buildDenseExpr signature.

buildDenseExpr now requires context.Context, but Line 360 still calls it without that argument. Pass a test context such as context.Background() and import context; otherwise this test package will not compile.

🤖 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 `@internal/service/graph/search_test.go` around lines 347 - 360, Update
TestBuildKGDenseExpr_WithModel’s buildDenseExpr call to pass
context.Background() as the new context argument, and add the context import to
the test file. Preserve the existing model, query, and limit arguments.
internal/service/file/file_content.go (1)

225-237: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Propagate parser cancellation instead of treating it as a successful fallback.

ParseWithResult(ctx, ...) can now return context.Canceled or context.DeadlineExceeded, but parseFileContent converts every error to raw file content and GetFileContents returns nil error. A canceled request can therefore continue with unparsed content and appear successful. Propagate context errors through parseFileContent and GetFileContents, while retaining the raw-content fallback only for non-context parse failures.

🤖 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 `@internal/service/file/file_content.go` around lines 225 - 237, Update
parseFileContent and its GetFileContents call path to propagate context.Canceled
and context.DeadlineExceeded from ParseWithResult instead of returning raw
content. Preserve the raw-content fallback for non-context parser failures and
ensure GetFileContents returns the propagated context error to the caller.
internal/parser/parser/xlsx_parser.go (1)

94-103: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Forward ctx into the TCADP parser path.

The new parameter is unused. In particular, the remote TCADP branch calls parseSpreadsheetWithTCADP without context, so cancellation and deadlines stop at XLSXParser. Add ctx to that helper and use it when creating its outbound request.

🤖 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 `@internal/parser/parser/xlsx_parser.go` around lines 94 - 103, Propagate ctx
through the TCADP branch of XLSXParser.ParseWithResult into
parseSpreadsheetWithTCADP, update that helper’s signature and all callers, and
use the context when constructing the outbound TCADP request so cancellation and
deadlines are honored.
internal/parser/parser/csv_parser.go (1)

117-126: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Propagate ctx through the TCADP spreadsheet path. The helper currently hardcodes context.Background() for both HTTP requests, so cancellations/timeouts from CSV/XLS/XLSX parsing never reach the remote TCADP calls.

  • internal/parser/parser/csv_parser.go
  • internal/parser/parser/xls_parser.go
  • internal/parser/parser/xlsx_parser.go
  • internal/parser/parser/xls_tcadp.go
🤖 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 `@internal/parser/parser/csv_parser.go` around lines 117 - 126, Propagate the
caller’s ctx through the TCADP parsing flow: update ParseWithResult in
internal/parser/parser/csv_parser.go and internal/parser/parser/xls_parser.go,
the corresponding XLSX parser path in internal/parser/parser/xlsx_parser.go, and
parseSpreadsheetWithTCADP in internal/parser/parser/xls_tcadp.go so both remote
HTTP requests use the propagated context instead of context.Background().
🟡 Minor comments (1)
internal/entity/models/302ai.go-670-672 (1)

670-672: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the stale TODO.

AudioSpeech intentionally remains unsupported; delete the deferred implementation note until the feature is actually added.

As per coding guidelines, remove stale documentation and “move later” notes.

🤖 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 `@internal/entity/models/302ai.go` around lines 670 - 672, Remove the stale
TODO comment from the AI302Model.AudioSpeech method while preserving its current
unsupported behavior and error return unchanged.

Source: Coding guidelines

🧹 Nitpick comments (1)
internal/entity/models/llm.go (1)

136-150: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the obsolete Phase 0 context comment.

Generate now calls ChatWithMessages with ctx, but lines 136-138 still claim the method has no context and describe this as future work. Delete or rewrite that stale comment; retain the cancellation guard if needed.

As per coding guidelines, remove stale documentation and migration-history comments.

🤖 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 `@internal/entity/models/llm.go` around lines 136 - 150, Remove the obsolete
Phase 0 migration-history comment above the ctx.Err() guard in Generate, since
ChatWithMessages now receives ctx. Retain the cancellation guard and its
behavior unchanged.

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 `@internal/entity/models/302ai_test.go`:
- Line 288: Complete the migration of tests in 302ai_test.go by adding the
leading ctx argument to every remaining ChatWithMessages,
ChatStreamlyWithSender, ListModels, and ShowTask call, matching the updated
method signatures while preserving all existing arguments and assertions.

In `@internal/entity/models/302ai.go`:
- Line 74: Preserve the public request context when constructing all provider
calls instead of replacing it with context.Background or omitting it. In
internal/entity/models/302ai.go:74-74, derive operation deadlines from ctx for
chat, streaming, embedding, reranking, ASR, OCR, parsing, model listing, and
task lookup; apply the same context propagation to chat, stream, embed, rerank,
and model-list requests in internal/entity/models/aliyun.go:56-56,
internal/entity/models/anthropic.go:64-64, and
internal/entity/models/qiniu.go:143-143; use http.NewRequestWithContext(ctx,
...) in Embed in internal/entity/models/builtin.go:60-60; pass ctx through all
request helpers and streaming paths in internal/entity/models/ragcon.go:130-130,
prediction creation, polling, and SSE reads in
internal/entity/models/replicate.go:328-328, and every outbound request in
internal/entity/models/siliconflow.go:70-70.

In `@internal/entity/models/azure_openai.go`:
- Line 64: Preserve the caller’s context across all listed outbound-request
methods: replace context.Background()-based context.WithTimeout/WithCancel calls
with the incoming ctx in internal/entity/models/azure_openai.go:64, 185, 316,
394; baichuan.go:52, 168, 293; paddleocr_local.go:101; perplexity.go:117, 184,
287, 353; ppio.go:115, 183, 282; xiaomi.go:56, 227, 398, 433, 644, 670;
xinference.go:146, 216, 345, 453, 544, 657, 733; xunfei.go:51, 183, 356; and
zhipu-ai.go:90, 250, 510, 586, 637, 713, 795, 927, 969, 1067. For Xinference and
Xiaomi ASR/TTS methods, also pass ctx to http.NewRequestWithContext so
cancellations and deadlines propagate.

In `@internal/entity/models/cohere.go`:
- Line 56: Propagate the supplied context through every outbound model request
instead of using context.Background(). In internal/entity/models/cohere.go:56,
derive existing chat, stream, embed, rerank, ASR, and ListModels timeouts from
ctx; in internal/entity/models/cometapi.go:238, use ctx for chat, stream, embed,
list, balance, ASR, and TTS; in internal/entity/models/deepinfra.go:58,
deepseek.go:55, fishaudio.go:74, and funasr.go:72, retain timeout limits with
context.WithTimeout(ctx, ...); in internal/entity/models/futurmix.go:149, pass
ctx to both request constructors; in internal/entity/models/gitee.go:58,
propagate ctx through requests and getParseFile polling; and in
internal/entity/models/google.go:299 and :353-359, derive the embed timeout from
ctx and call googleListModels(ctx, ...).

In `@internal/entity/models/cometapi_test.go`:
- Line 314: The CometAPI test still calls methods using removed signatures. In
internal/entity/models/cometapi_test.go lines 314-314, update the
ChatWithMessages, ChatStreamlyWithSender, and both Embed table callbacks to pass
ctx; also update the subsequent empty-model Embed call at lines 659-659 to pass
ctx.

In `@internal/entity/models/groq_test.go`:
- Line 381: Update the unsupported-method test calls for Rerank, Balance,
ParseFile, and ListTasks to use the ctx-first argument signature, matching the
existing Embed invocation. Preserve the current error assertions while passing
ctx as the first argument to each method.

In `@internal/entity/models/hunyuan_test.go`:
- Around line 472-475: Update the remaining Embed invocations in
hunyuan_test.go, including the calls around the empty-input and
required-model-name cases, to pass ctx as the first argument and shift the
existing arguments accordingly. Preserve each test’s current assertions and
inputs.

In `@internal/entity/models/jiekouai_test.go`:
- Line 317: Update the remaining calls in the test file to use the ctx-first
signatures: migrate Embed, Rerank, ChatWithMessages, ChatStreamlyWithSender, and
ListModels calls, including the shown newJieKouAIForTest invocation, by moving
the context argument to the required first position while preserving all other
arguments and assertions.

In `@internal/entity/models/lmstudio.go`:
- Line 56: Thread the caller context through every outbound request: in
internal/entity/models/lmstudio.go at lines 56, 207, 354, and 471; localai.go at
84, 198, 373, 475, and 556; longcat.go at 55, 170, and 312; mineru.go at 108 and
199; mineru_local.go at 101 and 194; minimax.go at 63, 227, 399, 476, and 566;
mistral.go at 58, 211, 346, 435, and 522; n1n.go at 162, 227, 325, 419, and 500;
novita.go at 191, 335, 496, 565, 669, and 759; nvidia.go at 54, 187, 327, 444,
and 567; and ollama.go at 76, 198, 333, and 462. Replace context.Background()
parents with the method ctx when creating deadlines, and replace any plain
http.NewRequest call with http.NewRequestWithContext using ctx, preserving each
request’s existing timeout and behavior.

In `@internal/entity/models/mistral_test.go`:
- Line 535: Update the second Embed invocation in the affected test to use the
current Embed signature, passing the required context and arguments consistently
with the preceding call. Ensure no remaining call in the test uses the removed
signature so the package compiles.

In `@internal/entity/models/modelscope_test.go`:
- Line 308: Update the test’s CheckConnection call to pass the existing ctx
argument alongside apiConfig, matching the current method signature. Locate the
call within the test around m.ListModels and preserve the rest of the test
behavior.

In `@internal/entity/models/perplexity_test.go`:
- Line 352: Complete the context-aware test-call migration: in
internal/entity/models/perplexity_test.go lines 341 and 352, pass ctx to the
Embed calls; in internal/entity/models/ppio_test.go lines 480-507, pass ctx to
all remaining unsupported-method calls in TestPPIOUnsupportedMethods; and in
internal/entity/models/xinference_test.go line 274, call x.CheckConnection with
ctx and apiConfig.

In `@internal/entity/models/sse_scanner_buffer_test.go`:
- Line 16: Update the ChatStreamlyWithSender test usage by importing the context
package and passing context.Background() (or an equivalent test context) as the
first argument before "test-model" at the call site around line 74, matching the
method signature.

In `@internal/entity/models/tokenhub_test.go`:
- Around line 283-286: Update the remaining Embed invocation in the tokenhub
test to pass ctx as the first argument, matching the current TokenHubModel.Embed
signature while preserving the existing error assertion.

In `@internal/ingestion/component/tokenizer.go`:
- Around line 489-490: Update the Encode call inside the runtime.WithTimeout
callback to pass timeoutCtx instead of the parent ctx, ensuring the embedder
request is cancelled when tokenizerTimeout expires.

In `@internal/parser/parser/parse_result.go`:
- Line 89: Complete the context-signature rollout for ParseWithResult by
updating every stale caller, including tests such as the 302ai model callers, to
pass a context.Context and adding the missing context import in
sse_scanner_buffer_test.go. Remove any resulting typecheck errors, then validate
the changes using the repository’s bash build.sh --test ... flow.

In `@internal/parser/parser/pdf_parser_docling.go`:
- Around line 39-42: Preserve the caller’s request context for outbound
PDF-service calls: in internal/parser/parser/pdf_parser_docling.go, update
parsePDFWithDocling’s models.PostJSONRequest call to use ctx instead of
context.Background(); likewise, in
internal/parser/parser/pdf_parser_opendataloader.go, update the HTTP request
creation to pass ctx to http.NewRequestWithContext. No direct change is needed
at the cited anchor lines beyond tracing these helpers to their request calls.

In `@internal/parser/parser/pdf_parser_mineru.go`:
- Around line 69-76: Update pollMinerUTask to stop immediately when the request
context is canceled: after ShowTask returns an error, check ctx.Err() and return
it instead of recording and retrying context errors. Replace the unconditional
polling sleep with a select between the timer and ctx.Done(), preserving the
existing timeout and retry behavior for non-context errors.

In `@internal/service/chunk/chunk.go`:
- Line 1248: Preserve request cancellation in downstream engine work: in
internal/service/chunk/chunk.go lines 1248-1248, update AddChunk to derive its
600-second insert timeout from ctx instead of context.Background(); in
internal/service/dataset/index.go lines 422-422, pass ctx to
sampleRandomChunksWithVectors and docEngine.GetChunk rather than replacing it
with a background context.

In `@internal/service/nlp/reranker.go`:
- Line 72: Update the call to RerankByModel in the reranking branch so it does
not pass nil alignment metadata; provide IDs and corresponding field data
derived from chunks, or revise RerankByModel to explicitly handle chunks-only
input while still producing scores. Preserve the existing reranking parameters
and ensure the docs list is populated before invoking the model.

---

Outside diff comments:
In `@internal/entity/models/astraflow.go`:
- Around line 71-123: Propagate caller cancellation through all provider
operations. In internal/entity/models/astraflow.go lines 71-123, update
AstraflowModel.ChatWithMessages and its stream, embed, rerank, and TTS request
paths to derive timeout contexts from ctx and attach ctx to requests. Apply the
same context propagation in internal/entity/models/avian.go lines 117-141,
baidu.go lines 53-152, bedrock.go lines 508-543, modelscope.go lines 144-169,
moonshot.go lines 61-149, openai.go lines 61-145, openrouter.go lines 57-124,
orcarouter.go lines 51-112, and paddleocr.go lines 119-158; preserve the
existing timeout behavior while making the modelscope idle-cancellation context
a child of ctx and ensuring OCR polling and downloads stop when ctx is canceled.

In `@internal/entity/models/gpustack.go`:
- Around line 55-110: Preserve the caller’s context when creating outbound
requests: in ChatWithMessages and the corresponding request flows in
internal/entity/models/gpustack.go (55-110), internal/entity/models/groq.go
(128-152), internal/entity/models/huaweicloud.go (177-216),
internal/entity/models/huggingface.go (52-126),
internal/entity/models/hunyuan.go (54-106), internal/entity/models/jiekouai.go
(65-130), and internal/entity/models/jina.go (58-113), derive timeouts with
context.WithTimeout(ctx, ...) rather than context.Background() and pass that
derived context to http.NewRequestWithContext, ensuring caller cancellation and
deadlines reach provider calls.

In `@internal/entity/models/stepfun.go`:
- Around line 56-109: Propagate the caller’s ctx through every affected HTTP
request instead of replacing it with context.Background(). Update the timeout
and request construction in StepFunModel.ChatWithMessages, and apply the same
change to the chat, stream, list, or TTS paths in
internal/entity/models/togetherai.go (130-154), tokenhub.go (62-119),
tokenpony.go (55-107), upstage.go (55-111), vllm.go (56-136), volcengine.go
(76-186), voyage.go (66-102), and xai.go (66-125), deriving each
WithTimeout/NewRequestWithContext from the incoming context while preserving the
existing provider timeout behavior.

In `@internal/parser/parser/csv_parser.go`:
- Around line 117-126: Propagate the caller’s ctx through the TCADP parsing
flow: update ParseWithResult in internal/parser/parser/csv_parser.go and
internal/parser/parser/xls_parser.go, the corresponding XLSX parser path in
internal/parser/parser/xlsx_parser.go, and parseSpreadsheetWithTCADP in
internal/parser/parser/xls_tcadp.go so both remote HTTP requests use the
propagated context instead of context.Background().

In `@internal/parser/parser/xlsx_parser.go`:
- Around line 94-103: Propagate ctx through the TCADP branch of
XLSXParser.ParseWithResult into parseSpreadsheetWithTCADP, update that helper’s
signature and all callers, and use the context when constructing the outbound
TCADP request so cancellation and deadlines are honored.

In `@internal/service/file/file_content.go`:
- Around line 225-237: Update parseFileContent and its GetFileContents call path
to propagate context.Canceled and context.DeadlineExceeded from ParseWithResult
instead of returning raw content. Preserve the raw-content fallback for
non-context parser failures and ensure GetFileContents returns the propagated
context error to the caller.

In `@internal/service/graph/search_test.go`:
- Around line 347-360: Update TestBuildKGDenseExpr_WithModel’s buildDenseExpr
call to pass context.Background() as the new context argument, and add the
context import to the test file. Preserve the existing model, query, and limit
arguments.

---

Minor comments:
In `@internal/entity/models/302ai.go`:
- Around line 670-672: Remove the stale TODO comment from the
AI302Model.AudioSpeech method while preserving its current unsupported behavior
and error return unchanged.

---

Nitpick comments:
In `@internal/entity/models/llm.go`:
- Around line 136-150: Remove the obsolete Phase 0 migration-history comment
above the ctx.Err() guard in Generate, since ChatWithMessages now receives ctx.
Retain the cancellation guard and its behavior unchanged.
🪄 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: 999b3b33-2427-4eb5-9275-388c7b4880f8

📥 Commits

Reviewing files that changed from the base of the PR and between ffccf0b and ca6195e.

📒 Files selected for processing (147)
  • internal/agent/audio/tts_dispatch.go
  • internal/entity/models/302ai.go
  • internal/entity/models/302ai_test.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/anthropic.go
  • internal/entity/models/astraflow.go
  • internal/entity/models/astraflow_test.go
  • internal/entity/models/avian.go
  • internal/entity/models/azure_openai.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/builtin.go
  • internal/entity/models/chat_tools.go
  • internal/entity/models/cohere.go
  • internal/entity/models/cometapi.go
  • internal/entity/models/cometapi_test.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/funasr.go
  • internal/entity/models/futurmix.go
  • internal/entity/models/gitee.go
  • internal/entity/models/gitee_test.go
  • internal/entity/models/google.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/groq.go
  • internal/entity/models/groq_test.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/hunyuan_test.go
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jiekouai_test.go
  • internal/entity/models/jina.go
  • internal/entity/models/llm.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/longcat.go
  • internal/entity/models/mineru.go
  • internal/entity/models/mineru_local.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/mistral_test.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/modelscope_test.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/n1n.go
  • internal/entity/models/novita.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/paddleocr.go
  • internal/entity/models/paddleocr_local.go
  • internal/entity/models/perplexity.go
  • internal/entity/models/perplexity_test.go
  • internal/entity/models/ppio.go
  • internal/entity/models/ppio_test.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/ragcon.go
  • internal/entity/models/replicate.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/sse_scanner_buffer_test.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/togetherai.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenhub_test.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/types.go
  • internal/entity/models/upstage.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/voyage.go
  • internal/entity/models/voyage_test.go
  • internal/entity/models/xai.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/xinference.go
  • internal/entity/models/xinference_test.go
  • internal/entity/models/xunfei.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/chat_audio.go
  • internal/handler/chat_recommendation.go
  • internal/handler/chunk.go
  • internal/handler/dataset.go
  • internal/handler/providers.go
  • internal/handler/searchbot.go
  • internal/ingestion/component/docx_vision_dispatch.go
  • internal/ingestion/component/markdown_vision_dispatch.go
  • internal/ingestion/component/media_dispatch.go
  • internal/ingestion/component/parser.go
  • internal/ingestion/component/parser_dispatch.go
  • internal/ingestion/component/parser_dispatch_test.go
  • internal/ingestion/component/pdf_vision_dispatch.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/task/embedder.go
  • internal/ingestion/task/embedder_test.go
  • internal/parser/parser/audio_parser.go
  • internal/parser/parser/csv_parser.go
  • internal/parser/parser/doc_parser.go
  • internal/parser/parser/docx_parser.go
  • internal/parser/parser/email_parser.go
  • internal/parser/parser/epub_parser.go
  • internal/parser/parser/html_parser.go
  • internal/parser/parser/json_parser.go
  • internal/parser/parser/markdown_parser.go
  • internal/parser/parser/parse_result.go
  • internal/parser/parser/pdf_parser_cgo.go
  • internal/parser/parser/pdf_parser_docling.go
  • internal/parser/parser/pdf_parser_mineru.go
  • internal/parser/parser/pdf_parser_opendataloader.go
  • internal/parser/parser/pdf_parser_paddleocr.go
  • internal/parser/parser/picture_parser.go
  • internal/parser/parser/ppt_parser.go
  • internal/parser/parser/pptx_parser.go
  • internal/parser/parser/text_parser.go
  • internal/parser/parser/xls_parser.go
  • internal/parser/parser/xlsx_parser.go
  • internal/service/agent.go
  • internal/service/ask_service.go
  • internal/service/chat_pipeline.go
  • internal/service/chunk/chunk.go
  • internal/service/citation.go
  • internal/service/dataset/index.go
  • internal/service/dataset/utils.go
  • internal/service/deep_researcher.go
  • internal/service/file/file_content.go
  • internal/service/generator.go
  • internal/service/graph/pipeline.go
  • internal/service/graph/retrieval.go
  • internal/service/graph/search.go
  • internal/service/graph/search_test.go
  • internal/service/memory.go
  • internal/service/memory_message_service.go
  • internal/service/metadata_filter.go
  • internal/service/model_chat.go
  • internal/service/model_chat_test.go
  • internal/service/model_service.go
  • internal/service/nlp/reranker.go
  • internal/service/nlp/retrieval.go
  • internal/service/related_question.go
  • internal/service/skill_indexer.go
  • internal/service/skill_search.go
  • internal/service/toc_enhancer.go

Comment thread internal/entity/models/302ai_test.go Resolved
Comment thread internal/entity/models/302ai.go Resolved
Comment thread internal/entity/models/azure_openai.go Resolved
Comment thread internal/entity/models/cohere.go Resolved
Comment thread internal/entity/models/cometapi_test.go Resolved
// contract. Every parser returned by GetParser must implement it.
type ParseResultProducer interface {
ParseWithResult(filename string, data []byte) ParseResult
ParseWithResult(ctx context.Context, filename string, data []byte) ParseResult

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.

🎯 Functional Correctness | 🔴 Critical | 🏗️ Heavy lift

Complete the context-signature rollout before merging.

The current typecheck still fails on stale callers such as internal/entity/models/302ai_test.go and a missing context import in internal/entity/models/sse_scanner_buffer_test.go. Update all affected callers/imports, then validate with the repository’s bash build.sh --test ... flow.

🤖 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 `@internal/parser/parser/parse_result.go` at line 89, Complete the
context-signature rollout for ParseWithResult by updating every stale caller,
including tests such as the 302ai model callers, to pass a context.Context and
adding the missing context import in sse_scanner_buffer_test.go. Remove any
resulting typecheck errors, then validate the changes using the repository’s
bash build.sh --test ... flow.

Sources: Coding guidelines, Linters/SAST tools

Comment on lines +39 to 42
func parsePDFWithDocling(ctx context.Context, filename string, data []byte, parser *PDFParser) ParseResult {
if len(data) == 0 {
return emptyPDFResult(filename)
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not discard request context before outbound PDF-service calls.

Both helpers accept ctx but replace it with context.Background() for the actual HTTP request, preventing cancellation and deadlines from propagating.

  • internal/parser/parser/pdf_parser_docling.go#L39-L42: pass ctx to models.PostJSONRequest at Line 91.
  • internal/parser/parser/pdf_parser_opendataloader.go#L16-L16: pass ctx to http.NewRequestWithContext at Line 36.
📍 Affects 2 files
  • internal/parser/parser/pdf_parser_docling.go#L39-L42 (this comment)
  • internal/parser/parser/pdf_parser_opendataloader.go#L16-L16
🤖 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 `@internal/parser/parser/pdf_parser_docling.go` around lines 39 - 42, Preserve
the caller’s request context for outbound PDF-service calls: in
internal/parser/parser/pdf_parser_docling.go, update parsePDFWithDocling’s
models.PostJSONRequest call to use ctx instead of context.Background();
likewise, in internal/parser/parser/pdf_parser_opendataloader.go, update the
HTTP request creation to pass ctx to http.NewRequestWithContext. No direct
change is needed at the cited anchor lines beyond tracing these helpers to their
request calls.

Comment on lines +69 to +76
func pollMinerUTask(ctx context.Context, driver *models.MinerULocalModel, taskID string, apiConfig *models.APIConfig, timeout time.Duration) (string, error) {
if timeout <= 0 {
timeout = minerUPollTimeout
}
deadline := time.Now().Add(timeout)
var lastErr error
for {
task, err := driver.ShowTask(taskID, apiConfig)
task, err := driver.ShowTask(ctx, taskID, apiConfig)

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Stop MinerU polling when the context is canceled.

When ShowTask returns a context error, the loop records it and retries; time.Sleep also ignores cancellation. A canceled request can therefore keep polling for up to 30 seconds. Return on ctx.Err() and use a select on ctx.Done() instead of unconditional sleep.

Proposed fix
 	for {
+		if err := ctx.Err(); err != nil {
+			return "", err
+		}
 		task, err := driver.ShowTask(ctx, taskID, apiConfig)
 		if err == nil {
 			...
 		} else {
+			if ctxErr := ctx.Err(); ctxErr != nil {
+				return "", ctxErr
+			}
 			lastErr = err
 		}
 		...
-		time.Sleep(minerUPollInterval)
+		timer := time.NewTimer(minerUPollInterval)
+		select {
+		case <-ctx.Done():
+			timer.Stop()
+			return "", ctx.Err()
+		case <-timer.C:
+		}
 	}
📝 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
func pollMinerUTask(ctx context.Context, driver *models.MinerULocalModel, taskID string, apiConfig *models.APIConfig, timeout time.Duration) (string, error) {
if timeout <= 0 {
timeout = minerUPollTimeout
}
deadline := time.Now().Add(timeout)
var lastErr error
for {
task, err := driver.ShowTask(taskID, apiConfig)
task, err := driver.ShowTask(ctx, taskID, apiConfig)
func pollMinerUTask(ctx context.Context, driver *models.MinerULocalModel, taskID string, apiConfig *models.APIConfig, timeout time.Duration) (string, error) {
if timeout <= 0 {
timeout = minerUPollTimeout
}
deadline := time.Now().Add(timeout)
var lastErr error
for {
if err := ctx.Err(); err != nil {
return "", err
}
task, err := driver.ShowTask(ctx, taskID, apiConfig)
if err == nil {
...
} else {
if ctxErr := ctx.Err(); ctxErr != nil {
return "", ctxErr
}
lastErr = err
}
...
timer := time.NewTimer(minerUPollInterval)
select {
case <-ctx.Done():
timer.Stop()
return "", ctx.Err()
case <-timer.C:
}
}
}
🤖 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 `@internal/parser/parser/pdf_parser_mineru.go` around lines 69 - 76, Update
pollMinerUTask to stop immediately when the request context is canceled: after
ShowTask returns an error, check ctx.Err() and return it instead of recording
and retrying context errors. Replace the unconditional polling sleep with a
select between the timer and ctx.Done(), preserving the existing timeout and
retry behavior for non-context errors.

}

func (s *ChunkService) AddChunk(req *service.AddChunkRequest, userID string) (*service.AddChunkResponse, error) {
func (s *ChunkService) AddChunk(ctx context.Context, req *service.AddChunkRequest, userID string) (*service.AddChunkResponse, error) {

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Request cancellation is still discarded in downstream engine work. Both methods accept a request context but replace it with context.Background() before expensive or persistent operations.

  • internal/service/chunk/chunk.go#L1248-L1248: derive the 600-second insert timeout from ctx, not context.Background().
  • internal/service/dataset/index.go#L422-L422: pass ctx to sampleRandomChunksWithVectors and docEngine.GetChunk.
📍 Affects 2 files
  • internal/service/chunk/chunk.go#L1248-L1248 (this comment)
  • internal/service/dataset/index.go#L422-L422
🤖 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 `@internal/service/chunk/chunk.go` at line 1248, Preserve request cancellation
in downstream engine work: in internal/service/chunk/chunk.go lines 1248-1248,
update AddChunk to derive its 600-second insert timeout from ctx instead of
context.Background(); in internal/service/dataset/index.go lines 422-422, pass
ctx to sampleRandomChunksWithVectors and docEngine.GetChunk rather than
replacing it with a background context.

// If reranker model is provided and there are results, use model reranking
if rerankModel != nil && total > 0 {
return RerankByModel(rerankModel, chunks, nil, nil, query, tkWeight, vtWeight, cfield, qb, rankFeature)
return RerankByModel(ctx, rerankModel, chunks, nil, nil, query, tkWeight, vtWeight, cfield, qb, rankFeature)

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not invoke model reranking with empty alignment metadata.

RerankByModel builds docs by ranging over ids; passing nil, nil means it sends an empty document list and returns empty scores whenever this branch is used. Supply IDs/field data here, or make RerankByModel explicitly support chunks-only input.

🤖 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 `@internal/service/nlp/reranker.go` at line 72, Update the call to
RerankByModel in the reranking branch so it does not pass nil alignment
metadata; provide IDs and corresponding field data derived from chunks, or
revise RerankByModel to explicitly handle chunks-only input while still
producing scores. Preserve the existing reranking parameters and ensure the docs
list is populated before invoking the model.

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

Caution

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

⚠️ Outside diff range comments (2)
internal/service/user_beta_test.go (1)

37-135: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Complete the model-test context migration before merge.

Static analysis reports internal/entity/models/localai_test.go has multiple undefined ctx references and an obsolete Balance call lacking its required context argument, so internal/entity/models tests do not compile. Fix those call sites and validate with bash build.sh --test internal/entity/models.

🤖 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 `@internal/service/user_beta_test.go` around lines 37 - 135, Complete the
context migration in the LocalAI model tests by defining or passing the
appropriate test context at every currently undefined ctx reference, and update
the obsolete Balance call to supply its required context argument. Ensure all
affected test call sites compile, then validate with the model test suite.

Source: Linters/SAST tools

internal/entity/models/ppio_test.go (1)

480-507: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Finish migrating the remaining unsupported-method calls.

Lines 486-507 still use pre-context signatures, so this test file cannot compile. Pass ctx to TranscribeAudio, TranscribeAudioWithSender, AudioSpeech, AudioSpeechWithSender, OCRFile, and ShowTask.

Proposed fix
- if _, err := m.TranscribeAudio(nil, nil, nil, nil, nil); err == nil {
+ if _, err := m.TranscribeAudio(ctx, nil, nil, nil, nil, nil); err == nil {
    // ...
  }
- if err := m.TranscribeAudioWithSender(nil, nil, nil, nil, nil, nil); err == nil {
+ if err := m.TranscribeAudioWithSender(ctx, nil, nil, nil, nil, nil, nil); err == nil {
    // ...
  }
- if _, err := m.AudioSpeech(nil, nil, nil, nil, nil); err == nil {
+ if _, err := m.AudioSpeech(ctx, nil, nil, nil, nil, nil); err == nil {
    // ...
  }
- if err := m.AudioSpeechWithSender(nil, nil, nil, nil, nil, nil); err == nil {
+ if err := m.AudioSpeechWithSender(ctx, nil, nil, nil, nil, nil, nil); err == nil {
    // ...
  }
- if _, err := m.OCRFile(nil, nil, nil, nil, nil, nil); err == nil {
+ if _, err := m.OCRFile(ctx, nil, nil, nil, nil, nil, nil); err == nil {
    // ...
  }
- if _, err := m.ShowTask("", nil); err == nil {
+ if _, err := m.ShowTask(ctx, "", nil); err == nil {
    // ...
  }
🤖 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 `@internal/entity/models/ppio_test.go` around lines 480 - 507, Update the
remaining unsupported-method calls in the test block to use the current
context-aware signatures: pass ctx to TranscribeAudio,
TranscribeAudioWithSender, AudioSpeech, AudioSpeechWithSender, OCRFile, and
ShowTask. Preserve the existing error assertions and arguments while adding the
context parameter in the correct position for each method.
♻️ Duplicate comments (1)
internal/entity/models/modelscope_test.go (1)

308-308: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Finish the remaining context-signature migration in internal/entity/models/modelscope_test.go. The shared ModelDriver contract is ctx-first, but several calls still use the removed signatures, so the test package will not compile.

  • internal/entity/models/modelscope_test.go#L308-L308: change CheckConnection(apiConfig) to CheckConnection(ctx, apiConfig).
  • internal/entity/models/modelscope_test.go#L334-L343: update the following TranscribeAudioWithSender, AudioSpeech, AudioSpeechWithSender, and OCRFile calls to pass ctx first.
🤖 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 `@internal/entity/models/modelscope_test.go` at line 308, Complete the
context-first signature migration in internal/entity/models/modelscope_test.go:
update CheckConnection at lines 308-308 and the TranscribeAudioWithSender,
AudioSpeech, AudioSpeechWithSender, and OCRFile calls at lines 334-343 to pass
ctx as the first argument, preserving all other arguments and test behavior.
🧹 Nitpick comments (4)
internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go (1)

38-38: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert that PDF-vision dispatch preserves the caller context.

Each mock accepts ctx but ignores it, so these tests still pass if dispatch drops or replaces the request context. Invoke the component with a sentinel context value and assert that each mock receives it.

  • internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go#L38-L38: validate the context received by the fixture invoker.
  • internal/ingestion/component/parser_dispatch_test.go#L433-L433: validate context propagation in the tenant-aware test.
  • internal/ingestion/component/parser_dispatch_test.go#L511-L511: validate context propagation in the empty-page test.
🤖 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 `@internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go` at line
38, Update the mock invokers in
internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go:38-38,
internal/ingestion/component/parser_dispatch_test.go:433-433, and
internal/ingestion/component/parser_dispatch_test.go:511-511 to assert that the
received ctx matches a sentinel context supplied by each test; ensure the
corresponding PDF-vision dispatch test setups invoke the component with that
sentinel so context propagation is verified.
internal/service/user.go (1)

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

Remove the unused ctx parameter from GetUserProfile.
This is a pure formatter over entity.User; drop ctx from the service method and update the handler call sites accordingly.

🤖 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 `@internal/service/user.go` at line 635, Remove the unused ctx parameter from
UserService.GetUserProfile, keeping it as a formatter over entity.User. Update
all five call sites in internal/handler/user.go at lines 94, 175, 261, 385, and
727 to invoke the method with only the user argument.

Source: Coding guidelines

internal/handler/searchbot.go (1)

382-384: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the handler documentation runtime-focused.

Remove “matching Python’s AUTH_BETA flow”; describe the Go endpoint’s beta-token requirement directly.

🤖 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 `@internal/handler/searchbot.go` around lines 382 - 384, Update the
SearchBotDetail documentation comment to state directly that the endpoint
requires a beta token, and remove the comparison to Python’s AUTH_BETA flow.

Source: Coding guidelines

internal/service/citation_test.go (1)

248-260: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert context propagation in the driver fakes. Both fakes accept ctx but discard it, so replacing the forwarded context with context.Background() would still pass.

  • internal/service/citation_test.go#L248-L260: retain the received context or a sentinel value in fakeEmbedder, then assert InsertCitations forwarded it.
  • internal/service/graph/retrieval_test.go#L327-L328: retain the received context in spyEmbedDriver.
  • internal/service/graph/retrieval_test.go#L415-L426: assert buildSearchExprs forwards the caller context to Embed.
🤖 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 `@internal/service/citation_test.go` around lines 248 - 260, Update
fakeEmbedder in internal/service/citation_test.go:248-260 and spyEmbedDriver in
internal/service/graph/retrieval_test.go:327-328 to retain the received context,
then add assertions that InsertCitations and buildSearchExprs, respectively,
forward the caller’s context to Embed; ensure the tests fail if
context.Background() is substituted.
🤖 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 `@internal/agent/audio/tts_dispatch_test.go`:
- Line 54: Update the fake dispatcher in the test around its fn callback to
retain the received ctx instead of discarding it, then assert that the stored
context contains the expected sentinel value from the request context. Ensure
the test verifies context propagation through the dispatcher.

In `@internal/dao/user.go`:
- Around line 39-41: Propagate request contexts through the user DAO paths so
GORM honors cancellation and deadlines: update internal/dao/user.go lines 39-41
in UserDAO.GetByID to use DB.WithContext(ctx), and update the DAO calls used by
LoginByEmail, GetUserByToken, UpdateUserSettings, ChangePassword, SetTenantInfo,
GetUserByAPIToken, GetAPITokenByBeta, and GetUserByBetaAPIToken in
internal/service/user.go lines 392-417, 424-426, 589-609, 740-801, 808-826,
878-899, 1004-1029, 1048-1069, and 1081-1110 to pass their existing ctx through.

In `@internal/entity/models/localai_test.go`:
- Line 81: Complete the context-signature migration across all affected tests:
in internal/entity/models/localai_test.go:81-81, define and reuse t.Context() at
updated call sites and migrate the remaining Balance call at line 221; in
internal/entity/models/moonshot_test.go:296-296 and 369-369, pass ctx to the
remaining Balance calls at lines 326 and 447; in
internal/entity/models/xunfei_test.go:16-20, pass ctx to the audio, OCR,
parsing, balance, task-list, and task-status calls; and in
internal/entity/models/xunfei_test.go:50-50, keep CheckConnection ctx-first
while migrating the other legacy calls in that table.

In `@internal/entity/models/novita_test.go`:
- Line 452: Update the affected test call sites to match the context-aware APIs:
in internal/entity/models/novita_test.go:452 and
internal/entity/models/nvidia_rerank_test.go:137, prepend the missing ctx
argument; in internal/entity/models/ollama_test.go:43, ragcon_test.go:261,
tokenhub_test.go:137, vllm_rerank_test.go:136, volcengine_test.go:80,
voyage_test.go:88, xiaomi_test.go:148, and xinference_test.go:93, declare ctx
with t.Context() in each affected test and pass it to the calls. In
internal/entity/models/xinference_test.go:93, also update Balance to use the new
leading-context signature.

In `@internal/handler/auth.go`:
- Around line 41-44: The user-service methods GetUserByToken, GetUserByAPIToken,
GetUserByBetaAPIToken, and GetAPITokenByBeta currently discard request
cancellation; update their service and DAO query paths to execute with the
supplied ctx, such as via GORM WithContext(ctx), or remove ctx only if
cancellation cannot be supported. In internal/handler/auth.go lines 41-44, make
the resolver contract match the implementation; in internal/handler/searchbot.go
lines 393-394, retain the existing request-context call because the beta-token
lookup must consume it.

In `@internal/parser/parser/docx_parser_cgo_test.go`:
- Around line 12-16: Update the no-CGO office parser stubs, including DOCX
ParseWithResult and the sibling methods in office_parsers_no_cgo.go, to match
the context-aware shared parser signatures by accepting a context argument and
ignoring it where unused. Preserve their existing stub behavior and return
values.

In `@internal/parser/parser/ppt_parser_cgo_test.go`:
- Around line 29-32: Update the !cgo ParseWithResult methods on DOCXParser,
DOCParser, PPTParser, and PPTXParser in office_parsers_no_cgo.go to accept ctx,
filename, and data in the new order, matching ParseResultProducer while
preserving stub behavior. Update the !cgo tests, including the call in
office_parsers_nocgo_test.go, to pass the context as the first argument.

---

Outside diff comments:
In `@internal/entity/models/ppio_test.go`:
- Around line 480-507: Update the remaining unsupported-method calls in the test
block to use the current context-aware signatures: pass ctx to TranscribeAudio,
TranscribeAudioWithSender, AudioSpeech, AudioSpeechWithSender, OCRFile, and
ShowTask. Preserve the existing error assertions and arguments while adding the
context parameter in the correct position for each method.

In `@internal/service/user_beta_test.go`:
- Around line 37-135: Complete the context migration in the LocalAI model tests
by defining or passing the appropriate test context at every currently undefined
ctx reference, and update the obsolete Balance call to supply its required
context argument. Ensure all affected test call sites compile, then validate
with the model test suite.

---

Duplicate comments:
In `@internal/entity/models/modelscope_test.go`:
- Line 308: Complete the context-first signature migration in
internal/entity/models/modelscope_test.go: update CheckConnection at lines
308-308 and the TranscribeAudioWithSender, AudioSpeech, AudioSpeechWithSender,
and OCRFile calls at lines 334-343 to pass ctx as the first argument, preserving
all other arguments and test behavior.

---

Nitpick comments:
In `@internal/handler/searchbot.go`:
- Around line 382-384: Update the SearchBotDetail documentation comment to state
directly that the endpoint requires a beta token, and remove the comparison to
Python’s AUTH_BETA flow.

In `@internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go`:
- Line 38: Update the mock invokers in
internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go:38-38,
internal/ingestion/component/parser_dispatch_test.go:433-433, and
internal/ingestion/component/parser_dispatch_test.go:511-511 to assert that the
received ctx matches a sentinel context supplied by each test; ensure the
corresponding PDF-vision dispatch test setups invoke the component with that
sentinel so context propagation is verified.

In `@internal/service/citation_test.go`:
- Around line 248-260: Update fakeEmbedder in
internal/service/citation_test.go:248-260 and spyEmbedDriver in
internal/service/graph/retrieval_test.go:327-328 to retain the received context,
then add assertions that InsertCitations and buildSearchExprs, respectively,
forward the caller’s context to Embed; ensure the tests fail if
context.Background() is substituted.

In `@internal/service/user.go`:
- Line 635: Remove the unused ctx parameter from UserService.GetUserProfile,
keeping it as a formatter over entity.User. Update all five call sites in
internal/handler/user.go at lines 94, 175, 261, 385, and 727 to invoke the
method with only the user argument.
🪄 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: b427339b-29c0-4d29-a89b-9146e7387692

📥 Commits

Reviewing files that changed from the base of the PR and between ca6195e and 3ec9754.

📒 Files selected for processing (87)
  • internal/admin/handler.go
  • internal/agent/audio/tts_dispatch_test.go
  • internal/cli/user_command.go
  • internal/dao/user.go
  • internal/entity/models/302ai.go
  • internal/entity/models/302ai_test.go
  • internal/entity/models/aliyun_test.go
  • internal/entity/models/anthropic_test.go
  • internal/entity/models/astraflow_test.go
  • internal/entity/models/avian_test.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/cometapi_test.go
  • internal/entity/models/deepinfra_test.go
  • internal/entity/models/deepseek_test.go
  • internal/entity/models/fishaudio_test.go
  • internal/entity/models/gitee_test.go
  • internal/entity/models/google_test.go
  • internal/entity/models/gpustack_test.go
  • internal/entity/models/groq_test.go
  • internal/entity/models/hunyuan_test.go
  • internal/entity/models/jiekouai_test.go
  • internal/entity/models/jina_test.go
  • internal/entity/models/llm_test.go
  • internal/entity/models/localai_test.go
  • internal/entity/models/longcat_test.go
  • internal/entity/models/minimax_test.go
  • internal/entity/models/mistral_test.go
  • internal/entity/models/modelscope_test.go
  • internal/entity/models/moonshot_test.go
  • internal/entity/models/novita_test.go
  • internal/entity/models/nvidia_rerank_test.go
  • internal/entity/models/ollama_test.go
  • internal/entity/models/perplexity_test.go
  • internal/entity/models/ppio_test.go
  • internal/entity/models/ragcon_test.go
  • internal/entity/models/replicate_test.go
  • internal/entity/models/sse_scanner_buffer_test.go
  • internal/entity/models/togetherai_test.go
  • internal/entity/models/tokenhub_test.go
  • internal/entity/models/tokenpony_test.go
  • internal/entity/models/upstage_test.go
  • internal/entity/models/vllm_rerank_test.go
  • internal/entity/models/volcengine_test.go
  • internal/entity/models/voyage_test.go
  • internal/entity/models/xai_test.go
  • internal/entity/models/xiaomi_test.go
  • internal/entity/models/xinference_test.go
  • internal/entity/models/xunfei_test.go
  • internal/handler/auth.go
  • internal/handler/bot_test.go
  • internal/handler/chunk_test.go
  • internal/handler/searchbot.go
  • internal/handler/searchbot_detail_test.go
  • internal/handler/user.go
  • internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go
  • internal/ingestion/component/parser_dispatch_test.go
  • internal/ingestion/component/tokenizer_unit_test.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/task/embedder_test.go
  • internal/parser/parser/audio_parser_test.go
  • internal/parser/parser/docx_parser.go
  • internal/parser/parser/docx_parser_cgo_test.go
  • internal/parser/parser/email_parser_test.go
  • internal/parser/parser/markdown_parser_test.go
  • internal/parser/parser/parse_result_test.go
  • internal/parser/parser/parse_with_result_test.go
  • internal/parser/parser/pdf_parser_cgo_test.go
  • internal/parser/parser/pdf_parser_docling_test.go
  • internal/parser/parser/pdf_parser_fixture_cgo_test.go
  • internal/parser/parser/pdf_parser_mineru_test.go
  • internal/parser/parser/pdf_parser_opendataloader_test.go
  • internal/parser/parser/pdf_parser_paddleocr_test.go
  • internal/parser/parser/pdf_parser_somark_test.go
  • internal/parser/parser/pdf_parser_tcadp_test.go
  • internal/parser/parser/picture_parser_test.go
  • internal/parser/parser/ppt_parser_cgo_test.go
  • internal/parser/parser/xls_tcadp_test.go
  • internal/router/router.go
  • internal/service/chunk/chunk_test.go
  • internal/service/citation_test.go
  • internal/service/file/file_content_test.go
  • internal/service/file/file_test.go
  • internal/service/graph/retrieval_test.go
  • internal/service/graph/search_test.go
  • internal/service/memory.go
  • internal/service/user.go
  • internal/service/user_beta_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/service/memory.go
  • internal/parser/parser/docx_parser.go
  • internal/ingestion/task/embedder_test.go
  • internal/service/graph/search_test.go

}

func (f *fakeTTSDispatcher) AudioSpeech(
ctx context.Context,

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that the request context reaches the dispatcher.

The fake accepts ctx but discards it, so this test cannot detect broken context propagation. Store the context and assert a sentinel value from the context passed to fn.

🤖 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 `@internal/agent/audio/tts_dispatch_test.go` at line 54, Update the fake
dispatcher in the test around its fn callback to retain the received ctx instead
of discarding it, then assert that the stored context contains the expected
sentinel value from the request context. Ensure the test verifies context
propagation through the dispatcher.

Comment thread internal/dao/user.go
Comment on lines +39 to 41
func (dao *UserDAO) GetByID(ctx context.Context, id uint) (*entity.User, error) {
var user entity.User
err := DB.First(&user, id).Error

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C2 'func \(.*UserDAO\) (GetByID|GetByEmail|GetByAccessToken|GetByTenantID|Update)' internal/dao
rg -n -C2 'func \(.*(APITokenDAO|TenantDAO)\)' internal/dao
rg -n -C2 'WithContext\(ctx\)' internal/dao internal/service
rg -n 'gorm.io/gorm' go.mod go.sum

Repository: infiniflow/ragflow

Length of output: 15649


🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline internal/service/user.go --view expanded >/tmp/user_service_outline.txt
ast-grep outline internal/dao/user.go --view expanded >/tmp/user_dao_outline.txt
ast-grep outline internal/dao/api_token.go --view expanded >/tmp/api_token_dao_outline.txt
ast-grep outline internal/dao/tenant.go --view expanded >/tmp/tenant_dao_outline.txt
ast-grep outline internal/dao/user_tenant.go --view expanded >/tmp/user_tenant_dao_outline.txt

printf '\n== internal/service/user.go ==\n'
sed -n '1,220p' /tmp/user_service_outline.txt
printf '\n== internal/dao/user.go ==\n'
sed -n '1,220p' /tmp/user_dao_outline.txt
printf '\n== internal/dao/api_token.go ==\n'
sed -n '1,220p' /tmp/api_token_dao_outline.txt
printf '\n== internal/dao/tenant.go ==\n'
sed -n '1,220p' /tmp/tenant_dao_outline.txt
printf '\n== internal/dao/user_tenant.go ==\n'
sed -n '1,260p' /tmp/user_tenant_dao_outline.txt

Repository: infiniflow/ragflow

Length of output: 14112


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the exact service methods and nearby DAO calls mentioned in the review note.
sed -n '360,450p' internal/service/user.go
printf '\n----\n'
sed -n '580,620p' internal/service/user.go
printf '\n----\n'
sed -n '730,835p' internal/service/user.go
printf '\n----\n'
sed -n '870,930p' internal/service/user.go
printf '\n----\n'
sed -n '998,1118p' internal/service/user.go
printf '\n----\n'
sed -n '1,130p' internal/dao/user.go
printf '\n----\n'
sed -n '1,110p' internal/dao/api_token.go
printf '\n----\n'
sed -n '1,130p' internal/dao/tenant.go
printf '\n----\n'
sed -n '55,95p' internal/dao/user_tenant.go

Repository: infiniflow/ragflow

Length of output: 28153


Propagate ctx into the DAO layer

GetByID still drops its ctx, and the other request-scoped paths here still call context-less DAO reads/updates. Cancellation and deadlines never reach GORM.

  • internal/dao/user.go: use DB.WithContext(ctx) in GetByID.
  • Thread ctx through the DAO calls in LoginByEmail, GetUserByToken, UpdateUserSettings, ChangePassword, SetTenantInfo, GetUserByAPIToken, GetAPITokenByBeta, and GetUserByBetaAPIToken.
📍 Affects 2 files
  • internal/dao/user.go#L39-L41 (this comment)
  • internal/service/user.go#L392-L417
  • internal/service/user.go#L424-L426
  • internal/service/user.go#L589-L609
  • internal/service/user.go#L740-L801
  • internal/service/user.go#L808-L826
  • internal/service/user.go#L878-L899
  • internal/service/user.go#L1004-L1029
  • internal/service/user.go#L1048-L1069
  • internal/service/user.go#L1081-L1110
🤖 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 `@internal/dao/user.go` around lines 39 - 41, Propagate request contexts
through the user DAO paths so GORM honors cancellation and deadlines: update
internal/dao/user.go lines 39-41 in UserDAO.GetByID to use DB.WithContext(ctx),
and update the DAO calls used by LoginByEmail, GetUserByToken,
UpdateUserSettings, ChangePassword, SetTenantInfo, GetUserByAPIToken,
GetAPITokenByBeta, and GetUserByBetaAPIToken in internal/service/user.go lines
392-417, 424-426, 589-609, 740-801, 808-826, 878-899, 1004-1029, 1048-1069, and
1081-1110 to pass their existing ctx through.

Comment thread internal/entity/models/localai_test.go Resolved
Comment thread internal/entity/models/novita_test.go Resolved
Comment thread internal/handler/auth.go
Comment on lines +41 to +44
GetUserByToken(ctx context.Context, authorization string) (*entity.User, common.ErrorCode, error)
GetUserByAPIToken(ctx context.Context, token string) (*entity.User, common.ErrorCode, error)
GetUserByBetaAPIToken(ctx context.Context, token string) (*entity.User, common.ErrorCode, error)
GetAPITokenByBeta(ctx context.Context, authorization string) (*entity.APIToken, error)

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

The request context is discarded by the user-service layer. The supplied implementations of GetUserByToken, GetUserByAPIToken, GetUserByBetaAPIToken, and GetAPITokenByBeta accept ctx but never use it; their DAO queries therefore continue after client cancellation.

  • internal/handler/auth.go#L41-L44: make the resolver contract meaningful by updating the corresponding user-service/DAO queries to execute with ctx (for example, GORM WithContext(ctx)), or remove context from methods that cannot honor cancellation.
  • internal/handler/searchbot.go#L393-L394: retain this request-context call once the beta-token lookup path consumes it.
📍 Affects 2 files
  • internal/handler/auth.go#L41-L44 (this comment)
  • internal/handler/searchbot.go#L393-L394
🤖 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 `@internal/handler/auth.go` around lines 41 - 44, The user-service methods
GetUserByToken, GetUserByAPIToken, GetUserByBetaAPIToken, and GetAPITokenByBeta
currently discard request cancellation; update their service and DAO query paths
to execute with the supplied ctx, such as via GORM WithContext(ctx), or remove
ctx only if cancellation cannot be supported. In internal/handler/auth.go lines
41-44, make the resolver contract match the implementation; in
internal/handler/searchbot.go lines 393-394, retain the existing request-context
call because the beta-token lookup must consume it.

Comment on lines +12 to +16
ctx := t.Context()
p := NewDOCXParser()
p.outputFormat = "json"
data := minimalDOCX(t, "Hello from JSON path")
res := p.ParseWithResult("sample.docx", data)
res := p.ParseWithResult(ctx, "sample.docx", data)

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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Update the no-CGO DOCX stub to the context-aware signature.

internal/parser/parser/office_parsers_no_cgo.go still exposes ParseWithResult(filename string, _ []byte), while these tests now call ParseWithResult(ctx, filename, data). The non-CGO parser path will therefore fail to compile once the shared parser contract is context-aware. Update the DOCX stub, and the sibling office stubs, to accept and ignore ctx.

Also applies to: 37-48, 61-68, 81-84

🤖 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 `@internal/parser/parser/docx_parser_cgo_test.go` around lines 12 - 16, Update
the no-CGO office parser stubs, including DOCX ParseWithResult and the sibling
methods in office_parsers_no_cgo.go, to match the context-aware shared parser
signatures by accepting a context argument and ignoring it where unused.
Preserve their existing stub behavior and return values.

Comment on lines +29 to +32
ctx := t.Context()
p := NewPPTXParser()
data := buildPPTX(t, "Hello World")
res := p.ParseWithResult("test.pptx", data)
res := p.ParseWithResult(ctx, "test.pptx", data)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n -A2 'func \(p \*(DOCXParser|DOCParser|PPTParser|PPTXParser)\) ParseWithResult' internal/parser/parser/office_parsers_no_cgo.go

Repository: infiniflow/ragflow

Length of output: 763


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== parser interface ==\n'
rg -n -A4 -B2 'type ParseResultProducer|ParseWithResult\(' internal/parser/parser | sed -n '1,220p'

printf '\n== no-cgo stubs ==\n'
cat -n internal/parser/parser/office_parsers_no_cgo.go | sed -n '1,220p'

Repository: infiniflow/ragflow

Length of output: 19691


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== no-cgo test header and calls ==\n'
cat -n internal/parser/parser/office_parsers_nocgo_test.go | sed -n '1,120p'

printf '\n== interface declaration ==\n'
rg -n -A3 -B3 'type ParseResultProducer interface|ParseWithResult\(ctx context.Context' internal/parser/parser | sed -n '1,120p'

Repository: infiniflow/ragflow

Length of output: 10573


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== parser factory and interface uses ==\n'
rg -n -A4 -B4 'GetParser|ParseResultProducer|NewDOCXParser\(|NewDOCParser\(|NewPPTParser\(|NewPPTXParser\(' internal/parser/parser | sed -n '1,260p'

Repository: infiniflow/ragflow

Length of output: 18728


Update the !cgo office parser stubs and tests to the ctx-first signature.

internal/parser/parser/office_parsers_no_cgo.go still defines ParseWithResult(filename, []byte) on DOCXParser, DOCParser, PPTParser, and PPTXParser, while ParseResultProducer now requires ParseWithResult(ctx, filename, data). The !cgo test in internal/parser/parser/office_parsers_nocgo_test.go still calls the old form too. Bring both over to the new contract so !cgo builds keep compiling.

🤖 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 `@internal/parser/parser/ppt_parser_cgo_test.go` around lines 29 - 32, Update
the !cgo ParseWithResult methods on DOCXParser, DOCParser, PPTParser, and
PPTXParser in office_parsers_no_cgo.go to accept ctx, filename, and data in the
new order, matching ParseResultProducer while preserving stub behavior. Update
the !cgo tests, including the call in office_parsers_nocgo_test.go, to pass the
context as the first argument.

@JinHai-CN
JinHai-CN merged commit d19a036 into infiniflow:main Jul 22, 2026
3 checks passed

@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 (2)
internal/entity/models/togetherai.go (1)

441-517: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Attach ctx to the TogetherAI requests.

Rerank, TranscribeAudio, AudioSpeech, and AudioSpeechWithSender accept ctx but still build context-less requests, so caller cancellation and deadlines are ignored. Use http.NewRequestWithContext(ctx, ...) in each path.

🤖 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 `@internal/entity/models/togetherai.go` around lines 441 - 517, Update
TogetherAIModel.Rerank, TranscribeAudio, AudioSpeech, and AudioSpeechWithSender
in internal/entity/models/togetherai.go (Rerank lines 441-517; TranscribeAudio
lines 519-624; AudioSpeech lines 630-688; AudioSpeechWithSender lines 690-774)
to construct each HTTP request with http.NewRequestWithContext(ctx, ...),
preserving the existing request behavior while ensuring caller cancellation and
deadlines reach the TogetherAI API calls.

Source: Coding guidelines

internal/entity/models/jina.go (1)

242-242: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Attach ctx to Jina rerank and model-list requests.

These methods now accept ctx, but their bodies were not changed to use it. Rerank and ListModels therefore continue after request cancellation; CheckConnection forwarding ctx cannot fix that downstream. Build their HTTP requests with the supplied context. Based on learnings, retain the existing client-level timeout rather than adding another overall request timeout.

Also applies to: 320-320

🤖 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 `@internal/entity/models/jina.go` at line 242, Update JinaModel.Rerank and the
corresponding ListModels method to build their HTTP requests with the supplied
ctx, ensuring cancellation propagates through rerank and model-list calls.
Preserve the existing client-level timeout and do not add a separate request
timeout; keep CheckConnection’s ctx forwarding unchanged.

Source: Learnings

🤖 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 `@internal/entity/models/jina.go`:
- Line 242: Update JinaModel.Rerank and the corresponding ListModels method to
build their HTTP requests with the supplied ctx, ensuring cancellation
propagates through rerank and model-list calls. Preserve the existing
client-level timeout and do not add a separate request timeout; keep
CheckConnection’s ctx forwarding unchanged.

In `@internal/entity/models/togetherai.go`:
- Around line 441-517: Update TogetherAIModel.Rerank, TranscribeAudio,
AudioSpeech, and AudioSpeechWithSender in internal/entity/models/togetherai.go
(Rerank lines 441-517; TranscribeAudio lines 519-624; AudioSpeech lines 630-688;
AudioSpeechWithSender lines 690-774) to construct each HTTP request with
http.NewRequestWithContext(ctx, ...), preserving the existing request behavior
while ensuring caller cancellation and deadlines reach the TogetherAI API calls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bb931719-8d9f-4df8-a589-9bfa83e94c28

📥 Commits

Reviewing files that changed from the base of the PR and between 3ec9754 and dc6d1aa.

📒 Files selected for processing (98)
  • internal/entity/models/302ai.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/anthropic.go
  • internal/entity/models/astraflow.go
  • internal/entity/models/avian.go
  • internal/entity/models/azure_openai.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/cohere.go
  • internal/entity/models/cometapi.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/funasr.go
  • internal/entity/models/futurmix.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/groq.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/jina.go
  • internal/entity/models/jina_test.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/localai_test.go
  • internal/entity/models/longcat.go
  • internal/entity/models/longcat_test.go
  • internal/entity/models/mineru.go
  • internal/entity/models/mineru_local.go
  • internal/entity/models/minimax.go
  • internal/entity/models/minimax_test.go
  • internal/entity/models/mistral.go
  • internal/entity/models/mistral_test.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/modelscope_test.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/moonshot_test.go
  • internal/entity/models/n1n.go
  • internal/entity/models/novita.go
  • internal/entity/models/novita_test.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/nvidia_rerank_test.go
  • internal/entity/models/ollama.go
  • internal/entity/models/ollama_test.go
  • internal/entity/models/openai.go
  • internal/entity/models/openai_test.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/openrouter_test.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/paddleocr.go
  • internal/entity/models/paddleocr_local.go
  • internal/entity/models/perplexity.go
  • internal/entity/models/perplexity_test.go
  • internal/entity/models/ppio.go
  • internal/entity/models/ppio_test.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/qiniu_test.go
  • internal/entity/models/ragcon.go
  • internal/entity/models/ragcon_test.go
  • internal/entity/models/reasoning_family_provider_test.go
  • internal/entity/models/replicate.go
  • internal/entity/models/replicate_test.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/siliconflow_test.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/timeout_test.go
  • internal/entity/models/togetherai.go
  • internal/entity/models/togetherai_test.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenhub_test.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/tokenpony_test.go
  • internal/entity/models/tool_call_test.go
  • internal/entity/models/upstage.go
  • internal/entity/models/upstage_test.go
  • internal/entity/models/vllm.go
  • internal/entity/models/vllm_rerank_test.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/volcengine_test.go
  • internal/entity/models/voyage.go
  • internal/entity/models/voyage_test.go
  • internal/entity/models/xai.go
  • internal/entity/models/xai_test.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/xiaomi_test.go
  • internal/entity/models/xinference.go
  • internal/entity/models/xinference_test.go
  • internal/entity/models/xunfei.go
  • internal/entity/models/xunfei_test.go
  • internal/entity/models/zhipu-ai.go
  • internal/entity/models/zhipu-ai_test.go
  • internal/entity/models/zhipu_ai_test.go
  • internal/parser/parser/xlsx_parse_method_test.go
  • internal/service/agent.go
  • internal/service/memory.go
🚧 Files skipped from review as they are similar to previous changes (32)
  • internal/service/agent.go
  • internal/entity/models/ollama_test.go
  • internal/entity/models/vllm_rerank_test.go
  • internal/entity/models/futurmix.go
  • internal/entity/models/modelscope_test.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/avian.go
  • internal/entity/models/xai_test.go
  • internal/entity/models/paddleocr.go
  • internal/entity/models/jina_test.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/mineru_local.go
  • internal/service/memory.go
  • internal/entity/models/anthropic.go
  • internal/entity/models/google.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/voyage_test.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/xinference.go
  • internal/entity/models/upstage_test.go
  • internal/entity/models/ppio.go
  • internal/entity/models/replicate.go
  • internal/entity/models/localai_test.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/cohere.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/longcat_test.go
  • internal/entity/models/mistral_test.go
  • internal/entity/models/xinference_test.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant