Repository navigation
fix(llm): replace mutable default gen_conf={} with None + defensive copy - #14566
Conversation
📝 WalkthroughWalkthroughMethod signatures across chat and vision-language LLM integrations were changed to replace mutable ChangesMutable Default Argument Elimination
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@rag/llm/chat_model.py`:
- Line 224: Replace incorrect annotations of parameters declared as "gen_conf:
dict = None" with a nullable union type "gen_conf: dict | None = None" (or
simply "gen_conf=None") wherever it appears; specifically update the
async_chat_streamly method and the other four occurrences of the same signature
so that None is assignable to gen_conf and static type checkers (mypy/pyright)
no longer report an error.
In `@test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py`:
- Around line 71-72: The conditional incorrectly accesses .keys on ast.List
causing AttributeError; update the guard to check Dict and List separately and
use the correct field for each (use default.keys for ast.Dict and
getattr(default, "elts", None) for ast.List) so that when default is an ast.List
(e.g., gen_conf=[]) it is properly recognized and appended to bad with
(node.name, default.lineno); reference the variables/default check in the
existing condition that populates bad.
🪄 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: 29421023-0a9c-453c-a772-05e518f0bb89
📒 Files selected for processing (3)
rag/llm/chat_model.pyrag/llm/cv_model.pytest/unit_test/rag/llm/test_gen_conf_no_mutable_default.py
… copy
19 methods across `rag/llm/chat_model.py` and `rag/llm/cv_model.py`
declared `gen_conf={}` (or `gen_conf: dict = {}`) as a parameter
default and then mutated `gen_conf` in place — typically
`del gen_conf["max_tokens"]`, `gen_conf["penalty_score"] = ...`, or
`gen_conf.pop(...)` as part of provider-specific normalization.
Two latent bugs in this pattern:
1. **Mutable default argument** — Python evaluates default values once
at function-definition time, so the single `{}` dict is *shared*
across every caller that doesn't pass `gen_conf`. The first such
call's mutations (e.g. `del gen_conf["max_tokens"]`) leak into the
default seen by every subsequent call.
2. **Caller-dict pollution** — when the caller *does* pass a
`gen_conf` dict, the same in-place mutations modify the caller's
dict. A reused `gen_conf` (very common for chat-loop callers that
build a config once and pass it on every turn) silently loses
`max_tokens` after the first round.
Fix in every affected method:
- Change `gen_conf={}` (or `gen_conf: dict = {}`) → `gen_conf=None`
- Add `gen_conf = dict(gen_conf or {})` as the first statement of
the body so all subsequent mutations operate on a fresh local copy.
Adds `test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py` —
an `ast`-based regression guard that walks both modules and asserts
no parameter named `gen_conf` ever has a mutable literal as its
default. The test caught five additional `gen_conf: dict = {}` sites
that a `gen_conf={}` text grep had missed.
```
$ pytest test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py -v
============================== 3 passed in 0.04s ===============================
```
Behavior is unchanged for callers that pass a fresh `gen_conf` per
call — the `dict(...)` copy is O(small constant) per call and the
provider-side mutation logic is byte-for-byte identical.
1. rag/llm/chat_model.py: 5 method signatures had `gen_conf: dict = None`,
which is a type-annotation mismatch (None is not a dict). Change to
`gen_conf: dict | None = None` so static type checkers accept None.
2. test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py: the AST
check accessed `default.keys` directly. ast.List has no `.keys`
attribute, so a future `gen_conf=[]` regression would crash with
AttributeError instead of being detected. Use getattr for both
`.keys` (Dict) and `.elts` (List). Verified manually that the
updated check catches both `gen_conf={}` and `gen_conf=[]` while
ignoring `gen_conf=None` and non-empty literals.
a60ef9a to
700bb54
Compare
|
cc @KevinHuSh @yingfeng — would appreciate a review when you have a moment. This fixes a Python mutable-default-argument pattern spread across 19 methods in `rag/llm/chat_model.py` and `rag/llm/cv_model.py` that has two latent bugs: ```python 1. Mutable default leak. Python evaluates `{}` once at definition time. After call N deletes `max_tokens`, call N+1 that omits `gen_conf` no longer sees `max_tokens` either. 2. Caller-dict pollution. When a caller passes their own `gen_conf` dict, the in-place `del` / `gen_conf[k] = v` mutates the caller's dict. A reused config (very common in chat loops) silently loses fields after the first turn. Fix in every affected method: `gen_conf=None` + `gen_conf = dict(gen_conf or {})` at the top, so all subsequent mutations operate on a fresh local copy. Behavior is byte-for-byte identical for callers that already pass a fresh `gen_conf` per call. Includes an `ast`-based regression test that flags any future `gen_conf={}` or `gen_conf=[]` regression. Latest revision after CodeRabbit feedback (`700bb54a7`):
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14566 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
What
19 methods across
rag/llm/chat_model.pyandrag/llm/cv_model.pydeclaregen_conf={}(orgen_conf: dict = {}) as a parameter default and then mutategen_confin place — typicallydel gen_conf["max_tokens"],gen_conf["penalty_score"] = ..., orgen_conf.pop(...)as part of provider-specific normalization.The two bugs in this pattern
1. Mutable default argument (Python footgun). Python evaluates default values once at function-definition time, so the single
{}dict is shared across every caller that doesn't passgen_conf. The first such call's mutations leak into the default seen by every subsequent call.After call N with
max_tokensset, call N+1 that omitsgen_confno longer seesmax_tokens— even though the caller never touched it.2. Caller-dict pollution. When the caller does pass a
gen_confdict, the same in-place mutations modify the caller's dict. A reusedgen_conf(very common for chat-loop callers that build the config once and pass it on every turn) silently losesmax_tokens,presence_penalty, etc. after the first round.The fix
In every affected method:
gen_conf={}(orgen_conf: dict = {}) →gen_conf=None.gen_conf = dict(gen_conf or {})as the first statement of the body so all subsequent mutations operate on a fresh local copy.This is byte-for-byte identical provider-side behavior for callers that already pass a fresh
gen_confper call. The newdict(...)copy is O(small constant) per call.Files changed
rag/llm/chat_model.py— 17 methodsrag/llm/cv_model.py— 2 methodsTests
Adds
test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py— anast-based regression guard that walks both modules and asserts no parameter namedgen_confever has a mutable literal ({}or[]) as its default. The test caught five additionalgen_conf: dict = {}sites that an initialgen_conf={}text grep had missed (annotated parameters with whitespace), and would fail again if the pattern is ever reintroduced.ruff checkpasses on all touched files.Notes
gen_confdefault + copy fix. There's a related (but separate)history.insert(0, ...)pattern in the same files that mutates the caller's history list in 12 places — left for a follow-up so this PR stays mechanical and easy to review.Latest revision (
700bb54a7) — addresses CodeRabbit reviewgen_conf: dict = None→gen_conf: dict | None = None(5 occurrences inchat_model.py). The old annotation was a static-checker mismatch sinceNoneisn't adict.default.keysdirectly.ast.Listhas no.keysattribute — a futuregen_conf=[]would crash withAttributeErrorinstead of being caught. Usegetattrfor both.keys(Dict) and.elts(List). Manually verified the updated check correctly catches bothgen_conf={}andgen_conf=[]while ignoringgen_conf=Noneand non-empty literals.