Skip to content

Fix: ValueError: too many values to unpack in list_tenant_added_models for model IDs containing '@' (#16467) - #16468

Merged
wangq8 merged 12 commits into
infiniflow:mainfrom
skbs-eng:fix/list-tenant-added-models-at-symbol
Jul 7, 2026
Merged

wangq8 merged 12 commits into
infiniflow:mainfrom
skbs-eng:fix/list-tenant-added-models-at-symbol

Conversation

@skbs-eng

@skbs-eng skbs-eng commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #16467 — ValueError: too many values to unpack (expected 3) in list_tenant_added_models for model IDs containing @, and three sibling code paths that exhibit the same @-mis-parsing bug. Adds a downstream NotFoundError tolerance so the dataset-configuration "check embedding" endpoint degrades to a user-friendly message instead of HTTP 500 when the tenant chunk index is missing.

Root cause (recap)

The composite model key is right-anchored:

model_name@instance_name@provider_name      # explicit instance
model_name@provider_name                    # default instance

Some model names legitimately contain @ characters (LM Studio embedding model IDs like text-embedding-nomic-embed-text-v1.5@q8_0, llama.cpp @<quantization> suffixes, HuggingFace dataset IDs). The full composite key then has 4+ @-separated fields:

text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio

A naive split("@") + 3-element unpack mis-assigns the fields.

Sites fixed

# File Function Fix
1 api/apps/services/models_api_service.py _get_model_info key.rsplit("@", 2); bare-name case sets empty provider
2 api/db/joint_services/tenant_model_service.py split_model_name rsplit("@", 2) from the right
3 internal/service/model_service.go parseModelName Rejoins leading fields when >3 @-segments
4 internal/service/model_service.go GetModelConfigFromProviderInstance TEI exact-match + Builtin suffix-based detection to handle bare model IDs with embedded @
5 api/apps/services/models_api_service.py list_tenant_added_models Internal map keys use `
6 api/apps/services/dataset_api_service.py sample_random_chunks_with_vectors Graceful empty-set return on missing chunk index

Review feedback addressed (commit 26a2cec)

  • Removed deprecated TenantLLMService dependency from models_api_service.py — the _resolve_bare_model_provider() function and its TenantLLMService import were deleted per maintainer request.
  • Replaced @ with | as internal map key separator in list_tenant_added_models to avoid conflicts with model names containing @.
  • Fixed Go TEI/Builtin fast paths — the TEI short-circuit now does exact string match first to handle bare model IDs with embedded @. The Builtin provider detection uses strings.HasSuffix instead of splitRightAnchoredModelName to avoid misidentifying embedded @ as a provider separator.
  • Updated tests — removed bare-model tests that depended on deprecated TenantLLMService, added test for two-part model IDs with embedded @.

Testing

  • Python: 5/5 unit tests pass (test_models_api_service_list_tenant_added_models.py)
  • Go: gofmt validates syntax; Go tests require Linux (platform-specific binding package)
  • Regression tests: test_tenant_model_service_split_model_name.py and model_service_test.go cover the parsing fixes

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Jun 29, 2026
@coderabbitai

coderabbitai Bot commented Jun 29, 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

Model-name parsing now preserves embedded @ characters across Python and Go helpers, tenant model listing uses safer internal keys, dataset sampling returns an empty list when an index is missing, and graph subgraph generation no longer applies relationship-content validation.

Changes

Model key parsing fixes

Layer / File(s) Summary
Model listing parsing and bare resolution
api/apps/services/models_api_service.py, test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py
list_tenant_added_models() now uses `
Right-anchored model-name splitting
api/db/joint_services/tenant_model_service.py, test/unit_test/api/db/services/test_tenant_model_service_split_model_name.py
split_model_name() now preserves embedded @ characters while keeping provider and instance extraction behavior, and the tests cover bare names plus embedded-@ cases.
Go model-name splitting
internal/service/model_service.go, internal/service/model_service_test.go
parseModelName, splitRightAnchoredModelName, and the TEI/Builtin shortcuts now right-anchor @ parsing, with tests covering the updated helper behavior.

Dataset sampling guard

Layer / File(s) Summary
Missing-index search handling
api/apps/services/dataset_api_service.py
sample_random_chunks_with_vectors now returns an empty list when the chunk index is missing and re-raises other search errors.

Subgraph relationship filtering

Layer / File(s) Summary
Relationship validation removal
rag/graphrag/general/index.py
generate_subgraph now skips only relationships with missing endpoints, and the prior relationship-content validation and invalid-relation reporting code is removed.

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

Poem

🐇 I hopped through names with @ in sight,
Split from the right, and all was right.
Missing indexes faded from view,
And graph checks drifted out of sight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR also changes Go parsing and dataset index handling, which are outside #16467’s list_tenant_added_models scope. Split the unrelated Go and dataset changes into separate PRs or link their issues if they are intended to be included.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR fixes the reported list_tenant_added_models crash by preserving embedded '@' characters in model names.
Docstring Coverage ✅ Passed Docstring coverage is 86.36% which is sufficient. The required threshold is 80.00%.
Title check ✅ Passed The title is specific and clearly describes the main bug fix around model IDs containing '@'.
Description check ✅ Passed The description includes the required Summary section plus helpful background, root cause, scope, and testing details.

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.

@yingfeng
yingfeng requested a review from Lynn-Inf June 29, 2026 15:24

@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
`@test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py`:
- Around line 160-167: Update the regression test docstrings in the affected
test function(s) to match the production fix: the composite key is unpacked with
split("@", 2), not rsplit("@", 2). Use the existing test names and nearby
references to the provider@instance@model_name key logic to rewrite the
narrative so it accurately describes the left-to-right split behavior being
protected.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 580fcf08-195b-42e6-883b-2e565a806d10

📥 Commits

Reviewing files that changed from the base of the PR and between 6370fce and c2bd230.

📒 Files selected for processing (2)
  • api/apps/services/models_api_service.py
  • test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py

@skbs-eng

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit docstring-coverage warning (75.00% → 100%) in commit bf8bf01e2.

The two helpers missing docstrings were:

  • _stub (registers a stubbed module in sys.modules)
  • _make_model_record (builds a SimpleNamespace mirroring a TenantModel ORM row)

Both now have full Google-style docstrings (Args / Returns) explaining the monkeypatching contract and the provider-1/instance-1 fixture assumption shared with _load_module.

No production code changes; all 4 tests still pass:

4 passed in 0.04s

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

LGTM

skbs-eng added a commit to skbs-eng/ragflow that referenced this pull request Jun 30, 2026
…ModelName; NotFoundError tolerance in sample_random_chunks_with_vectors

PR infiniflow#16468 fixed the ValueError in list_tenant_added_models for model IDs containing '@', but missed three sibling code paths that parse the same composite key with the same buggy split('@') strategy:

- api/db/joint_services/tenant_model_service.py: split_model_name now uses rsplit('@', 2) so embedded '@' in the leftmost model-name component is preserved (LM Studio embedding IDs like 'text-embedding-nomic-embed-text-v1.5@q8_0').
- api/apps/services/models_api_service.py: _get_model_info likewise. Bare-name case now falls through with provider_name='' instead of returning None so downstream resolution can still match a tenant default.
- internal/service/model_service.go: parseModelName handles >3 fields by rejoining the leading fields into modelName.
- api/apps/services/dataset_api_service.py: sample_random_chunks_with_vectors now catches not_found_exception / index_not_found_exception and returns [] so check_embedding reports 'No embedded chunks are available to compare.' instead of HTTP 500 when the tenant's chunk index is missing.
- test/unit_test/api/db/services/test_tenant_model_service_split_model_name.py: 7 new tests using AST extraction (load only the function definition; bypasses the heavy common.settings import chain). 11/11 tests pass in 0.03s.

Refs infiniflow#16467
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Jun 30, 2026
@skbs-eng
skbs-eng requested a review from Lynn-Inf June 30, 2026 05:37

@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

🤖 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 `@api/apps/services/models_api_service.py`:
- Around line 83-89: The bare-model fallback in models_api_service’s model
parsing still reaches the provider lookup and returns None for non-TEI models,
so it does not provide general bare-model support. Update the model resolution
flow around the parsing logic in the service method that sets model_name,
provider_name, and instance_name so legacy bare defaults are resolved before any
provider lookup, instead of leaving provider_name empty and relying on
downstream matching.

In `@internal/service/model_service.go`:
- Around line 47-63: The Builtin and TEI fast paths are still splitting model
names with a left-anchored strings.Split, which drops embedded @ suffixes in the
model portion. Update the parsing in GetModelConfigFromProviderInstance to use
the same right-anchored logic as parseModelName so inputs like
model@q8_0@Builtin preserve the full modelName and only treat the last two
tokens as instance/provider. Keep the special-case behavior for the Builtin/TEI
branches, but make them consume the parsed model, instance, and provider values
instead of taking the first token as the model name.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2d8dcf6b-817c-4b07-a560-e6bf80df0318

📥 Commits

Reviewing files that changed from the base of the PR and between bf8bf01 and d2b7221.

📒 Files selected for processing (5)
  • api/apps/services/dataset_api_service.py
  • api/apps/services/models_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • internal/service/model_service.go
  • test/unit_test/api/db/services/test_tenant_model_service_split_model_name.py

Comment thread api/apps/services/models_api_service.py Resolved
Comment thread internal/service/model_service.go Resolved

@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

Caution

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

⚠️ Outside diff range comments (1)
api/apps/services/models_api_service.py (1)

110-129: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Two-part bare model IDs with @ still bypass bare-model resolution.

On Line 113, a legacy default like text-embedding-nomic-embed-text-v1.5@q8_0 is still parsed as model_name="text-embedding-nomic-embed-text-v1.5" and provider_name="q8_0", so _resolve_bare_model_provider() never runs. That means the LM Studio shape called out in this PR still resolves to None unless the suffix happens to be a real provider.

Suggested fix
-    parts = default_model.rsplit("@", 2)
+    model_type = MODEL_TAG_TO_TYPE.get(model_type, model_type)
+    parts = default_model.rsplit("@", 2)
     if len(parts) == 3:
         model_name, instance_name, provider_name = parts
     elif len(parts) == 2:
-        model_name, provider_name = parts
-        instance_name = "default"
+        provider_name = _resolve_bare_model_provider(tenant_id, default_model, model_type)
+        if provider_name:
+            model_name = default_model
+            instance_name = "default"
+        else:
+            model_name, provider_name = parts
+            instance_name = "default"
     else:
         # Bare model name (no provider suffix at all). Resolve the factory
         # from the tenant's enrolled ``tenant_llm`` rows before the standard
         # provider lookup below; legacy tenants persisted bare defaults
         # before composite keys became the convention.
         model_name = parts[0]
         provider_name = _resolve_bare_model_provider(tenant_id, model_name, model_type)
         instance_name = "default"
         if not provider_name:
             logging.warning(
                 "could not resolve provider for bare model %r (tenant %r, type %s); "
                 "no unique enrolled match",
                 default_model, tenant_id, model_type,
             )
-
-    model_type = MODEL_TAG_TO_TYPE.get(model_type, model_type)
🤖 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 `@api/apps/services/models_api_service.py` around lines 110 - 129, The
default-model parsing in models_api_service.py still treats two-part values in
the fallback path as if the suffix is always a provider, which lets legacy bare
model IDs with a single “@” skip _resolve_bare_model_provider(). Update the
default_model handling in the logic around _resolve_bare_model_provider() so
that only known provider/instance composites are parsed as such, and otherwise
fall back to resolving the bare model against the tenant’s enrolled tenant_llm
rows before using provider_name; keep the bare-model warning path intact for
unresolved cases.
🤖 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/service/model_service.go`:
- Around line 75-87: The splitRightAnchoredModelName helper is over-splitting
two-part bare model IDs that contain an embedded @, causing the second token to
be treated as providerName when it may actually be part of modelName. Update
splitRightAnchoredModelName in model_service.go so the TEI/Builtin fast-paths
only consider the trailing token a provider suffix when it is a real provider
case; otherwise preserve the full composite string as modelName and leave
providerName empty/default. Make sure the callers that rely on this helper
continue to get the correct modelName for legacy bare defaults with embedded @.

---

Outside diff comments:
In `@api/apps/services/models_api_service.py`:
- Around line 110-129: The default-model parsing in models_api_service.py still
treats two-part values in the fallback path as if the suffix is always a
provider, which lets legacy bare model IDs with a single “@” skip
_resolve_bare_model_provider(). Update the default_model handling in the logic
around _resolve_bare_model_provider() so that only known provider/instance
composites are parsed as such, and otherwise fall back to resolving the bare
model against the tenant’s enrolled tenant_llm rows before using provider_name;
keep the bare-model warning path intact for unresolved cases.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d8b1d0f2-8050-46f8-bb59-0c3acc4a87e6

📥 Commits

Reviewing files that changed from the base of the PR and between d2b7221 and ee65cec.

📒 Files selected for processing (4)
  • api/apps/services/models_api_service.py
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py

Comment thread internal/service/model_service.go Resolved

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

Please remove tenant_llm service and DB calls in models_api_service.py — they are deprecated and will be removed.

Also, a suggestion on @ handling: consider counting occurrences before splitting. The rsplit approach in tenant_model_service.py is clean and safe. For models_api_service, since @ is only used as a separator when generating map keys, consider replacing it with a character that's less likely to appear in model_name(e.g., | or ^).

@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)
test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py (1)

98-100: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

This regression test currently blesses the broken parse.

The stub on Lines 98-100 accepts any provider_name, and the assertion on Line 309 expects "q8_0" as the provider for a bare LM Studio ID. That means the test still passes when _get_model_info() is incorrectly treating the embedded @ as a provider suffix instead of preserving the full model ID / resolving it through tenant enrollment.

Also applies to: 286-311

🤖 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
`@test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py`
around lines 98 - 100, The regression test is still masking the parsing bug in
`_get_model_info()` by stubbing `get_by_tenant_id_and_provider_name` to accept
any provider and asserting `"q8_0"` for a bare LM Studio model ID. Tighten the
test so it verifies the full model ID is preserved or resolved through tenant
enrollment rather than treating the embedded `@` as a provider suffix, and
update the `test_list_tenant_added_models` assertions around the `q8_0` case to
reflect the intended provider resolution behavior.
♻️ Duplicate comments (2)
internal/service/model_service.go (1)

75-86: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Explicit TEI_MODEL@Builtin keys still miss the TEI fast path when the model name already contains @.

After the exact-match check, splitRightAnchoredModelName("...@q8_0@Builtin") still produces teiPure="..." and drops @q8_0, so Line 2353 misses and Lines 2375-2405 fall back to the generic Builtin branch. That returns a different config path and skips the TEI BaseURL, so explicit Builtin keys do not behave the same as the bare TEI_MODEL form.

💡 Possible fix
-        teiPure, _, teiProvider := splitRightAnchoredModelName(modelName)
-        if teiPure == teiModel && (teiProvider == "Builtin" || teiProvider == "") {
+        teiPure := ""
+        switch {
+        case strings.HasSuffix(modelName, "`@default`@Builtin"):
+            teiPure = strings.TrimSuffix(modelName, "`@default`@Builtin")
+        case strings.HasSuffix(modelName, "`@Builtin`"):
+            teiPure = strings.TrimSuffix(modelName, "`@Builtin`")
+        default:
+            parsedModel, _, parsedProvider := splitRightAnchoredModelName(modelName)
+            if parsedProvider == "Builtin" || parsedProvider == "" {
+                teiPure = parsedModel
+            }
+        }
+        if teiPure == teiModel {
             builtinDriver := modelModule.GetBuiltinEmbeddingModel(teiPure)
             if builtinDriver == nil {
                 return nil, "", nil, 0, fmt.Errorf("builtin (TEI) embedding model %q not found", teiPure)
             }
             apiConfig := &modelModule.APIConfig{ApiKey: nil, Region: nil, BaseURL: &teiBaseURL}
             return builtinDriver, teiPure, apiConfig, 0, nil
         }

Also applies to: 2350-2359, 2375-2405

🤖 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 75 - 86, The right-anchored
parsing in splitRightAnchoredModelName is dropping the embedded suffix for
explicit Builtin keys, so TEI_MODEL@Builtin variants do not reach the TEI fast
path. Update the model lookup flow in model_service.go so the TEI-specific check
handles composite names that already contain @, preserving the full TEI model
portion before the Builtin/provider split. Make sure the exact-match path and
the later Builtin branch both use the same parsing behavior so explicit
TEI_MODEL@Builtin keys resolve to the same BaseURL/config as the bare TEI_MODEL
form.
api/apps/services/models_api_service.py (1)

49-78: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Two-part LM Studio IDs still fall through as model@provider.

For a legacy bare ID like text-embedding-nomic-embed-text-v1.5@q8_0, Lines 109-114 still assign provider_name="q8_0" and never consult _resolve_bare_model_provider(). The provider lookup on Lines 148-151 then fails unless the tenant literally has a provider named q8_0, so the bare-name regression this PR is targeting is still reproducible.

💡 Possible fix
 def _get_model_info(tenant_id: str, default_model: str, model_type: str):
@@
-    parts = default_model.rsplit("@", 2)
+    model_type = MODEL_TAG_TO_TYPE.get(model_type, model_type)
+    parts = default_model.rsplit("@", 2)
     if len(parts) == 3:
         model_name, instance_name, provider_name = parts
     elif len(parts) == 2:
-        model_name, provider_name = parts
+        resolved_provider = _resolve_bare_model_provider(tenant_id, default_model, model_type)
+        if resolved_provider:
+            model_name = default_model
+            provider_name = resolved_provider
+        else:
+            model_name, provider_name = parts
         instance_name = "default"
     else:
         model_name = parts[0]
         provider_name = ""
         instance_name = "default"
-
-    model_type = MODEL_TAG_TO_TYPE.get(model_type, model_type)

Also applies to: 105-118, 147-151

🤖 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 `@api/apps/services/models_api_service.py` around lines 49 - 78, The bare-model
fallback in models_api_service still splits LM Studio IDs like
text-embedding-nomic-embed-text-v1.5@q8_0 as model@provider, so the legacy
provider lookup is never reached. Update the model resolution flow in the code
that builds the provider/model pair and the later lookup path to detect these
“bare” tenant models and call _resolve_bare_model_provider() before using the
suffix as provider_name. Make sure the logic in the branches around the model
parsing and provider lookup uses the resolved factory from
_resolve_bare_model_provider() when the tenant has a single matching
TenantLLMService row, and only falls back to the raw suffix when no bare-model
match is found.
🤖 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
`@test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py`:
- Around line 98-100: The regression test is still masking the parsing bug in
`_get_model_info()` by stubbing `get_by_tenant_id_and_provider_name` to accept
any provider and asserting `"q8_0"` for a bare LM Studio model ID. Tighten the
test so it verifies the full model ID is preserved or resolved through tenant
enrollment rather than treating the embedded `@` as a provider suffix, and
update the `test_list_tenant_added_models` assertions around the `q8_0` case to
reflect the intended provider resolution behavior.

---

Duplicate comments:
In `@api/apps/services/models_api_service.py`:
- Around line 49-78: The bare-model fallback in models_api_service still splits
LM Studio IDs like text-embedding-nomic-embed-text-v1.5@q8_0 as model@provider,
so the legacy provider lookup is never reached. Update the model resolution flow
in the code that builds the provider/model pair and the later lookup path to
detect these “bare” tenant models and call _resolve_bare_model_provider() before
using the suffix as provider_name. Make sure the logic in the branches around
the model parsing and provider lookup uses the resolved factory from
_resolve_bare_model_provider() when the tenant has a single matching
TenantLLMService row, and only falls back to the raw suffix when no bare-model
match is found.

In `@internal/service/model_service.go`:
- Around line 75-86: The right-anchored parsing in splitRightAnchoredModelName
is dropping the embedded suffix for explicit Builtin keys, so TEI_MODEL@Builtin
variants do not reach the TEI fast path. Update the model lookup flow in
model_service.go so the TEI-specific check handles composite names that already
contain @, preserving the full TEI model portion before the Builtin/provider
split. Make sure the exact-match path and the later Builtin branch both use the
same parsing behavior so explicit TEI_MODEL@Builtin keys resolve to the same
BaseURL/config as the bare TEI_MODEL form.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bdd9fd8f-eb54-4140-b87d-ac142aff32cb

📥 Commits

Reviewing files that changed from the base of the PR and between ee65cec and 26a2cec.

📒 Files selected for processing (3)
  • api/apps/services/models_api_service.py
  • internal/service/model_service.go
  • test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py

skbs-eng added a commit to skbs-eng/ragflow that referenced this pull request Jul 3, 2026
…d '@' bare

Address CodeRabbit Major comment on PR infiniflow#16468: the helper previously
treated the trailing token of every 2-segment key as a provider, so a
bare default like 'text-embedding-nomic-embed-text-v1.5@q8_0' was
mis-classified as provider='q8_0' instead of staying bare. That
defeated the TEI short-circuit's 'modelName == teiModel' exact-match
fast path when TEI_MODEL is the full embedded string.

The helper now only treats the last token as a provider when it is
recognised (only 'Builtin' for now, matching its sole callers);
otherwise the whole string is returned as the bare modelName and the
caller falls through to the standard lookup. Adds a regression test
case for the LM Studio embedding ID scenario.
@skbs-eng

skbs-eng commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

Pushed a follow-up at a9977572f addressing the Major / Functional Correctness concern on splitRightAnchoredModelName: the 2-segment case no longer treats the trailing token as a provider unless it actually is one ("Builtin"); otherwise the whole string stays as the bare modelName and the caller falls through to the standard lookup. A regression test was added to TestSplitRightAnchoredModelName covering the text-embedding-nomic-embed-text-v1.5@q8_0 LM Studio embedding case.

Could you take another look?

@skbs-eng

skbs-eng commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: splitRightAnchoredModelName 2-segment edge case

Thanks @wangq8 for the ci label and @Lynn-Inf for the earlier reviews. Pushed a9977572f addressing the CodeRabbit Major / Functional Correctness comment on the TEI/Builtin helper.

Behaviour before: splitRightAnchoredModelName("text-embedding-nomic-embed-text-v1.5@q8_0") returned ("text-embedding-nomic-embed-text-v1.5", "default", "q8_0"), mis-classifying the quantization tag as a provider and missing the TEI fast path's modelName == teiModel exact-match when TEI_MODEL is the full embedded string.

Behaviour after: the helper only treats the last token as a provider when it equals "Builtin" (the only recognised suffix in its sole call-sites, the TEI / Builtin short-circuits). For any other 2-segment key the whole string is returned as the bare modelName with empty instanceName / providerName, and the caller falls through to the standard lookup — same as the 1-segment case. The pre-existing TEI exact-match fast path at the top of the TEI short-circuit (if modelName == teiModel) covers the bare-default case where the embedded @ happens to match TEI_MODEL verbatim.

Tests: added "two parts bare default with embedded '@' stays bare" to TestSplitRightAnchoredModelName. The existing 4 cases are unchanged and continue to pass.

Diff scope: 2 files, +29 / −1. Re-requesting review from @coderabbitai (auto-paused after the earlier commit influx) and would appreciate a re-look from @Lynn-Inf on the new commit when convenient.

@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
fd model_service.go
echo "---"
ast-grep run --pattern 'func splitRightAnchoredModelName($$$) {
  $$$
}' --lang go internal/service/model_service.go

Length of output: 523


🏁 Script executed:

#!/bin/bash
set -uo pipefail
sed -n '1,400p' internal/service/model_service.go | grep -n "func splitRightAnchoredModelName" 
echo "---"
awk '/func splitRightAnchoredModelName/,/^}/' internal/service/model_service.go
echo "---callers---"
grep -n "splitRightAnchoredModelName" internal/service/model_service.go
echo "---test file---"
awk '/func TestSplitRightAnchoredModelName/,0' internal/service/model_service_test.go | sed -n '1,150p'

Length of output: 4721


🏁 Script executed:

#!/bin/bash
sed -n '2330,2400p' internal/service/model_service.go

Length of output: 3793


The fix looks solid. splitRightAnchoredModelName's updated 2-segment handling now only treats the trailing token as a provider when it is literally "Builtin" (the only suffix its call sites recognize), otherwise returns the bare composite string with empty instance/provider — correctly avoiding misclassifying q8_0 as a provider. I traced the sole call site at line 2366 (GetModelConfigFromProviderInstance's TEI short-circuit): it already has an exact-match fast path (modelName == teiModel) ahead of the helper call, which covers the bare-default LM Studio case, and the helper's fallthrough correctly lets non-Builtin 2-segment keys pass through unmodified to the standard lookup path. The new regression test "two parts bare default with embedded '@' stays bare" correctly asserts text-embedding-nomic-embed-text-v1.5@q8_0 stays bare with empty instance/provider, and the existing 3/4/5-part cases with embedded @ remain unaffected.

This resolves the Major/Functional Correctness concern I raised. Nice regression test coverage and clear inline comments explaining the ambiguity trade-off.

ヽ(・∀・)ノ

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
fd -a model_service.go
echo "---outline---"
ast-grep run --pattern 'func splitRightAnchoredModelName($$$) {
  $$$
}' --lang go internal/service/model_service.go
echo "---test---"
rg -n "two parts bare default" -A 20 internal/service/model_service_test.go
echo "---git log---"
git log --oneline -5

Length of output: 701


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "---outline---"
ast-grep run --pattern 'func splitRightAnchoredModelName($ARGS) $RET {
  $$$
}' --lang go internal/service/model_service.go || true
echo "---grep---"
rg -n "func splitRightAnchoredModelName" -A 40 internal/service/model_service.go
echo "---test file search---"
fd -a model_service_test.go
rg -n "two parts bare default|func TestSplitRightAnchoredModelName" -A 25 internal/service/model_service_test.go
echo "---git log---"
git log --oneline -5

Length of output: 6975


The fix looks correct and matches your description. The 2-segment case in splitRightAnchoredModelName now correctly disambiguates:

  • "BAAI/bge-m3@Builtin" → ("BAAI/bge-m3", "default", "Builtin") (recognized provider suffix)
  • "text-embedding-nomic-embed-text-v1.5@q8_0" → ("text-embedding-nomic-embed-text-v1.5@q8_0", "", "") (bare, embedded @ preserved)

This resolves the earlier concern where "q8_0" would have been misclassified as a provider. The added test case "two parts bare default with embedded '@' stays bare" directly covers the LM Studio quantization-suffix scenario, and the existing 3/4/5-part cases still pass with the right-anchored parsing intact.

One thing worth double-checking on your end: since the fallback now returns the full compositeName as modelName with empty instanceName/providerName for any non-"Builtin" 2-segment input, please confirm the callers in GetModelConfigFromProviderInstance (TEI and generic Builtin short-circuits) correctly fall through to the standard lookup path in this case, rather than treating the empty provider as a match failure. From the earlier summary this appears intended, but it's worth a final sanity check since it's the crux of the fix.

Approving this follow-up — nice catch and clean fix.

✅ Action performed

Reviews resumed.


Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

yuzhichang pushed a commit that referenced this pull request Jul 3, 2026
…es (#16469)

## Summary

While fixing #16467 (IterationItem crash on `@` in user-defined output
keys), an audit of `agent/**/*.py` revealed **three additional sites**
with the same vulnerability. This PR hardens all of them with
`maxsplit=1` and adds regression tests.

This is **defense-in-depth hardening**, not a behavior change. The
current `variable_ref_patt` regex constrains `var_nm` to
`[A-Za-z0-9_.-]+`, so single-`@` templates resolve exactly as before.
The `maxsplit=1` only kicks in if the trailing side itself contains `@`
— currently unreachable from the public DSL surface, but trivially
exploitable the moment a user-defined output key happens to contain `@`
(e.g. `user@email`) or the regex is ever relaxed.

> **Note on issue scope**: The primary fix for #16467 (the
`list_tenant_added_models` `ValueError` crash on `@` in model names) is
in PR #16468. This PR is a **follow-up hardening sweep** of the same
vulnerability class found in `agent/` during that audit; it does not
duplicate or replace #16468.

## Sites hardened

| File | Line | Method |
|------|------|--------|
| `agent/canvas.py` | 206 | `Graph.get_variable_value` |
| `agent/canvas.py` | 256 | `Graph.set_variable_value` |
| `agent/component/base.py` | 533 |
`ComponentBase.get_input_elements_from_text` |
| `agent/component/iterationitem.py` | 88 |
`IterationItem.output_collation` |

All now use `split("@", 1)` with an inline comment explaining the
rationale. The trailing side keeps any embedded `@`.

## Sites already safe (audited but left alone)

| File | Reason safe |
|------|------------|
| `agent/canvas.py:708` (`is_reff`) | Pre-checks `len(arr) != 2` |
| `agent/component/categorize.py` | Uses `rsplit` |
| `agent/component/iteration.py` | Pre-validates via regex |
| Other call sites | `rsplit` or regex pre-validation |

## Regression tests

9 new tests across 2 files, all `pytest.mark.p2`:

| File | Tests |
|------|-------|
| `test/unit_test/agent/test_canvas_at_split.py` | 6 —
`get_variable_value`, `set_variable_value`, round-trip, single-`@`,
missing-component |
| `test/unit_test/agent/component/test_iterationitem_at_split.py` | 3 —
`output_collation` with `@` in var, single-`@`, non-matching cid |

Each test was **verified to fail with `ValueError: too many values to
unpack (expected 2)`** when the corresponding fix is temporarily
reverted, confirming the tests actually catch the bug rather than just
exercising the happy path.

## Test results

```
9 passed in 0.04s
```

Full agent unit suite also clean (38 passed, 3 skipped; 6 unrelated
pre-existing collection errors from missing `peewee`/`requests` in local
venv — not caused by this PR).

## Related

- Issue: #16467
- Primary fix PR: #16468 (closes the issue)
- This PR: defense-in-depth follow-up, intentionally non-blocking on
#16467

---------

Co-authored-by: skbs-eng <[email protected]>
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
…es (infiniflow#16469)

## Summary

While fixing infiniflow#16467 (IterationItem crash on `@` in user-defined output
keys), an audit of `agent/**/*.py` revealed **three additional sites**
with the same vulnerability. This PR hardens all of them with
`maxsplit=1` and adds regression tests.

This is **defense-in-depth hardening**, not a behavior change. The
current `variable_ref_patt` regex constrains `var_nm` to
`[A-Za-z0-9_.-]+`, so single-`@` templates resolve exactly as before.
The `maxsplit=1` only kicks in if the trailing side itself contains `@`
— currently unreachable from the public DSL surface, but trivially
exploitable the moment a user-defined output key happens to contain `@`
(e.g. `user@email`) or the regex is ever relaxed.

> **Note on issue scope**: The primary fix for infiniflow#16467 (the
`list_tenant_added_models` `ValueError` crash on `@` in model names) is
in PR infiniflow#16468. This PR is a **follow-up hardening sweep** of the same
vulnerability class found in `agent/` during that audit; it does not
duplicate or replace infiniflow#16468.

## Sites hardened

| File | Line | Method |
|------|------|--------|
| `agent/canvas.py` | 206 | `Graph.get_variable_value` |
| `agent/canvas.py` | 256 | `Graph.set_variable_value` |
| `agent/component/base.py` | 533 |
`ComponentBase.get_input_elements_from_text` |
| `agent/component/iterationitem.py` | 88 |
`IterationItem.output_collation` |

All now use `split("@", 1)` with an inline comment explaining the
rationale. The trailing side keeps any embedded `@`.

## Sites already safe (audited but left alone)

| File | Reason safe |
|------|------------|
| `agent/canvas.py:708` (`is_reff`) | Pre-checks `len(arr) != 2` |
| `agent/component/categorize.py` | Uses `rsplit` |
| `agent/component/iteration.py` | Pre-validates via regex |
| Other call sites | `rsplit` or regex pre-validation |

## Regression tests

9 new tests across 2 files, all `pytest.mark.p2`:

| File | Tests |
|------|-------|
| `test/unit_test/agent/test_canvas_at_split.py` | 6 —
`get_variable_value`, `set_variable_value`, round-trip, single-`@`,
missing-component |
| `test/unit_test/agent/component/test_iterationitem_at_split.py` | 3 —
`output_collation` with `@` in var, single-`@`, non-matching cid |

Each test was **verified to fail with `ValueError: too many values to
unpack (expected 2)`** when the corresponding fix is temporarily
reverted, confirming the tests actually catch the bug rather than just
exercising the happy path.

## Test results

```
9 passed in 0.04s
```

Full agent unit suite also clean (38 passed, 3 skipped; 6 unrelated
pre-existing collection errors from missing `peewee`/`requests` in local
venv — not caused by this PR).

## Related

- Issue: infiniflow#16467
- Primary fix PR: infiniflow#16468 (closes the issue)
- This PR: defense-in-depth follow-up, intentionally non-blocking on
infiniflow#16467

---------

Co-authored-by: skbs-eng <[email protected]>
skbs-eng and others added 7 commits July 5, 2026 22:38
…s for model IDs containing '@' (infiniflow#16467)

LM Studio exposes embedding model IDs with a '@<quantization>' suffix
(e.g. 'text-embedding-nomic-embed-text-v1.5@q8_0'). When such an ID is
used as a model_name the composite key 'provider@instance@model_name'
contains 4 '@'-separated parts. The previous key.split('@') raised
'ValueError: too many values to unpack (expected 3)' and crashed the
whole 'list_tenant_added_models' call, leaving tenants with no models
visible.

Use split('@', 2) so the trailing model_name absorbs any extra '@'
characters (provider_id and instance_id are UUIDs and never contain
'@'). A defensive try/except logs and skips any future malformed key.

Adds unit tests covering: trailing '@<quantization>' suffix, multiple
'@' in the model_name, plain model_name regression check.

Fixes infiniflow#16467
This reverts commit d91fd39.
CodeRabbit flagged the test file for 75.00% docstring coverage (below
the 80.00% threshold). The two helpers missing docstrings were:

  - `_stub`               (registers a stubbed module in sys.modules)
  - `_make_model_record`  (builds a SimpleNamespace mirroring a
                           TenantModel ORM row)

Both helpers are private to the test module but appear in multiple test
cases, so documenting their contract (parameters, return value, the
provider-1/instance-1 fixture assumption) helps the next maintainer
reason about the monkeypatching setup without re-reading every call
site.

The four test functions and `_load_module` already had docstrings.

No production code changes; all 4 tests still pass.
…ModelName; NotFoundError tolerance in sample_random_chunks_with_vectors

PR infiniflow#16468 fixed the ValueError in list_tenant_added_models for model IDs containing '@', but missed three sibling code paths that parse the same composite key with the same buggy split('@') strategy:

- api/db/joint_services/tenant_model_service.py: split_model_name now uses rsplit('@', 2) so embedded '@' in the leftmost model-name component is preserved (LM Studio embedding IDs like 'text-embedding-nomic-embed-text-v1.5@q8_0').
- api/apps/services/models_api_service.py: _get_model_info likewise. Bare-name case now falls through with provider_name='' instead of returning None so downstream resolution can still match a tenant default.
- internal/service/model_service.go: parseModelName handles >3 fields by rejoining the leading fields into modelName.
- api/apps/services/dataset_api_service.py: sample_random_chunks_with_vectors now catches not_found_exception / index_not_found_exception and returns [] so check_embedding reports 'No embedded chunks are available to compare.' instead of HTTP 500 when the tenant's chunk index is missing.
- test/unit_test/api/db/services/test_tenant_model_service_split_model_name.py: 7 new tests using AST extraction (load only the function definition; bypasses the heavy common.settings import chain). 11/11 tests pass in 0.03s.

Refs infiniflow#16467
…ck in _get_model_info

- internal/service/model_service.go: add splitRightAnchoredModelName helper that
  mirrors parseModelName but accepts bare names (returns empty provider/instance
  instead of error). Use it in the TEI Builtin short-circuit and the
  Builtin embedding short-circuit so a model name containing '@' (e.g. LM
  Studio 'text-embedding-nomic-embed-text-v1.5@q8_0') is preserved as the
  leftmost segment instead of being truncated by split('@')[0].

- api/apps/services/models_api_service.py: when _get_model_info receives a
  truly bare model name (no '@' separator at all), resolve the provider from
  the tenant's enrolled tenant_llm rows via TenantLLMService.get_my_llms so
  the downstream provider/instance lookups have a usable provider_name
  instead of an empty string that would always fail.

- Tests: add TestParseModelName and TestSplitRightAnchoredModelName in
  internal/service/model_service_test.go covering the 3-part / 2-part /
  1-part / embedded-@ cases; extend test_models_api_service_list_tenant_added_models.py
  with three bare-model tests (resolves via enrolled row, returns None on
  no match, returns None on ambiguous enrollment).

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

I've noticed that there is still a tenant_llm service call in the _resolve_bare_model_provider function in api/apps/services/models_api_service.py (line 65: TenantLLMService.get_my_llms). Since _resolve_bare_model_provider itself is not called anywhere, I think it can be removed directly. Other parts look good to me.

xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
…es (infiniflow#16469)

## Summary

While fixing infiniflow#16467 (IterationItem crash on `@` in user-defined output
keys), an audit of `agent/**/*.py` revealed **three additional sites**
with the same vulnerability. This PR hardens all of them with
`maxsplit=1` and adds regression tests.

This is **defense-in-depth hardening**, not a behavior change. The
current `variable_ref_patt` regex constrains `var_nm` to
`[A-Za-z0-9_.-]+`, so single-`@` templates resolve exactly as before.
The `maxsplit=1` only kicks in if the trailing side itself contains `@`
— currently unreachable from the public DSL surface, but trivially
exploitable the moment a user-defined output key happens to contain `@`
(e.g. `user@email`) or the regex is ever relaxed.

> **Note on issue scope**: The primary fix for infiniflow#16467 (the
`list_tenant_added_models` `ValueError` crash on `@` in model names) is
in PR infiniflow#16468. This PR is a **follow-up hardening sweep** of the same
vulnerability class found in `agent/` during that audit; it does not
duplicate or replace infiniflow#16468.

## Sites hardened

| File | Line | Method |
|------|------|--------|
| `agent/canvas.py` | 206 | `Graph.get_variable_value` |
| `agent/canvas.py` | 256 | `Graph.set_variable_value` |
| `agent/component/base.py` | 533 |
`ComponentBase.get_input_elements_from_text` |
| `agent/component/iterationitem.py` | 88 |
`IterationItem.output_collation` |

All now use `split("@", 1)` with an inline comment explaining the
rationale. The trailing side keeps any embedded `@`.

## Sites already safe (audited but left alone)

| File | Reason safe |
|------|------------|
| `agent/canvas.py:708` (`is_reff`) | Pre-checks `len(arr) != 2` |
| `agent/component/categorize.py` | Uses `rsplit` |
| `agent/component/iteration.py` | Pre-validates via regex |
| Other call sites | `rsplit` or regex pre-validation |

## Regression tests

9 new tests across 2 files, all `pytest.mark.p2`:

| File | Tests |
|------|-------|
| `test/unit_test/agent/test_canvas_at_split.py` | 6 —
`get_variable_value`, `set_variable_value`, round-trip, single-`@`,
missing-component |
| `test/unit_test/agent/component/test_iterationitem_at_split.py` | 3 —
`output_collation` with `@` in var, single-`@`, non-matching cid |

Each test was **verified to fail with `ValueError: too many values to
unpack (expected 2)`** when the corresponding fix is temporarily
reverted, confirming the tests actually catch the bug rather than just
exercising the happy path.

## Test results

```
9 passed in 0.04s
```

Full agent unit suite also clean (38 passed, 3 skipped; 6 unrelated
pre-existing collection errors from missing `peewee`/`requests` in local
venv — not caused by this PR).

## Related

- Issue: infiniflow#16467
- Primary fix PR: infiniflow#16468 (closes the issue)
- This PR: defense-in-depth follow-up, intentionally non-blocking on
infiniflow#16467

---------

Co-authored-by: skbs-eng <[email protected]>
Per maintainer feedback (Lynn-Inf): the function references the
deprecated TenantLLMService, has no callers anywhere in production
or tests, and would NameError because TenantLLMService is not
imported in this module (the broad 'except Exception' silently
turned the crash into a return "" mask).

Removing the dead helper also resolves the CodeRabbit Critical
'NameError on every call' finding without expanding scope to
other review items.

Refs infiniflow#16468
@skbs-eng

skbs-eng commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the remaining review item in b4db8cb15 per Lynn-Inf's latest comment: removed _resolve_bare_model_provider from api/apps/services/models_api_service.py entirely.

Why remove rather than wire in:

  • The function has zero callers anywhere in the codebase (production or tests).
  • It referenced TenantLLMService without importing it, so it would NameError on every call — the broad except Exception silently turned the crash into return "" (CodeRabbit's Critical 🔴 finding).
  • TenantLLMService is the deprecated service Lynn-Inf asked to remove in 26a2cec59, so adding the missing import would re-introduce the very dependency we just deleted.

Validation:

  • ruff check → All checks passed
  • ruff format --check → already formatted
  • pytest on the two regression test files → 12 passed

Diff: -37 / +5 (5 added lines are isort-driven import reordering after the helper was removed).

Re-requesting review from @Lynn-Inf — would appreciate confirmation this addresses the request, and a final look from @coderabbitai on the new commit.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Your plan includes PR reviews subject to rate limits. Reviews are available now.

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

LGTM

@wangq8 wangq8 added the ci Continue Integration label Jul 6, 2026
@wangq8
wangq8 marked this pull request as draft July 6, 2026 12:04
@wangq8
wangq8 marked this pull request as ready for review July 6, 2026 12:04
@dosubot dosubot Bot added 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jul 6, 2026
@wangq8
wangq8 marked this pull request as draft July 6, 2026 12:07
@wangq8
wangq8 marked this pull request as ready for review July 6, 2026 12:07

@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)
api/apps/services/dataset_api_service.py (1)

1155-1189: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Unresolved merge conflict markers break this module.

Lines 1155-1158, 1172, 1182, and 1189 still contain Git conflict markers (<<<<<<<, =======, >>>>>>>). This makes the file a syntax error and unimportable, which Ruff confirms across the entire region. The conflict must be resolved before merge.

Resolve by keeping the intended try:/except Exception as e: structure and removing all marker lines. Based on the surrounding code, the resolved block should wrap the initial docStoreConn.search probe in a try and return [] on missing-index errors, e.g.:

🔧 Sketch of the resolved structure
    index_nm = search.index_name(tenant_id)
    try:
        res0 = docStoreConn.search(
            select_fields=[],
            highlight_fields=[],
            condition={"kb_id": kb_id, "available_int": 1},
            match_expressions=[],
            order_by=OrderByExpr(),
            offset=0,
            limit=1,
            index_names=index_nm,
            knowledgebase_ids=[kb_id],
        )
    except Exception as e:
        if "not_found_exception" in repr(e) or "index_not_found_exception" in repr(e):
            logging.info(
                "sample_random_chunks_with_vectors: index %s not yet created for tenant %s; "
                "returning empty sample set",
                index_nm,
                tenant_id,
            )
            return []
        raise
🤖 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 `@api/apps/services/dataset_api_service.py` around lines 1155 - 1189, Resolve
the Git merge conflict markers in sample_random_chunks_with_vectors so the
module is valid Python again. Keep the intended try/except around
docStoreConn.search, preserve the missing-index handling in the except Exception
as e block, and remove all <<<<<<<, =======, and >>>>>>> lines. Ensure the
resolved logging message still uses index_nm and tenant_id, and that missing
not_found_exception/index_not_found_exception cases return an empty list while
other exceptions are re-raised.

Source: Linters/SAST tools

🤖 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 `@api/apps/services/dataset_api_service.py`:
- Around line 1155-1189: Resolve the Git merge conflict markers in
sample_random_chunks_with_vectors so the module is valid Python again. Keep the
intended try/except around docStoreConn.search, preserve the missing-index
handling in the except Exception as e block, and remove all <<<<<<<, =======,
and >>>>>>> lines. Ensure the resolved logging message still uses index_nm and
tenant_id, and that missing not_found_exception/index_not_found_exception cases
return an empty list while other exceptions are re-raised.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 75fd9364-00b3-4b40-82f5-fef8031f4426

📥 Commits

Reviewing files that changed from the base of the PR and between b4db8cb and 6a1af70.

📒 Files selected for processing (1)
  • api/apps/services/dataset_api_service.py

@wangq8
wangq8 marked this pull request as draft July 6, 2026 12:47
@wangq8
wangq8 marked this pull request as ready for review July 6, 2026 12:47
@wangq8
wangq8 force-pushed the fix/list-tenant-added-models-at-symbol branch from 4c78d8b to b4db8cb Compare July 6, 2026 13:20
@wangq8
wangq8 marked this pull request as draft July 6, 2026 13:27
@wangq8
wangq8 marked this pull request as ready for review July 6, 2026 13:27
@wangq8
wangq8 merged commit f477d33 into infiniflow:main Jul 7, 2026
5 of 6 checks passed
yuzhichang pushed a commit that referenced this pull request Jul 20, 2026
…6737)

Follow-up to #16468.

PR #16468 fixed the Python
(`api/db/joint_services/tenant_model_service.py
split_model_name`) and Go (`internal/service/model_service.go
parseModelName`)
parsers to right-anchor the '@'-split on the composite
"model_name@instance@provider" key, but the matching helper in the
front-end
(`web/src/utils/llm-util.ts parseModelValue`) was missed.

parseModelValue used `split('@')` (anchored on the first '@'), which
silently
mangles composite keys whose model_name itself contains '@' (e.g. LM
Studio
embedding IDs like `text-embedding-nomic-embed-text-v1.5@q8_0`):

  text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio

became

  model_name:     text-embedding-nomic-embed-text-v1.5
  model_instance: q8_0@lmstudio
  model_provider: LM-Studio

`PATCH /api/v1/models/default` then sent those to the server, which
returned
HTTP 200 with body `{"code": 102, "message": "Instance 'q8_0@lmstudio'
not
found for provider 'LM-Studio'"}`. The UI swallowed the body-level error
code, so the failure was silent: no toast, the Embedding field stayed
empty.

This change makes parseModelValue do a right-anchored split that mirrors
the
Python `split_model_name` `rsplit('@', 2)` exactly:

  - 3-part form: model_name@instance@provider -> same three fields.
- 2-part form: model_name@provider -> model_instance defaults to
"default"
    (matching Python).
- 4+-part form (embedded '@' in model name): last two fields are
anchored
as instance and provider, everything to the left is the bare model name.

`parseModelUuid` is updated to the same right-anchored split so the
factoryId portion of `model_name@factory_id[#instance]` keeps the last
'@'
as the separator even when the model name itself contains '@'.

Adds jest cases under `web/src/utils/tests/llm-util.test.ts` (12 total)
covering the plain 3-part, 2-part, 4-part, multi-'@' name,
buildModelValue
round-trip and parseModelUuid variants.

Note for reviewers: the front-end is bundled into the published docker
image, so a release containing this fix will need `docker compose build
--no-cache ragflow-cpu` (or equivalent) for it to be visible to end
users.

Refs #16468, #16467
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ValueError: too many values to unpack (expected 3) in list_tenant_added_models when LM-Studio model_name contains '@'

3 participants