Skip to content

fix(ingestion): improve Extractor/LLM robustness and Python->Go parity - #17470

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:fix/extractor
Jul 28, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:fix/extractor

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR hardens the Go ingestion Extractor and LLM retry paths and closes several Python->Go parity gaps in the keyword/question/tag extraction flow.

  • Generic retry utility (internal/common/retry.go): RetryWithBackoff with exponential backoff (default 3 retries, 2s initial delay, capped at 1m), context-aware sleep, and a maxRetries<=0 fast path. Covered by internal/common/retry_test.go.
  • LLM retry reuse: agent/component/llm_retry.go now delegates to common.RetryWithBackoff instead of an inline loop (behavior preserved: ctx cancellation short-circuits the backoff).
  • Extractor LLM calls (extractor.go):
    • call() now retries transient LLM failures via RetryWithBackoff (retry exhaustion fails the chunk instead of silently skipping).
    • Sets temperature = 0.2, matching Python generator.py:230,245.
    • Runs keyword and question extraction concurrently per chunk when both are enabled (task_executor.py:444-448), with mutex-guarded map writes to avoid data races.
    • Substitutes {field_name} placeholders (including {chunks} -> chunk text) in prompt/system_prompt before the call, mirroring Python string_format (extractor.py:102-103); unmatched placeholders are left as-is.
    • Falls back to the tenant default chat model when llm_id is empty (task_executor.py:573-574).
    • Strips `` greedily (strings.LastIndex) in `cleanExtractionResult`.
  • Auto-tagging (extractor_tag.go): drops the in.llmID != "" guards so an empty llm_id no longer skips tagging (uses the tenant default model), and strips `` greedily in parseTaggerResponse.
  • Docs: fixes a misleading PresentationChunker docstring that claimed per-slide image/position output (the PPTX path emits none — unlike PDF), and removes a stale docs/migration_python_go_diff.md reference in media_dispatch.go.

Test plan

  • bash build.sh --test ./internal/common/... — passes (new retry utility + tests).
  • bash build.sh --test ./internal/ingestion/component/... — passes (extractor/chunker/schema).
  • gofmt and lefthook pre-commit checks pass.

Note: the personal docs/migration_python_go_diff.md working notebook in the tree is intentionally not part of this PR.

- Add a generic RetryWithBackoff utility (exponential backoff, ctx-aware
  sleep, capped at 1m) in internal/common.
- Use it in the agent LLM retry component and in Extractor LLM calls so
  transient failures are retried instead of giving up immediately.
- Set extractor temperature to 0.2 (Python generator.py:230,245 parity).
- Run keyword and question extraction concurrently per chunk when both are
  enabled, with mutex-guarded map writes to avoid data races.
- Substitute {field_name} placeholders (incl. {chunks} -> chunk text) in
  prompt/system_prompt before the LLM call, mirroring Python's
  string_format (extractor.py:102-103).
- Fall back to the tenant default chat model when llm_id is empty
  (task_executor.py:573-574 parity).
- Strip </think> greedily (LastIndex) in cleanExtractionResult and
  parseTaggerResponse.
- Drop the empty llm_id guard in runAutoTags so tagging is not skipped.
- Fix a misleading PresentationChunker docstring and remove a stale doc
  reference in media_dispatch.go.
@xugangqiang xugangqiang added the ci Continue Integration label Jul 28, 2026
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change centralizes retry behavior, integrates retry classification into extractor LLM calls, enables concurrent metadata extraction, adds chunk placeholders and default model resolution, and updates reasoning-tag parsing, tag dispatch, tests, and related comments.

Changes

Extractor reliability and processing

Layer / File(s) Summary
Shared retry foundation
internal/common/retry.go, internal/common/retry_test.go, internal/agent/component/llm_retry.go
Adds configurable exponential backoff with cancellation, retry predicates, exported defaults, comprehensive tests, and shared retry handling for agent chat calls.
Extractor processing and chat integration
internal/ingestion/component/extractor.go, internal/ingestion/component/extractor_test.go
Adds retry classification, temperature overrides, concurrent keyword/question extraction, placeholder substitution, tenant default chat-model resolution, and corresponding tests.
Response and tag processing
internal/ingestion/component/extractor.go, internal/ingestion/component/extractor_tag.go, internal/ingestion/component/extractor_tag_test.go, internal/ingestion/component/chunker/presentation.go, internal/ingestion/component/media_dispatch.go
Uses the last reasoning closing tag, updates phase-2 tag dispatch, adds parsing coverage, and revises ingestion comments.

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

Sequence Diagram(s)

sequenceDiagram
  participant ExtractorComponent.Invoke
  participant ExtractorComponent.call
  participant RetryWithBackoff
  participant ChatInvoker
  ExtractorComponent.Invoke->>ExtractorComponent.call: prepare chunk prompts
  ExtractorComponent.call->>RetryWithBackoff: submit chat callback
  RetryWithBackoff->>ChatInvoker: Chat request with temperature
  ChatInvoker-->>RetryWithBackoff: response or error
  RetryWithBackoff-->>ExtractorComponent.call: final response or error
Loading

Possibly related PRs

Suggested labels: 🐞 bug, ☯️ refactor

Suggested reviewers: jinhai-cn, qinling0210, yuzhichang

Poem

I’m a rabbit, hopping through retries,
With prompts that bloom in chunk-sized skies.
Think tags yield to the final gate,
While keywords and questions coordinate.
Backoff moonlight keeps calls bright—
Squeak, the extractor works just right!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately reflects the main extractor, retry, and parity improvements in the PR.
Description check ✅ Passed The description includes a clear Summary and a Test plan, and it provides enough context for reviewers.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
internal/ingestion/component/extractor.go (1)

624-636: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Chunk text gets embedded twice into the LLM prompt when using {field_name} placeholders.

substituteChunkPlaceholders replaces {text}/{chunks} in callIn.prompt/callIn.systemPrompt with the chunk's own text, but c.call(timeoutCtx, db, callIn, text) still passes the non-empty text as chunkText. Inside call() → buildExtractorMessages, that chunkText is unconditionally appended again (see lines 1048-1054), so the chunk content is duplicated in the final user message whenever the prompt template references {text}/{chunks} — the exact scenario the new placeholder feature targets. The keyword/question helper paths avoid this correctly by calling c.call(ctx, db, kwIn, "") since their prompt already embeds the text.

🐛 Proposed fix: suppress the automatic chunkText append once it has been substituted into the prompt
 			if in.fieldName != "" {
 				// Substitute {field_name} placeholders with current
 				// chunk field values, mirroring Python's
 				// string_format at extractor.py:103.
 				callIn := in
-				callIn.prompt = substituteChunkPlaceholders(in.prompt, ck, text)
-				callIn.systemPrompt = substituteChunkPlaceholders(in.systemPrompt, ck, text)
-				ans, callErr := c.call(timeoutCtx, db, callIn, text)
+				substitutedPrompt := substituteChunkPlaceholders(in.prompt, ck, text)
+				substitutedSystemPrompt := substituteChunkPlaceholders(in.systemPrompt, ck, text)
+				callIn.prompt = substitutedPrompt
+				callIn.systemPrompt = substitutedSystemPrompt
+				callChunkText := text
+				if substitutedPrompt != in.prompt || substitutedSystemPrompt != in.systemPrompt {
+					// The chunk text was already embedded via a
+					// placeholder; don't append it again.
+					callChunkText = ""
+				}
+				ans, callErr := c.call(timeoutCtx, db, callIn, callChunkText)
🤖 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/extractor.go` around lines 624 - 636, Update the
fieldName placeholder path around substituteChunkPlaceholders and c.call so the
chunk text is not appended a second time after being embedded in the prompt;
pass the empty chunkText value used by the keyword/question helper paths while
preserving the existing placeholder substitution and error handling.
🧹 Nitpick comments (1)
internal/ingestion/component/extractor_test.go (1)

1036-1067: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Strengthen assertions to exact-match to catch prompt duplication.

Both tests use strings.Contains(userContent, ...), which would still pass if the chunk text were duplicated in the final prompt (see the duplication bug flagged in extractor.go lines 624-631). An exact-equality assertion on userContent would catch this class of regression.

Also applies to: 1072-1103

🤖 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/extractor_test.go` around lines 1036 - 1067,
Strengthen the assertions in
TestExtractorComponent_Invoke_SubstitutesPlaceholders and the corresponding test
around the second highlighted range by comparing userContent against the exact
expected prompt string. Replace the substring checks with exact-match assertions
that verify the placeholder is replaced once and the chunk text is not
duplicated.
🤖 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/ingestion/component/extractor.go`:
- Around line 624-636: Update the fieldName placeholder path around
substituteChunkPlaceholders and c.call so the chunk text is not appended a
second time after being embedded in the prompt; pass the empty chunkText value
used by the keyword/question helper paths while preserving the existing
placeholder substitution and error handling.

---

Nitpick comments:
In `@internal/ingestion/component/extractor_test.go`:
- Around line 1036-1067: Strengthen the assertions in
TestExtractorComponent_Invoke_SubstitutesPlaceholders and the corresponding test
around the second highlighted range by comparing userContent against the exact
expected prompt string. Replace the substring checks with exact-match assertions
that verify the placeholder is replaced once and the chunk text is not
duplicated.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e2df294a-4dd7-44dc-b6c1-bbcd38481820

📥 Commits

Reviewing files that changed from the base of the PR and between 0fdefb2 and e5058fa.

📒 Files selected for processing (9)
  • internal/agent/component/llm_retry.go
  • internal/common/retry.go
  • internal/common/retry_test.go
  • internal/ingestion/component/chunker/presentation.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/extractor_tag.go
  • internal/ingestion/component/extractor_tag_test.go
  • internal/ingestion/component/extractor_test.go
  • internal/ingestion/component/media_dispatch.go

- Scope temperature to 0.2 only for keyword/question extraction; the
  generic field-extraction path now leaves Temperature unset to use the
  model default, matching Python's generic Extractor (generator.py).
- Merge runAutoKeywords/runAutoQuestions with their *Locked duplicates
  into single functions taking a *sync.Mutex (nil = sequential); map
  access stays race-safe under concurrency.
- retryInvoker.Invoke now returns a nil response on failure instead of
  the last partial response.
- RetryWithBackoff gains an optional shouldRetry predicate; the extractor
  chat call uses a lightweight classifier so non-transient errors
  (auth/4xx/config) stop retrying immediately. The greedy </think> strip
  already matched Python's re.sub behavior, so no change there.

Addresses review items #3, #5, #6, #7 on PR infiniflow#17470.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/common/retry.go (1)

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

Remove migration-history/compatibility wording from doc comments in both files. Both comments describe pre-PR behavior instead of the current contract, violating the guideline to keep doc comments aligned with the current runtime path and to avoid compatibility wording in documentation.

  • internal/common/retry.go#L34-L40: reword away from "preserving the original behavior" to simply state the current default (no predicate ⇒ retry on every error).
  • internal/ingestion/component/extractor.go#L802-L810: reword away from "matching the prior blind-retry behavior" to state the current fallback rule (unrecognized errors default to retryable).

As per coding guidelines, "Keep Go package comments and doc comments aligned with the current runtime path rather than migration history" and "do not add compatibility wording to comments or documentation."

🤖 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/common/retry.go` around lines 34 - 40, Remove migration-history and
compatibility wording from the doc comments at internal/common/retry.go lines
34-40 and internal/ingestion/component/extractor.go lines 802-810. In the
RetryWithBackoff documentation, state that a nil predicate retries every error;
in the extractor documentation, state that unrecognized errors default to
retryable, without referring to prior or original behavior.

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/ingestion/component/extractor.go`:
- Around line 811-829: Update isRetryableLLMError so numeric status-code checks
match standalone codes using word boundaries rather than substring matching,
preventing values such as “4000” from being treated as HTTP 400. Remove the
generic “not found” matcher and retain “model not found” only if it represents a
confirmed terminal provider error; leave the remaining retry classification
unchanged.

---

Nitpick comments:
In `@internal/common/retry.go`:
- Around line 34-40: Remove migration-history and compatibility wording from the
doc comments at internal/common/retry.go lines 34-40 and
internal/ingestion/component/extractor.go lines 802-810. In the RetryWithBackoff
documentation, state that a nil predicate retries every error; in the extractor
documentation, state that unrecognized errors default to retryable, without
referring to prior or original behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 39d5e774-081e-454c-a213-e4847a817bc6

📥 Commits

Reviewing files that changed from the base of the PR and between e5058fa and 75c360e.

📒 Files selected for processing (5)
  • internal/agent/component/llm_retry.go
  • internal/common/retry.go
  • internal/common/retry_test.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/extractor_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/agent/component/llm_retry.go
  • internal/common/retry_test.go
  • internal/ingestion/component/extractor_test.go

Comment on lines +811 to +829
func isRetryableLLMError(err error) bool {
if err == nil {
return true
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
msg := strings.ToLower(err.Error())
for _, s := range []string{
"401", "403", "unauthorized", "authentication", "api key",
"400", "bad request", "404", "not found", "model not found", "content filter",
"no driver resolved", "model_name is required", "resolve driver",
} {
if strings.Contains(msg, s) {
return false
}
}
return true
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
fd -a 'extractor.go$' . | sed 's#^\./##'

echo "== relevant file stats and outline =="
wc -l internal/ingestion/component/extractor.go
ast-grep outline internal/ingestion/component/extractor.go --view compact | sed -n '1,220p'

echo "== lines 760-860 =="
sed -n '760,860p' internal/ingestion/component/extractor.go

echo "== search isRetryableLLMError usages =="
rg -n "isRetryableLLMError|RetryWithBackoff" internal/ingestion/component/extractor.go internal/ingestion -S

Repository: infiniflow/ragflow

Length of output: 616


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== relevant lines =="
sed -n '760,850p' internal/ingestion/component/extractor.go

echo "== usages =="
rg -n "isRetryableLLMError|RetryWithBackoff|TerminalStatusCode|terminalStatusCode" internal/ingestion -S

echo "== behavioral probe for current predicate against sample error text =="
python3 - <<'PY'
import re

def is_retryable_llm_error(err):
    if err is None:
        return True
    from contextlib import nullcontext
    # emulate only the substring list from the current code; omit context errors here
    msg = err.lower()
    substrings = [
        "401", "403", "unauthorized", "authentication", "api key",
        "400", "bad request", "404", "not found", "model not found", "content filter",
        "no driver resolved", "model_name is required", "resolve driver",
    ]
    return not any(s in msg for s in substrings)

samples = [
    "maximum context length is 4000 tokens",
    "maximum context length is 4040 tokens",
    "request timeout due not found upstream",
    "unable to reach cache, not found",
    "model_name is required",
    "content filter hit",
    "API key is invalid",
    "transient route not found",
    "400 bad request invalid input",
]
for s in samples:
    print(f"{s!r}: retryable={is_retryable_llm_error(s)}")

def is_retryable_bounded(err):
    if err is None:
        return True
    msg = err.lower()
    substrings = [
        "unauthorized", "authentication", "api key", "bad request",
        "model not found", "content filter", "no driver resolved",
        "model_name is required", "resolve driver",
    ]
    codes = re.compile(r"\b40[0134]\b")
    return not any(s in msg for s in substrings) and not codes.search(msg)

print("\nbounded probe:")
for s in samples:
    print(f"{s!r}: retryable={is_retryable_bounded(s)}")
PY

Repository: infiniflow/ragflow

Length of output: 4875


Don’t let substring literals gate LLM retries.

isRetryableLLMError is passed directly to common.RetryWithBackoff, so incidental matches make transient errors non-retryable: "maximum context length is 4000 tokens" matches "400", and "not found" matches many transient lookup errors. Anchor numeric status-code literals with word boundaries and drop/invalidate the bare "not found" literal; keep the more specific "model not found" only if that exact provider message is a real terminal error.

🤖 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/extractor.go` around lines 811 - 829, Update
isRetryableLLMError so numeric status-code checks match standalone codes using
word boundaries rather than substring matching, preventing values such as “4000”
from being treated as HTTP 400. Remove the generic “not found” matcher and
retain “model not found” only if it represents a confirmed terminal provider
error; leave the remaining retry classification unchanged.

The retry predicate matched bare status-code substrings ("400",
"404", ...), so a transient timeout phrased as "context deadline
exceeded after 400ms" was misclassified as a permanent HTTP 400 and
dropped instead of retried. Match standalone status tokens with a
\b-bounded regex so "400ms"/"4000" no longer match, and add
TestIsRetryableLLMError to lock in 429/5xx staying retryable and
context/deadline being terminal.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/ingestion/component/extractor_test.go`:
- Around line 944-980: Update TestIsRetryableLLMError to rename the errors.New
case so it describes only the 400ms status-token boundary, then add an actual
fmt.Errorf("%w", context.DeadlineExceeded) wrapped-error case expecting false.
Add a separate 4000 status-token case with the expected retry classification
promised by the heuristic, and import fmt if needed.
🪄 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 Plus

Run ID: 51883db4-6060-4973-bd93-27fbad3c3631

📥 Commits

Reviewing files that changed from the base of the PR and between 75c360e and 3f0de13.

📒 Files selected for processing (2)
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/extractor_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/ingestion/component/extractor.go

Comment on lines +944 to +980
// TestIsRetryableLLMError locks in the retry-classification heuristic,
// especially the word-boundary guard that prevents a transient timeout
// message ("...after 400ms") from being misclassified as a permanent
// HTTP 400 and dropped.
func TestIsRetryableLLMError(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{name: "nil is retryable", err: nil, want: true},
{name: "context canceled is terminal", err: context.Canceled, want: false},
{name: "deadline exceeded is terminal", err: context.DeadlineExceeded, want: false},
{
name: "wrapped deadline with 400ms must stay retryable",
err: errors.New("context deadline exceeded after 400ms"),
want: true,
},
{name: "429 stays retryable", err: errors.New("429 Too Many Requests"), want: true},
{name: "503 stays retryable", err: errors.New("503 Service Unavailable"), want: true},
{name: "401 unauthorized is terminal", err: errors.New("HTTP 401 Unauthorized"), want: false},
{name: "403 forbidden is terminal", err: errors.New("403 forbidden"), want: false},
{name: "404 not found is terminal", err: errors.New("HTTP 404 Not Found"), want: false},
{name: "405 method not allowed is terminal", err: errors.New("405 Method Not Allowed"), want: false},
{name: "422 unprocessable is terminal", err: errors.New("422 Unprocessable Entity"), want: false},
{name: "bad request is terminal", err: errors.New("400 Bad Request: malformed"), want: false},
{name: "api key phrase is terminal", err: errors.New("invalid api key"), want: false},
{name: "no driver phrase is terminal", err: errors.New("no driver resolved for llm_id"), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isRetryableLLMError(tt.err); got != tt.want {
t.Errorf("isRetryableLLMError(%v) = %v, want %v", tt.err, got, tt.want)
}
})
}
}

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

Cover wrapped context errors and the 4000 boundary accurately.

Line 958 labels the 400ms string as “wrapped deadline,” but errors.New does not wrap context.DeadlineExceeded; this only tests the status-token boundary. Rename it and add an actual %w case expecting terminal behavior. Also add the 4000 case promised by the PR objective.

Suggested test additions
 		{
-			name: "wrapped deadline with 400ms must stay retryable",
+			name: "timeout text with 400ms stays retryable",
 			err:  errors.New("context deadline exceeded after 400ms"),
 			want: true,
 		},
+		{
+			name: "wrapped deadline is terminal",
+			err:  fmt.Errorf("request failed: %w", context.DeadlineExceeded),
+			want: false,
+		},
+		{
+			name: "4000 is not standalone HTTP 400",
+			err:  errors.New("upstream returned 4000"),
+			want: true,
+		},

Add the fmt import if it is not already present.

📝 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
// TestIsRetryableLLMError locks in the retry-classification heuristic,
// especially the word-boundary guard that prevents a transient timeout
// message ("...after 400ms") from being misclassified as a permanent
// HTTP 400 and dropped.
func TestIsRetryableLLMError(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{name: "nil is retryable", err: nil, want: true},
{name: "context canceled is terminal", err: context.Canceled, want: false},
{name: "deadline exceeded is terminal", err: context.DeadlineExceeded, want: false},
{
name: "wrapped deadline with 400ms must stay retryable",
err: errors.New("context deadline exceeded after 400ms"),
want: true,
},
{name: "429 stays retryable", err: errors.New("429 Too Many Requests"), want: true},
{name: "503 stays retryable", err: errors.New("503 Service Unavailable"), want: true},
{name: "401 unauthorized is terminal", err: errors.New("HTTP 401 Unauthorized"), want: false},
{name: "403 forbidden is terminal", err: errors.New("403 forbidden"), want: false},
{name: "404 not found is terminal", err: errors.New("HTTP 404 Not Found"), want: false},
{name: "405 method not allowed is terminal", err: errors.New("405 Method Not Allowed"), want: false},
{name: "422 unprocessable is terminal", err: errors.New("422 Unprocessable Entity"), want: false},
{name: "bad request is terminal", err: errors.New("400 Bad Request: malformed"), want: false},
{name: "api key phrase is terminal", err: errors.New("invalid api key"), want: false},
{name: "no driver phrase is terminal", err: errors.New("no driver resolved for llm_id"), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isRetryableLLMError(tt.err); got != tt.want {
t.Errorf("isRetryableLLMError(%v) = %v, want %v", tt.err, got, tt.want)
}
})
}
}
// TestIsRetryableLLMError locks in the retry-classification heuristic,
// especially the word-boundary guard that prevents a transient timeout
// message ("...after 400ms") from being misclassified as a permanent
// HTTP 400 and dropped.
func TestIsRetryableLLMError(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{name: "nil is retryable", err: nil, want: true},
{name: "context canceled is terminal", err: context.Canceled, want: false},
{name: "deadline exceeded is terminal", err: context.DeadlineExceeded, want: false},
{
name: "timeout text with 400ms stays retryable",
err: errors.New("context deadline exceeded after 400ms"),
want: true,
},
{
name: "wrapped deadline is terminal",
err: fmt.Errorf("request failed: %w", context.DeadlineExceeded),
want: false,
},
{name: "429 stays retryable", err: errors.New("429 Too Many Requests"), want: true},
{name: "503 stays retryable", err: errors.New("503 Service Unavailable"), want: true},
{name: "401 unauthorized is terminal", err: errors.New("HTTP 401 Unauthorized"), want: false},
{name: "403 forbidden is terminal", err: errors.New("403 forbidden"), want: false},
{name: "404 not found is terminal", err: errors.New("HTTP 404 Not Found"), want: false},
{name: "405 method not allowed is terminal", err: errors.New("405 Method Not Allowed"), want: false},
{name: "422 unprocessable is terminal", err: errors.New("422 Unprocessable Entity"), want: false},
{name: "bad request is terminal", err: errors.New("400 Bad Request: malformed"), want: false},
{name: "4000 is not standalone HTTP 400", err: errors.New("upstream returned 4000"), want: true},
{name: "api key phrase is terminal", err: errors.New("invalid api key"), want: false},
{name: "no driver phrase is terminal", err: errors.New("no driver resolved for llm_id"), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isRetryableLLMError(tt.err); got != tt.want {
t.Errorf("isRetryableLLMError(%v) = %v, want %v", tt.err, got, tt.want)
}
})
}
}
🤖 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/extractor_test.go` around lines 944 - 980,
Update TestIsRetryableLLMError to rename the errors.New case so it describes
only the 400ms status-token boundary, then add an actual fmt.Errorf("%w",
context.DeadlineExceeded) wrapped-error case expecting false. Add a separate
4000 status-token case with the expected retry classification promised by the
heuristic, and import fmt if needed.

@xugangqiang

Copy link
Copy Markdown
Contributor Author

@yuzhichang @yingfeng pls help to review

@yuzhichang

Copy link
Copy Markdown
Member

LGTM

@yuzhichang
yuzhichang merged commit 76aaecc into infiniflow:main Jul 28, 2026
5 of 6 checks passed
buua436 pushed a commit to buua436/ragflow that referenced this pull request Jul 29, 2026
infiniflow#17470)

## Summary

This PR hardens the Go ingestion **Extractor** and **LLM retry** paths
and closes several Python->Go parity gaps in the keyword/question/tag
extraction flow.

- **Generic retry utility** (`internal/common/retry.go`):
`RetryWithBackoff` with exponential backoff (default 3 retries, 2s
initial delay, capped at 1m), context-aware sleep, and a `maxRetries<=0`
fast path. Covered by `internal/common/retry_test.go`.
- **LLM retry reuse**: `agent/component/llm_retry.go` now delegates to
`common.RetryWithBackoff` instead of an inline loop (behavior preserved:
ctx cancellation short-circuits the backoff).
- **Extractor LLM calls** (`extractor.go`):
- `call()` now retries transient LLM failures via `RetryWithBackoff`
(retry exhaustion fails the chunk instead of silently skipping).
  - Sets `temperature = 0.2`, matching Python `generator.py:230,245`.
- Runs keyword and question extraction **concurrently** per chunk when
both are enabled (`task_executor.py:444-448`), with mutex-guarded map
writes to avoid data races.
- Substitutes `{field_name}` placeholders (including `{chunks}` -> chunk
text) in `prompt`/`system_prompt` before the call, mirroring Python
`string_format` (`extractor.py:102-103`); unmatched placeholders are
left as-is.
- Falls back to the **tenant default chat model** when `llm_id` is empty
(`task_executor.py:573-574`).
- Strips `` **greedily** (`strings.LastIndex`) in
`cleanExtractionResult`.
- **Auto-tagging** (`extractor_tag.go`): drops the `in.llmID != ""`
guards so an empty `llm_id` no longer skips tagging (uses the tenant
default model), and strips `` greedily in `parseTaggerResponse`.
- **Docs**: fixes a misleading `PresentationChunker` docstring that
claimed per-slide `image`/`position` output (the PPTX path emits none —
unlike PDF), and removes a stale `docs/migration_python_go_diff.md`
reference in `media_dispatch.go`.

## Test plan

- `bash build.sh --test ./internal/common/...` — passes (new retry
utility + tests).
- `bash build.sh --test ./internal/ingestion/component/...` — passes
(extractor/chunker/schema).
- `gofmt` and lefthook pre-commit checks pass.

Note: the personal `docs/migration_python_go_diff.md` working notebook
in the tree is intentionally **not** part of this PR.

---------

Co-authored-by: CodeBuddy <[email protected]>
@xugangqiang
xugangqiang deleted the fix/extractor branch August 7, 2026 12:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants