Skip to content

fix(ingestion): fit extractor and tagger prompts to model content_length - #18095

Merged
yuzhichang merged 9 commits into
infiniflow:mainfrom
jay77721:pr/4-ingestion-messagefit
Aug 12, 2026
Merged

yuzhichang merged 9 commits into
infiniflow:mainfrom
jay77721:pr/4-ingestion-messagefit

Conversation

@jay77721

@jay77721 jay77721 commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Trim Extractor call prompts and the automatic tagger prompt to the chat model's context window (content_length) before sending, so oversized chunks or tag files are trimmed instead of rejected by the provider with a context-length error. Uses the shared messagefit package (#18091) and dao.ResolveModelContentLength (#18106).

Changes

  • internal/ingestion/component/extractor.go:
    • fitExtractorMessages: shared helper wrapping messagefit.Fit (feat(component): add shared message-fit package #18091), adapted to the non-mutating API (kept + keptIdx); drops entries the fitter removed and returns a clear error instead of sending a conversation whose final user turn was trimmed to empty.
    • Guards: a retained system message must have non-empty content (a system prompt kept but trimmed to empty carries no extraction contract), and the final user turn must be non-empty. The guards only apply when the input actually had a system message — user-only prompts remain valid.
    • extractorContextLength: resolves content_length for the effective model through the shared dao.ResolveModelContentLength (feat(dao): add shared ResolveModelContentLength helper #18106); the private resolveExtractorModelContextLength copy is removed. When llm_id is empty it resolves the tenant default chat model (mirroring resolveExtractorChatTarget), so the default-model path gets fitting too.
    • extractorContextFitBudget: 97% of the resolved context window (clamped to >= 1 so messagefit never falls into its 8192 default).
    • callRaw returns the fitting error directly instead of retrying an empty-user request.
  • internal/ingestion/component/extractor_tag.go: llmTagChunk uses the shared helper; skips tagging (with a warning) when fitting fails.
  • dao.ResolveModelContentLength (feat(dao): add shared ResolveModelContentLength helper #18106, merged) resolves content_length; no copies are carried on this branch.
  • Tests: fit guard (rejects empty user turn / keeps user turn / rejects emptied system prompt / user-only prompts without a system prompt keep working), extractorContextLength resolution paths (UUID, pinned/composite default, unknown, nil-DB), budget clamp, tagger message-fit + no-context-length skip, and an end-to-end callRaw test asserting the invoker receives fitted messages within the budget (TestExtractorComponent_CallRaw_FitsBeforeInvoke).

Testing

Known limitations (follow-up)

dao.ResolveModelContentLength (from #18106) currently reads content_length from the provider catalog only; per-model max_tokens overrides in tenant_model.extra are not honored yet (Python resolves them via model_extra.get("max_tokens") or 8192). Models absent from the catalog therefore get no fitting here (extractor passes prompts through untrimmed). A follow-up PR will honor the extra["max_tokens"] override — tracked alongside #18106.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds token-budget fitting for message lists. Extractor and tag-generation requests resolve model context lengths, trim messages before LLM calls, and validate that retained messages include a non-empty final user turn.

Changes

Message fitting and extractor integration

Layer / File(s) Summary
Message fitting core
internal/component/messagefit/messagefit.go, internal/component/messagefit/messagefit_test.go
Adds Message and Fit. The fitter applies a default budget, retains system and latest non-system messages, truncates content, clears dropped messages, and returns the token count. Tests cover retention, truncation, default budgets, exact limits, and empty inputs.
Model context-length resolution
internal/dao/model_context.go, internal/dao/model_context_test.go
Resolves model content lengths from tenant model records, composite model references, and driver/model fallbacks. Tests cover active and inactive tenant models and unknown references.
Extractor context resolution and fitting
internal/ingestion/component/extractor.go, internal/ingestion/component/extractor_test.go
Resolves tenant or default-model context lengths, applies a 97% fitting budget with a one-token minimum, fits extractor requests before dispatch, supports test overrides, and rejects empty fitted messages or final user turns.
Tag-generation fitting integration
internal/ingestion/component/extractor_tag.go, internal/ingestion/component/extractor_tag_test.go
Fits tag-generation prompts before provider calls. Tests verify trimming with a known context length and bypassing fitting when the length is unavailable.

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

Sequence Diagram(s)

sequenceDiagram
  participant Extractor
  participant ModelResolver
  participant messagefit
  participant ChatProvider
  Extractor->>ModelResolver: resolve effective model context length
  ModelResolver-->>Extractor: return context length
  Extractor->>messagefit: fit assembled messages within budget
  messagefit-->>Extractor: return fitted messages or error
  Extractor->>ChatProvider: send fitted chat request
Loading

Possibly related PRs

Suggested labels: 🐞 bug

Suggested reviewers: xugangqiang

Poem

A rabbit fits each prompt with care,
Keeps system words and user fare.
Middle messages hop away,
Before the chat request goes astray.
Within the token bounds, they stay.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% 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.
Title check ✅ Passed The title clearly and concisely describes fitting Extractor and tagger prompts to the model context.
Description check ✅ Passed The description includes the required Summary section and provides clear scope, implementation details, testing results, dependencies, and known limitations.

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.

@jay77721 jay77721 added the ci Continue Integration label Aug 11, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
internal/ingestion/component/extractor_test.go (1)

1796-1800: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the review-history phrase.

review feedback does not describe test behavior. Keep the explanation of the empty-user-turn condition.

As per coding guidelines, keep documentation aligned with current runtime behavior rather than migration history.

🤖 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 1796 - 1800,
Update the comment for TestFitExtractorMessages_RejectsEmptyUserTurn to remove
the “review feedback” phrase while preserving the explanation that messagefit’s
proportional trim can empty the final user turn and the extractor should return
a clear error instead of sending an empty user message.

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/component/messagefit/messagefit_test.go`:
- Around line 33-61: Update TestFit_Step2_DropsMiddle to use a fixture matching
its description: retain the system and final user messages while making the
middle turn droppable. Pass the calculated budget to Fit instead of the
hard-coded value, assert the middle message is empty, and assert both required
retained messages are nonempty. Remove the unused budget assignment and stale
comments describing the old fixture or Step 3 behavior.

In `@internal/component/messagefit/messagefit.go`:
- Around line 93-113: Update the message-fitting logic around kept, ll, and ll2
to trim every retained system-message index rather than only msgs[sysIdx].
Allocate the available system-token budget across all retained system messages
while preserving the final non-system message allocation, then ensure
countTokensMulti never exceeds maxTokens. Add coverage for two retained system
messages plus one user message asserting the returned token count stays within
the budget.
- Around line 55-83: Update both token-budget checks in the message-fitting flow
around countTokens and keptMsgs to use <= maxTokens instead of < maxTokens,
preserving all messages when the total exactly matches the budget and accepting
retained messages that exactly fit.

---

Nitpick comments:
In `@internal/ingestion/component/extractor_test.go`:
- Around line 1796-1800: Update the comment for
TestFitExtractorMessages_RejectsEmptyUserTurn to remove the “review feedback”
phrase while preserving the explanation that messagefit’s proportional trim can
empty the final user turn and the extractor should return a clear error instead
of sending an empty user message.
🪄 Autofix

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: e3ad9cd5-62ee-4575-828b-e0652e874de2

📥 Commits

Reviewing files that changed from the base of the PR and between dd52dee and 2dacac7.

📒 Files selected for processing (6)
  • internal/component/messagefit/messagefit.go
  • internal/component/messagefit/messagefit_test.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

@jay77721

Copy link
Copy Markdown
Member Author

Two items addressed on this branch:

  1. CI failure — import cycle in test builds: extractor.go called service.ModelProviderService.ResolveModelContextLength, but the service package's tests import internal/ingestion/component to register components, producing import cycle not allowed in test for internal/service and internal/ingestion/pipeline. extractorContextLength now resolves content_length through the DAO + provider catalog directly (resolveExtractorModelContextLength, mirroring service.ResolveModelContextLength) and the service import was dropped. Verified locally: go test compile of internal/ingestion/component/..., internal/service/..., and internal/ingestion/pipeline/... all pass. (44487b5)

  2. CodeRabbit messagefit comments (Step 2 test, exact-budget <=, trim every retained system message) are all fixed in PR feat(component): add shared message-fit package #18091 (a2c290b) and synced here; the later test-assertion strengthening (0be2661) is also synced (ec61ea2).

bash build.sh --test ./internal/ingestion/component/... passes.

@jay77721

Copy link
Copy Markdown
Member Author

Updated to use the shared helper: the private resolveExtractorModelContextLength copy is removed and extractorContextLength now calls dao.ResolveModelContentLength from #18106. Depends on #18106.

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

🧹 Nitpick comments (1)
internal/dao/model_context_test.go (1)

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

Add coverage for the three-part composite reference.

splitCompositeModelRef supports model@instance@provider, but this test only covers model@provider. Add a case such as gpt-4o@instance-1@openai. The two-part case can pass while the three-part branch regresses.

As per coding guidelines, “Preserve still-valid behavior with focused tests.”

Proposed test update
 func TestResolveModelContentLength_CompositeReference(t *testing.T) {
-	if got := ResolveModelContentLength(t.Context(), nil, "gpt-4o@openai", "", ""); got != 128000 {
-		t.Fatalf("ResolveModelContentLength(gpt-4o@openai) = %d, want 128000", got)
+	for _, ref := range []string{"gpt-4o@openai", "gpt-4o@instance-1@openai"} {
+		if got := ResolveModelContentLength(t.Context(), nil, ref, "", ""); got != 128000 {
+			t.Fatalf("ResolveModelContentLength(%s) = %d, want 128000", ref, got)
+		}
 	}
 }
🤖 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/model_context_test.go` around lines 28 - 34, Add a focused
assertion to TestResolveModelContentLength_CompositeReference covering the
three-part model@instance@provider form, using a reference such as
gpt-4o@instance-1@openai and the expected content length of 128000. Keep the
existing two-part case 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.

Nitpick comments:
In `@internal/dao/model_context_test.go`:
- Around line 28-34: Add a focused assertion to
TestResolveModelContentLength_CompositeReference covering the three-part
model@instance@provider form, using a reference such as gpt-4o@instance-1@openai
and the expected content length of 128000. Keep the existing two-part case
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1ce0f7de-da8b-46f0-b1c0-427c7fd900c9

📥 Commits

Reviewing files that changed from the base of the PR and between 1bb138b and d3b1d5b.

📒 Files selected for processing (5)
  • internal/component/messagefit/messagefit.go
  • internal/component/messagefit/messagefit_test.go
  • internal/dao/model_context.go
  • internal/dao/model_context_test.go
  • internal/ingestion/component/extractor.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/component/messagefit/messagefit.go
  • internal/ingestion/component/extractor.go

@jay77721
jay77721 force-pushed the pr/4-ingestion-messagefit branch from d3b1d5b to 0f44156 Compare August 11, 2026 09:00

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

🧹 Nitpick comments (2)
internal/ingestion/component/extractor_test.go (2)

1852-1854: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Remove the unused global DAO database replacement.

Every test passes db to extractorContextLength. That function passes the same handle to defaultChatModelRef and dao.ResolveModelContentLength. The dao.DB replacement does not affect these assertions. Remove it to avoid shared test-state interference.

Proposed change
-	"ragflow/internal/dao"
@@
-	prev := dao.DB
-	dao.DB = db
-	t.Cleanup(func() { dao.DB = prev })
🤖 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 1852 - 1854,
Remove the dao.DB replacement and its t.Cleanup restoration from the test setup
around extractorContextLength. Keep passing db directly to
extractorContextLength, defaultChatModelRef, and dao.ResolveModelContentLength
as currently implemented, without introducing shared DAO state changes.

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

Remove review-history text from the test comment.

Remove the phrase “review feedback”. Describe the fitting condition and expected error only.

As per coding guidelines, keep Go doc comments aligned with the current runtime path rather than migration history.

Proposed change
-// review feedback: when messagefit's proportional trim would empty the final
+// when messagefit's proportional trim would empty the final
🤖 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 1799 - 1803,
Update the comment for TestFitExtractorMessages_RejectsEmptyUserTurn to remove
the phrase “review feedback” and describe only the proportional-trim condition
and the expected clear error when the system prompt exceeds the context budget.

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.

Nitpick comments:
In `@internal/ingestion/component/extractor_test.go`:
- Around line 1852-1854: Remove the dao.DB replacement and its t.Cleanup
restoration from the test setup around extractorContextLength. Keep passing db
directly to extractorContextLength, defaultChatModelRef, and
dao.ResolveModelContentLength as currently implemented, without introducing
shared DAO state changes.
- Around line 1799-1803: Update the comment for
TestFitExtractorMessages_RejectsEmptyUserTurn to remove the phrase “review
feedback” and describe only the proportional-trim condition and the expected
clear error when the system prompt exceeds the context budget.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 35959521-473b-4b56-93b4-3606aece0817

📥 Commits

Reviewing files that changed from the base of the PR and between d3b1d5b and b7b1c21.

📒 Files selected for processing (1)
  • internal/ingestion/component/extractor_test.go

@jay77721
jay77721 force-pushed the pr/4-ingestion-messagefit branch from 6fd2af1 to e6c292e Compare August 12, 2026 03:23
yuzhichang pushed a commit that referenced this pull request Aug 12, 2026
The agent LLM component and the ingestion Extractor component both need
to trim prompts to the model's context window before calling the
provider. Each previously did (or would do) this with its own copy of
the logic. This PR adds the shared primitive; follow-up PRs wire it into
the agent LLM component (#18092) and the ingestion Extractor/tagger
(#18095).
Trim Extractor call prompts and the automatic tagger prompt to the
chat model's context window (content_length) before sending, so
oversized chunks or tag files are trimmed instead of rejected by
the provider with a context-length error.

- fitExtractorMessages: shared helper wrapping messagefit.Fit; drops
  entries the fitter removed and returns a clear error instead of
  sending a conversation whose final user turn was trimmed to empty.
- extractorContextLength: resolves content_length for the effective
  model; when llm_id is empty it resolves the tenant default chat
  model (mirroring resolveExtractorChatTarget), so the default-model
  path gets fitting too.
- llmTagChunk: skips tagging (with a warning) when fitting fails.
extractor.go called service.ModelProviderService.ResolveModelContextLength,
but the service package's tests import internal/ingestion/component to
register components, creating an import cycle in test builds
(component -> service -> (test) component). Resolve content_length through
the DAO and the provider catalog directly (mirroring
service.ResolveModelContextLength) and drop the service import.
Drop the private resolveExtractorModelContextLength copy and use the
shared dao.ResolveModelContentLength helper introduced in the new dao
PR. Behavior is unchanged.
Add unit tests for extractorContextLength against an in-memory DB with a
tenant, provider and active gpt-4o tenant model row:
- tenant_model UUID resolves content_length via the provider catalog
- llm_id empty falls back to the tenant default chat model (pinned UUID
  and composite llm_id forms)
- unknown model references return 0 (skip fitting)
messagefit.Fit was called with the full content_length as the budget. The
cl100k tokenizer used for counting differs from each model's own tokenizer
and the per-message formatting overhead is uncounted, so a prompt trimmed
to exactly the context window could still be rejected by the provider with
a context-length error. Budget at 97% of content_length, mirroring the
agent component's contextFitBudget; clamp tiny contexts to 1 token so Fit
never falls back to its <=0 → 8192 default. Tests assert the margin and the
tagger path now trims within the margin-adjusted budget.
…ookup

Two robustness fixes in the extractor message-fitting path:

- fitExtractorMessages now requires at least one retained system message.
  The proportional trim can empty every system message when the final user
  turn alone fills the budget; sending only the user turn loses the
  extraction contract (output format, field definitions) and would silently
  produce garbage. Fail with a clear error instead.

- defaultChatModelRef returns "" when db is nil (and extractorContextLength
  falls back to the global dao.DB handle), so resolving the tenant default
  chat model without a database degrades to 0 / skip-fitting instead of
  panicking in TenantDAO.GetByID.

Tests cover both: the system-prompt-loss scenario errors, and a nil-db
default-model lookup returns 0 without panicking.
…esent

The system-prompt guard in fitExtractorMessages fired even for user-only
requests (systemPrompt is optional and defaults to empty), so any extractor
without a system prompt failed once the model's content_length was
resolvable. Track whether the input actually had a system message and only
enforce the guard then.

Also drop the unused dao.DB swap in openExtractorContextTestDB and remove
review-history phrasing from a test comment.
…essagefit API

messagefit.Fit now returns (kept, keptIdx, count) instead of clearing
dropped entries in place; rebuild fitted from keptIdx and write kept[j].
Content back to the original messages.

Because a system message kept but trimmed to empty is still reported as
kept, the system-prompt guard now requires a retained system message with
non-empty content — an emptied system prompt carries no extraction
contract and would silently produce garbage.
@jay77721
jay77721 force-pushed the pr/4-ingestion-messagefit branch from 0efd738 to 1408be4 Compare August 12, 2026 05:22
The fitExtractorMessages unit tests and the tagger test cover the fitter,
but nothing exercised the production wiring (callRaw resolves the context
length, fits, then hands the fitted messages to the invoker). Add an
end-to-end test asserting the system prompt survives, the sent total stays
within the margin-adjusted budget, and the chunk text is retained.
@jay77721
jay77721 requested a review from xugangqiang August 12, 2026 06:14
@xugangqiang
xugangqiang requested a review from yuzhichang August 12, 2026 07:39
@yuzhichang
yuzhichang merged commit 86b6f64 into infiniflow:main Aug 12, 2026
3 checks passed
@jay77721 jay77721 changed the title fix(ingestion): fit extractor and tagger prompts to model context fix(ingestion): fit extractor and tagger prompts to model content_length Aug 12, 2026
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