Skip to content

fix(dao): honor tenant-configured context window override (D22/D23) - #18171

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
jay77721:fix/model-context-extra-override
Aug 12, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
jay77721:fix/model-context-extra-override

Conversation

@jay77721

@jay77721 jay77721 commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Make ResolveModelContentLength honor the per-model custom context window length (content_length) — stored in the Python-legacy tenant_model.extra["max_tokens"] field, whose semantic meaning is the context window, NOT the generation cap — before any provider-catalog read, and remove the parallel service-layer implementation so every consumer shares one resolution path.

Why

Python resolves a chat model's context window as model_extra.get("max_tokens") or 8192 — the per-model "max_tokens" a user configures IS the context window length (content_length / Python max_length), not the output cap. Go ignored that override: custom/local models (not in the catalog) resolved to 0, so the agent silently fell back to the 8192 budget (truncating large contexts) and the extractor skipped fitting entirely (D22). The service layer also had a duplicate catalog-only resolver feeding the knowledge compiler (RAPTOR/dedup/merge) (D23).

Changes

  • internal/dao/model_context.go: ResolveModelContentLength now takes tenantID and resolves the tenant_model row (UUID or composite via tenant provider/instance/model) before any catalog read:
    1. active row with a custom context-window override (extra["max_tokens"] > 0; the field name is a Python legacy for the context window, i.e. content_length) → that override wins;
    2. otherwise fall back to catalog content_length (the context window length, via the tenant row, the composite reference parts, or resolved driver + model name).
  • internal/service/model_service.go: ResolveModelContextLength delegates to the shared dao resolver; modelContextLengthByID / modelContextLengthByName (parallel catalog-only implementations) are removed.
  • internal/ingestion/component/extractor.go: extractorContextLength passes tenantID.
  • internal/agent/component/llm.go: agent reads tenant_id from canvas state and passes it.

Testing

  • dao: 12 tests — existing composite/UUID/driver-fallback/unknown/too-many-parts plus new UUID/composite/custom-model override cases, invalid/zero overrides falling back to the catalog, and inactive rows ignoring the override.
  • agent: end-to-end TestLLM_Invoke_UUIDModel_CustomContextOverride proves a 2000-token context-window override drives trimming (not gpt-4o's 128k catalog content_length); existing content_length/fallback tests still pass.
  • bash build.sh --test ./internal/dao/... ./internal/agent/component/... ./internal/ingestion/component/... and service/ingestion-task compiles pass.

Note

Branched from pr/3-agent-content-length (the #18093 agent content_length work) so the agent caller is included; once #18093 merges, this PR's diff shrinks to the resolver/service/extractor changes. D24 (chat_pipeline using catalog MaxOutput as context) is tracked separately.

Review updates (2026-08-12)

  • UUID resolution is intentionally unscoped by tenant: UUIDs are globally unique/unguessable and shared/joined-tenant models are legitimate (matches the previous service behavior and Python's get_model_config_by_id). This also fixes a service unit test that passes a user id as the tenant id.
  • splitCompositeModelRef recombines 4+ @-separated segments into the model name (LM Studio style name@quant@provider@...), preserving the old service parseModelName capability.
  • modelExtraMaxTokens parses via json.Number (int / float / numeric string).
  • Composite override lookup requires an active instance.

Known limitations / follow-ups

  • extra["max_tokens"] semantics are not yet unified across Go: internal/ingestion/component/dispatch_model.go still interprets the same field as a max_output (generation cap) override, while this PR (and Python) treat it as the context window length (content_length). A follow-up should reconcile that path.
  • The composite lookup does not yet implement the agent's "default instance → sole active instance" fallback (findSoleActiveProviderInstance); a 2-segment model@provider ref on a tenant whose default instance is not literally named default will fall back to the catalog length.
  • D24 (chat_pipeline using catalog MaxOutput as the context window) is tracked separately in the extractor bug notes.

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

coderabbitai Bot commented Aug 12, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9c2acd2b-23a1-4802-a530-dcd9d447e18e

📥 Commits

Reviewing files that changed from the base of the PR and between 5acc461 and 4125e28.

📒 Files selected for processing (5)
  • internal/agent/component/llm_test.go
  • internal/dao/model_context.go
  • internal/dao/model_context_test.go
  • internal/ingestion/component/extractor_test.go
  • internal/service/model_service_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/dao/model_context.go
  • internal/dao/model_context_test.go

📝 Walkthrough

Walkthrough

The change makes model context-length resolution tenant-aware. The DAO applies active tenant max_tokens overrides before provider catalog values. Callers pass tenant identity, and tests verify prompt fitting with tenant overrides.

Changes

Model context resolution

Layer / File(s) Summary
DAO model context resolution
internal/dao/model_context.go, internal/dao/model_context_test.go
The DAO resolves UUID and composite tenant models, parses positive numeric or string extra.max_tokens values, and falls back to catalog content_length. Tests cover inactive records, invalid overrides, multi-segment references, tenant isolation, and fixture setup.
Tenant-aware resolution call sites
internal/service/model_service.go, internal/ingestion/component/extractor.go
The service delegates context-length resolution to the DAO. The service and ingestion path pass tenant identity to the updated method.
LLM fitting integration
internal/agent/component/llm.go, internal/agent/component/llm_test.go, internal/ingestion/component/extractor_test.go, internal/service/model_service_test.go
LLMComponent.Invoke reads the tenant ID before resolving context length. Tests verify max_tokens overrides for UUID and composite references during model resolution and message fitting.

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

Sequence Diagram(s)

sequenceDiagram
  participant LLMComponent
  participant ModelService
  participant DAO
  participant TenantModel
  participant ProviderCatalog
  participant MessageFitter
  LLMComponent->>ModelService: resolve context length with tenant ID
  ModelService->>DAO: resolve tenant model context length
  DAO->>TenantModel: inspect model reference and extra
  TenantModel-->>DAO: max_tokens override or model metadata
  DAO->>ProviderCatalog: read catalog content_length when needed
  ProviderCatalog-->>DAO: catalog context length
  DAO-->>ModelService: resolved context length
  ModelService-->>LLMComponent: context length
  LLMComponent->>MessageFitter: fit messages within context length
  MessageFitter-->>LLMComponent: fitted messages
Loading

Possibly related PRs

Suggested labels: 🐞 bug, 🧪 test

Suggested reviewers: xugangqiang, yuzhichang

Poem

A rabbit checks the tenant model row,
Finds the limit before prompts flow.
Catalog values wait as fallback light,
Large prompts trim to the configured height.
Hop, hop—the context fits just right!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 identifies the DAO fix that honors tenant-configured context window overrides.
Description check ✅ Passed The description includes the required Summary section and clearly explains the background, changes, testing, limitations, and follow-up work.

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 12, 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: 2

🧹 Nitpick comments (2)
internal/service/model_service.go (1)

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

Remove migration history from this method comment.

Remove the PR #17839`` migration reference. State the current contract directly: content_length is the context window, and `max_output` is the generation cap.

As per coding guidelines, “keep package and doc comments aligned with the current runtime path 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/service/model_service.go` around lines 3597 - 3607, Update the
ResolveModelContextLength doc comment to remove the PR `#17839` migration
reference and describe the current contract directly: content_length is the
total context window, while max_output is the generation cap. Preserve the
remaining behavior and resolution details.

Source: Coding guidelines

internal/agent/component/llm_test.go (1)

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

Attach each test description to its test.

Lines 268-272 describe TestLLM_Invoke_UUIDModel_ResolvesContentLength, but the next declaration is TestLLM_Invoke_UUIDModel_CustomContextOverride. Move lines 268-272 above line 336. Keep lines 273-277 above the custom-override test.

As per coding guidelines, remove stale documentation instead of preserving it.

🤖 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/component/llm_test.go` around lines 268 - 277, Move the
comment describing TestLLM_Invoke_UUIDModel_ResolvesContentLength so it
immediately precedes that test’s declaration near line 336, while keeping the
TestLLM_Invoke_UUIDModel_CustomContextOverride description directly above its
test. Remove the misplaced duplicate or stale comment rather than retaining it.

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/dao/model_context_test.go`:
- Around line 140-143: Update the custom-model assertion in
ResolveModelContentLength to exercise the no-override path: clear the existing
max_tokens Extra value or use a separately seeded custom model without Extra,
then expect 0 instead of 32000. Keep the existing override assertion covered
separately.

In `@internal/dao/model_context.go`:
- Around line 21-22: Update modelExtraMaxTokens to accept positive max_tokens
values represented as either JSON numbers or numeric strings, preserving the
existing catalog/8192 fallback for invalid or non-positive values. Add coverage
for the string-form value, including tenant override behavior.

---

Nitpick comments:
In `@internal/agent/component/llm_test.go`:
- Around line 268-277: Move the comment describing
TestLLM_Invoke_UUIDModel_ResolvesContentLength so it immediately precedes that
test’s declaration near line 336, while keeping the
TestLLM_Invoke_UUIDModel_CustomContextOverride description directly above its
test. Remove the misplaced duplicate or stale comment rather than retaining it.

In `@internal/service/model_service.go`:
- Around line 3597-3607: Update the ResolveModelContextLength doc comment to
remove the PR `#17839` migration reference and describe the current contract
directly: content_length is the total context window, while max_output is the
generation cap. Preserve the remaining behavior and resolution details.
🪄 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: 4dd55ea7-604e-4242-babe-ff9d12aff239

📥 Commits

Reviewing files that changed from the base of the PR and between eada2f6 and a6cebd3.

📒 Files selected for processing (6)
  • internal/agent/component/llm.go
  • internal/agent/component/llm_test.go
  • internal/dao/model_context.go
  • internal/dao/model_context_test.go
  • internal/ingestion/component/extractor.go
  • internal/service/model_service.go

Comment thread internal/dao/model_context_test.go Resolved
Comment thread internal/dao/model_context.go Resolved
ResolveModelContentLength now takes tenantID and resolves the tenant_model
row before any catalog read: an active row's extra["max_tokens"] override
wins over the provider catalog's content_length (Python model_extra parity),
and catalog content_length is only a fallback. Custom/local models no longer
fall back to 8192 in the agent or skip fitting in the extractor.

service.ModelProviderService.ResolveModelContextLength delegates to the
shared dao resolver; the parallel modelContextLengthByID/ByName
implementations are removed (one resolution path).

Callers pass tenantID: the extractor already has it, and the agent LLM
component reads it from canvas state. Tests cover UUID/composite/custom-model
overrides, invalid/zero overrides falling back to the catalog, inactive rows,
and an end-to-end agent test proving the override drives trimming.
- modelExtraMaxTokens accepts both JSON numbers and numeric strings for
  extra.max_tokens (some callers persist it as a string); non-numeric
  strings still fall back to the catalog.
- TestResolveModelContentLength_CustomModelExtraComposite now actually
  exercises the no-override path (clears extra, expects 0) instead of
  repeating the override assertion.
- ResolveModelContextLength doc comment drops the migration-history
  reference; llm_test.go comment blocks are attached to their own tests.
@jay77721
jay77721 force-pushed the fix/model-context-extra-override branch from 7d62780 to ad46681 Compare August 12, 2026 09:36

@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/dao/model_context_test.go (1)

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

Test the inactive composite fallback that the comment describes.

The test uses a UUID reference and correctly expects 0. It does not execute the composite/catalog fallback described in Lines 209-211. Add an assertion for "gpt-4o@OpenAI" with "tenant-1" that expects the catalog value 128000, or revise the comment to describe UUID-only behavior.

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

🤖 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 209 - 228, The test
TestResolveModelContentLength_InactiveTenantModel currently covers only the UUID
path, not the composite/catalog fallback described by its comment. Add a focused
assertion calling ResolveModelContentLength with model reference "gpt-4o@OpenAI"
and tenant "tenant-1", expecting the catalog value 128000, while preserving the
existing UUID assertion.

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/dao/model_context_test.go`:
- Around line 91-108: Update UUID resolution in lookupTenantModel to require the
matched TenantModelProvider.TenantID to equal the requested tenant ID, rather
than using an unscoped GetByID result. In
TestResolveModelContentLength_ExtraOverrideUUID and related positive UUID
assertions, pass "tenant-1"; add a test asserting the same UUID returns 0 for
"tenant-2" when no driver fallback is provided.

---

Nitpick comments:
In `@internal/dao/model_context_test.go`:
- Around line 209-228: The test
TestResolveModelContentLength_InactiveTenantModel currently covers only the UUID
path, not the composite/catalog fallback described by its comment. Add a focused
assertion calling ResolveModelContentLength with model reference "gpt-4o@OpenAI"
and tenant "tenant-1", expecting the catalog value 128000, while preserving the
existing UUID assertion.
🪄 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: 863a451c-4374-4baf-b8a1-e8c3238d55ab

📥 Commits

Reviewing files that changed from the base of the PR and between 7d62780 and ad46681.

📒 Files selected for processing (4)
  • internal/agent/component/llm_test.go
  • internal/dao/model_context.go
  • internal/dao/model_context_test.go
  • internal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/service/model_service.go
  • internal/dao/model_context.go

Comment thread internal/dao/model_context_test.go Resolved
lookupTenantModel resolved a UUID with an unscoped GetByID, so a caller
holding another tenant's UUID could read that tenant's per-model
max_tokens override (and tenant-row catalog read). Require the
tenant_model row's provider to belong to the requested tenantID.

UUID-positive dao tests now pass the owning tenant id, and a new
TestResolveModelContentLength_UUIDCrossTenantRejected asserts the same
UUID resolves to 0 for an unrelated tenant.
…ite, robust parsing

Address the PR review regressions:

- UUID resolution is unscoped again (globally unique, unguessable, and
  shared/joined-tenant models are legitimate — matching the old service
  behavior and Python's get_model_config_by_id), fixing the broken
  service unit test and the joined-tenant context-length regression.
- splitCompositeModelRef now recombines 4+ '@'-separated segments into the
  model name (preserving embedded '@', e.g. LM Studio
  name@quant@lmstudio@LM-Studio), so the service path no longer degrades
  multi-segment chat model refs to 0.
- modelExtraMaxTokens parses via json.Number, accepting int, float, and
  numeric-string forms.
- Composite override lookup requires an active instance (provider has no
  status field; tenant+provider is unique-indexed).

New coverage: service override (UUID + composite), agent composite
override, extractor end-to-end override, inactive-instance composite
fallback to catalog, multi-segment splitter behavior. Cross-tenant
rejection test removed (behavior intentionally unscoped).
A composite reference whose model row is inactive applies neither the
override nor the tenant-row catalog read and falls back to the catalog by
reference parts (gpt-4o -> 128000).
@yuzhichang

Copy link
Copy Markdown
Member

LGTM

@yuzhichang
yuzhichang merged commit 91fd114 into infiniflow:main Aug 12, 2026
3 checks passed
@jay77721
jay77721 deleted the fix/model-context-extra-override branch August 13, 2026 08:47
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