Repository navigation
Fix: ValueError: too many values to unpack in list_tenant_added_models for model IDs containing '@' (#16467) - #16468
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughModel-name parsing now preserves embedded ChangesModel key parsing fixes
Dataset sampling guard
Subgraph relationship filtering
Estimated code review effort: 4 (Complex) | ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
api/apps/services/models_api_service.pytest/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py
|
Addressed the CodeRabbit docstring-coverage warning (75.00% → 100%) in commit The two helpers missing docstrings were:
Both now have full Google-style docstrings (Args / Returns) explaining the monkeypatching contract and the 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
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
api/apps/services/dataset_api_service.pyapi/apps/services/models_api_service.pyapi/db/joint_services/tenant_model_service.pyinternal/service/model_service.gotest/unit_test/api/db/services/test_tenant_model_service_split_model_name.py
There was a problem hiding this comment.
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 winTwo-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_0is still parsed asmodel_name="text-embedding-nomic-embed-text-v1.5"andprovider_name="q8_0", so_resolve_bare_model_provider()never runs. That means the LM Studio shape called out in this PR still resolves toNoneunless 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
📒 Files selected for processing (4)
api/apps/services/models_api_service.pyinternal/service/model_service.gointernal/service/model_service_test.gotest/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py
Lynn-Inf
left a comment
There was a problem hiding this comment.
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 ^).
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py (1)
98-100: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThis 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 winExplicit
TEI_MODEL@Builtinkeys still miss the TEI fast path when the model name already contains@.After the exact-match check,
splitRightAnchoredModelName("...@q8_0@Builtin")still producesteiPure="..."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 TEIBaseURL, so explicit Builtin keys do not behave the same as the bareTEI_MODELform.💡 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 winTwo-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 assignprovider_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 namedq8_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
📒 Files selected for processing (3)
api/apps/services/models_api_service.pyinternal/service/model_service.gotest/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py
…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.
|
@coderabbitai resume Pushed a follow-up at Could you take another look? |
Follow-up:
|
🧩 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.goLength 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.goLength of output: 3793 The fix looks solid. This resolves the Major/Functional Correctness concern I raised. Nice regression test coverage and clear inline comments explaining the ambiguity trade-off. ヽ(・∀・)ノ ✅ Action performedReview finished.
|
🧩 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 -5Length 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 -5Length of output: 6975 The fix looks correct and matches your description. The 2-segment case in
This resolves the earlier concern where One thing worth double-checking on your end: since the fallback now returns the full Approving this follow-up — nice catch and clean fix. ✅ Action performedReviews resumed. Review finished.
|
…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]>
…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]>
…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
left a comment
There was a problem hiding this comment.
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.
…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
|
Addressed the remaining review item in Why remove rather than wire in:
Validation:
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. |
|
Your plan includes PR reviews subject to rate limits. Reviews are available now. |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/services/dataset_api_service.py (1)
1155-1189: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winUnresolved 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 initialdocStoreConn.searchprobe in atryand 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
📒 Files selected for processing (1)
api/apps/services/dataset_api_service.py
4c78d8b to
b4db8cb
Compare
…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
Summary
Fixes #16467 —
ValueError: too many values to unpack (expected 3)inlist_tenant_added_modelsfor model IDs containing@, and three sibling code paths that exhibit the same@-mis-parsing bug. Adds a downstreamNotFoundErrortolerance 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:
Some model names legitimately contain
@characters (LM Studio embedding model IDs liketext-embedding-nomic-embed-text-v1.5@q8_0, llama.cpp@<quantization>suffixes, HuggingFace dataset IDs). The full composite key then has 4+@-separated fields:A naive
split("@")+ 3-element unpack mis-assigns the fields.Sites fixed
api/apps/services/models_api_service.py_get_model_infokey.rsplit("@", 2); bare-name case sets empty providerapi/db/joint_services/tenant_model_service.pysplit_model_namersplit("@", 2)from the rightinternal/service/model_service.goparseModelName@-segmentsinternal/service/model_service.goGetModelConfigFromProviderInstance@api/apps/services/models_api_service.pylist_tenant_added_modelsapi/apps/services/dataset_api_service.pysample_random_chunks_with_vectorsReview feedback addressed (commit 26a2cec)
TenantLLMServicedependency frommodels_api_service.py— the_resolve_bare_model_provider()function and itsTenantLLMServiceimport were deleted per maintainer request.@with|as internal map key separator inlist_tenant_added_modelsto avoid conflicts with model names containing@.@. The Builtin provider detection usesstrings.HasSuffixinstead ofsplitRightAnchoredModelNameto avoid misidentifying embedded@as a provider separator.TenantLLMService, added test for two-part model IDs with embedded@.Testing
test_models_api_service_list_tenant_added_models.py)gofmtvalidates syntax; Go tests require Linux (platform-specificbindingpackage)test_tenant_model_service_split_model_name.pyandmodel_service_test.gocover the parsing fixes