Repository navigation
fix(ingestion): improve Extractor/LLM robustness and Python->Go parity - #17470
Conversation
- 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.
📝 WalkthroughWalkthroughThe 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. ChangesExtractor reliability and processing
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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 winChunk text gets embedded twice into the LLM prompt when using
{field_name}placeholders.
substituteChunkPlaceholdersreplaces{text}/{chunks}incallIn.prompt/callIn.systemPromptwith the chunk's own text, butc.call(timeoutCtx, db, callIn, text)still passes the non-emptytextaschunkText. Insidecall()→buildExtractorMessages, thatchunkTextis 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 callingc.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 winStrengthen 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 inextractor.golines 624-631). An exact-equality assertion onuserContentwould 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
📒 Files selected for processing (9)
internal/agent/component/llm_retry.gointernal/common/retry.gointernal/common/retry_test.gointernal/ingestion/component/chunker/presentation.gointernal/ingestion/component/extractor.gointernal/ingestion/component/extractor_tag.gointernal/ingestion/component/extractor_tag_test.gointernal/ingestion/component/extractor_test.gointernal/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.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/common/retry.go (1)
34-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove 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
📒 Files selected for processing (5)
internal/agent/component/llm_retry.gointernal/common/retry.gointernal/common/retry_test.gointernal/ingestion/component/extractor.gointernal/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
| 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 | ||
| } |
There was a problem hiding this comment.
🩺 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 -SRepository: 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)}")
PYRepository: 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]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@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
📒 Files selected for processing (2)
internal/ingestion/component/extractor.gointernal/ingestion/component/extractor_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/ingestion/component/extractor.go
| // 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) | ||
| } | ||
| }) | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 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.
| // 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.
|
@yuzhichang @yingfeng pls help to review |
|
LGTM |
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]>
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.
internal/common/retry.go):RetryWithBackoffwith exponential backoff (default 3 retries, 2s initial delay, capped at 1m), context-aware sleep, and amaxRetries<=0fast path. Covered byinternal/common/retry_test.go.agent/component/llm_retry.gonow delegates tocommon.RetryWithBackoffinstead of an inline loop (behavior preserved: ctx cancellation short-circuits the backoff).extractor.go):call()now retries transient LLM failures viaRetryWithBackoff(retry exhaustion fails the chunk instead of silently skipping).temperature = 0.2, matching Pythongenerator.py:230,245.task_executor.py:444-448), with mutex-guarded map writes to avoid data races.{field_name}placeholders (including{chunks}-> chunk text) inprompt/system_promptbefore the call, mirroring Pythonstring_format(extractor.py:102-103); unmatched placeholders are left as-is.llm_idis empty (task_executor.py:573-574).strings.LastIndex) in `cleanExtractionResult`.extractor_tag.go): drops thein.llmID != ""guards so an emptyllm_idno longer skips tagging (uses the tenant default model), and strips `` greedily inparseTaggerResponse.PresentationChunkerdocstring that claimed per-slideimage/positionoutput (the PPTX path emits none — unlike PDF), and removes a staledocs/migration_python_go_diff.mdreference inmedia_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).gofmtand lefthook pre-commit checks pass.Note: the personal
docs/migration_python_go_diff.mdworking notebook in the tree is intentionally not part of this PR.