Skip to content

fix(llm): replace mutable default gen_conf={} with None + defensive copy - #14566

Merged
KevinHuSh merged 2 commits into
infiniflow:mainfrom
Ricardo-M-L:fix/llm-mutable-default-gen-conf
May 9, 2026
Merged

KevinHuSh merged 2 commits into
infiniflow:mainfrom
Ricardo-M-L:fix/llm-mutable-default-gen-conf

Conversation

@Ricardo-M-L

@Ricardo-M-L Ricardo-M-L commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

What

19 methods across rag/llm/chat_model.py and rag/llm/cv_model.py declare gen_conf={} (or gen_conf: dict = {}) as a parameter default and then mutate gen_conf in place — typically del gen_conf["max_tokens"], gen_conf["penalty_score"] = ..., or gen_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 pass gen_conf. The first such call's mutations leak into the default seen by every subsequent call.

# Before
def chat_streamly(self, system, history, gen_conf={}, **kwargs):
    if "max_tokens" in gen_conf:
        del gen_conf["max_tokens"]   # mutates the SHARED default dict
    ...

After call N with max_tokens set, call N+1 that omits gen_conf no longer sees max_tokens — even though the caller never touched it.

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 the config once and pass it on every turn) silently loses max_tokens, presence_penalty, etc. after the first round.

The 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.
# After
def chat_streamly(self, system, history, gen_conf=None, **kwargs):
    gen_conf = dict(gen_conf or {})
    if "max_tokens" in gen_conf:
        del gen_conf["max_tokens"]   # local copy — safe
    ...

This is byte-for-byte identical provider-side behavior for callers that already pass a fresh gen_conf per call. The new dict(...) copy is O(small constant) per call.

Files changed

  • rag/llm/chat_model.py — 17 methods
  • rag/llm/cv_model.py — 2 methods

Tests

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 ({} or []) as its default. The test caught five additional gen_conf: dict = {} sites that an initial gen_conf={} text grep had missed (annotated parameters with whitespace), and would fail again if the pattern is ever reintroduced.

$ pytest test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py -v
============================== 3 passed in 0.04s ===============================

ruff check passes on all touched files.

Notes

  • This PR is intentionally focused on just the gen_conf default + 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 review

  • Type annotation: gen_conf: dict = None → gen_conf: dict | None = None (5 occurrences in chat_model.py). The old annotation was a static-checker mismatch since None isn't a dict.
  • Regression test: the AST check accessed default.keys directly. ast.List has no .keys attribute — a future gen_conf=[] would crash with AttributeError instead of being caught. Use getattr for both .keys (Dict) and .elts (List). Manually verified the updated check correctly catches both gen_conf={} and gen_conf=[] while ignoring gen_conf=None and non-empty literals.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 4, 2026
@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Method signatures across chat and vision-language LLM integrations were changed to replace mutable gen_conf={} defaults with gen_conf=None, and each method now normalizes with gen_conf = dict(gen_conf or {}). A new AST-based regression test prevents reintroducing mutable defaults.

Changes

Mutable Default Argument Elimination

Layer / File(s) Summary
Data Shape & Interfaces
rag/llm/chat_model.py, rag/llm/cv_model.py
Updated many method signatures to accept gen_conf: dict = None instead of gen_conf={} across Base, LiteLLMBase, and provider classes (BaiChuanChat, LocalAIChat, MistralChat, ReplicateChat, BaiduYiyanChat, GoogleChat, Zhipu4V, NvidiaCV).
Implementation Normalization
.../chat_model.py, .../cv_model.py
Each affected method now immediately does gen_conf = dict(gen_conf or {}) (or equivalent) at start of body before further processing or request construction.
Tests
test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py
Added AST-based test that scans target modules for gen_conf parameters with mutable literal defaults ({} or []) and asserts they do not exist; includes a file-existence sanity check.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit hops through lines so keen,
Replacing shared dicts with something clean.
gen_conf=None, then copy away,
Each call fresh dawns a brand-new day 🐇
AST keeps watch while testers play.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: replacing mutable default gen_conf={} with None and adding defensive copy logic.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description comprehensively documents the problem (mutable defaults and caller pollution), the fix (gen_conf=None with defensive copy), all affected files, test coverage, and implementation notes.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@dosubot dosubot Bot added 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels May 4, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 24af087 and a60ef9a.

📒 Files selected for processing (3)
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • test/unit_test/rag/llm/test_gen_conf_no_mutable_default.py

Comment thread rag/llm/chat_model.py Resolved
Ricardo-M-L and others added 2 commits May 7, 2026 12:55
… 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.
@Ricardo-M-L
Ricardo-M-L force-pushed the fix/llm-mutable-default-gen-conf branch from a60ef9a to 700bb54 Compare May 7, 2026 04:55
@Ricardo-M-L

Copy link
Copy Markdown
Contributor Author

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
async def chat(self, system, history, gen_conf={}):
del gen_conf["max_tokens"] # mutates the SHARED default + caller's dict
```

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`):

  • `gen_conf: dict | None = None` annotation (so static type checkers accept None)
  • `getattr` for the `ast.List` path in the regression check (would have crashed with AttributeError on `gen_conf=[]`)

@KevinHuSh KevinHuSh added the ci Continue Integration label May 9, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 9, 2026 04:02
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 9, 2026 04:02
@codecov

codecov Bot commented May 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (12f80f1) to head (700bb54).
⚠️ Report is 2305 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevinHuSh
KevinHuSh merged commit 1046042 into infiniflow:main May 9, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 9, 2026
1 task done
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:M This PR changes 30-99 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants