Repository navigation
fix(config): prevent .pr_agent.toml state leak between repositories - #2346
tharatynowicz wants to merge 1 commit into
Conversation
Review Summary by QodoPrevent .pr_agent.toml state leak between repositories
WalkthroughsDescription• Prevent .pr_agent.toml configuration state leaking between repositories • Add reset_to_startup_defaults() function to restore global settings • Call reset at start of apply_repo_settings() for clean per-repo loads • Add regression tests verifying settings isolation between repos Diagramflowchart LR
A["apply_repo_settings called"] --> B["reset_to_startup_defaults"]
B --> C["Restore global_settings snapshot"]
C --> D["Load repo-specific config"]
D --> E["Clean state for next repo"]
File Changes1. pr_agent/config_loader.py
|
Code Review by Qodo
1. Override ledger crosses requests
|
| def apply_repo_settings(pr_url): | ||
| os.environ["AUTO_CAST_FOR_DYNACONF"] = "false" | ||
| # Reset first so that .pr_agent.toml from a previously-reviewed repo | ||
| # cannot leak into this call via the module-level global_settings singleton. | ||
| reset_to_startup_defaults() | ||
| git_provider = get_git_provider_with_context(pr_url) |
There was a problem hiding this comment.
1. Auto flag wiped 🐞 Bug ≡ Correctness
apply_repo_settings() now resets settings to a startup snapshot on every call, which clears config.is_auto_command that webhook servers set before invoking PRAgent.handle_request(). Auto-command flows can then behave like manual flows (e.g., publishing temporary/progress comments) because the flag is read later by tools but is removed by the second apply_repo_settings() call.
Agent Prompt
### Issue description
`reset_to_startup_defaults()` is invoked unconditionally at the top of `apply_repo_settings()`. In auto-command flows, servers set `config.is_auto_command=True` and then call `PRAgent.handle_request()`, but `PRAgent._handle_request()` calls `apply_repo_settings()` again first. The second call resets settings back to the startup snapshot and clears `config.is_auto_command`, changing downstream behavior.
### Issue Context
This is a regression introduced by adding the reset call; prior behavior relied on `is_auto_command` surviving into tool execution.
### Fix Focus Areas
- pr_agent/git_providers/utils.py[14-20]
- pr_agent/agent/pr_agent.py[54-57]
- pr_agent/servers/github_app.py[395-416]
- pr_agent/servers/gitlab_webhook.py[39-59]
### Suggested fix direction
Implement a mechanism so that the second `apply_repo_settings()` call in the same logical request does **not** clear runtime flags:
- Either avoid calling `apply_repo_settings()` twice (e.g., guard in `PRAgent._handle_request()` when settings were already applied), or
- Preserve and restore key runtime flags (at least `config.is_auto_command`, and any similar request-scoped flags) across `reset_to_startup_defaults()`.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| def reset_to_startup_defaults(): | ||
| """Restore ``global_settings`` to the state captured at the first call. | ||
|
|
||
| Must be invoked at the top of ``apply_repo_settings()`` so that sections | ||
| set by a previously-reviewed repo's ``.pr_agent.toml`` do not leak into | ||
| subsequent PRs processed by the same Python process. | ||
| """ | ||
| global _STARTUP_SETTINGS_SNAPSHOT | ||
| if _STARTUP_SETTINGS_SNAPSHOT is None: | ||
| _STARTUP_SETTINGS_SNAPSHOT = copy.deepcopy(global_settings.as_dict()) | ||
| return # nothing to restore on the very first call | ||
|
|
||
| current_sections = set(global_settings.as_dict().keys()) | ||
| snapshot_sections = set(_STARTUP_SETTINGS_SNAPSHOT.keys()) | ||
| # Remove sections that appeared after startup (i.e. injected by apply_repo_settings). | ||
| for section in current_sections - snapshot_sections: | ||
| global_settings.unset(section) | ||
| # Restore pre-existing sections to their startup values. | ||
| for section, contents in _STARTUP_SETTINGS_SNAPSHOT.items(): | ||
| global_settings.unset(section) | ||
| global_settings.set(section, copy.deepcopy(contents), merge=False) |
There was a problem hiding this comment.
2. Reset misses context settings 🐞 Bug ≡ Correctness
reset_to_startup_defaults() mutates only global_settings, but get_settings() prefers context["settings"] when present, so apply_repo_settings() can run against a different settings object than the one being reset. In deployments that install a per-request settings clone (e.g., Bitbucket app), the leak-prevention reset may not affect the effective settings for that request.
Agent Prompt
### Issue description
`reset_to_startup_defaults()` resets `global_settings` only, but `apply_repo_settings()` mutates `get_settings()`, which may be `context["settings"]` (a per-request clone). This can make the reset ineffective for the settings object actually used during request handling.
### Issue Context
`get_settings()` always tries `context["settings"]` first; Bitbucket app installs it as `copy.deepcopy(global_settings)`.
### Fix Focus Areas
- pr_agent/config_loader.py[48-62]
- pr_agent/config_loader.py[102-122]
- pr_agent/git_providers/utils.py[14-20]
- pr_agent/servers/bitbucket_app.py[266-273]
### Suggested fix direction
Change the reset logic to reset the *effective* settings object:
- Make `reset_to_startup_defaults()` operate on `get_settings()` (or accept a Dynaconf instance to reset), and
- Apply the startup snapshot contents into that object (context clone or global), so the reset actually affects what `apply_repo_settings()` will read/modify.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
Thanks for the review. Going through the three findings: 1. "Auto flag wiped" ‚ confirmed bug, introduced by this PR. The flow in 2. "Reset misses context settings" ‚ architecturally valid. In deployments that install a per-request 3. "Non-atomic global reset" ‚ theoretical in the current webhook deployments. In single-worker async servers the event loop serializes; in multi-worker ( Two directions to fix #1 and #2a) Minimal iteration on this PR: b) Larger refactor: push per-request settings isolation through Happy to do (a) on this PR if that's acceptable, or open a separate PR for (b) if you'd prefer to go that route instead. Which direction do you prefer? |
|
Heads-up for whoever picks this up — there is a parallel PR #2351 by @alonz101 also targeting issue #2345, taking a different route:
Both PRs come with unit tests at @ofir-frd — could you weigh in on which direction you'd prefer? Happy to close this one and rebase on top of #2351 if you'd rather take the surgical route; or to address review feedback here if you'd rather go global. Either way the leak is real (see issue #2345 reproducer) and biting a single-replica self-hosted setup right now. |
I think I'd rather go for the global approach here, this PR LGTM overall, I need to give the fixes some thought though |
|
Thanks @naorpeled - appreciate the read. Going to rebase onto main in the meantime (the branch is a couple of months stale at this point). Happy to wait for your direction on the is_auto_command and context["settings"] findings - or to take a shot at it myself if you would rather. No rush from my side. |
d7bb776 to
10c720d
Compare
…view Rework the state-leak fix from a full 'restore all settings to a startup snapshot' into a surgical per-key revert, and address Qodo's review of The-PR-Agent#2346. Why the rework: a blanket snapshot-restore at the top of apply_repo_settings() also wipes legitimate per-request/base config that current main sets before the call (config.extra_config_url, config.is_auto_command, mosaico flags, ...), regressing 11 existing tests. Instead, note_repo_setting_override() records the pre-override value of each key a repo/extra .pr_agent.toml writes, and reset_repo_settings_overrides() reverts exactly those keys on the next load. This addresses the review findings: - The-PR-Agent#1 (is_auto_command wiped): flags set outside the repo-settings merge are never recorded, so they are never reverted by the second apply_repo_settings(). - The-PR-Agent#2 (reset missed context settings): record/revert both go through get_settings(), so a per-request context['settings'] clone is handled too. - The-PR-Agent#3 (non-atomic global reset): record/revert are guarded by an RLock and touch only the overridden keys; full cross-request isolation still relies on a per-request clone. Also uses Dynaconf unset(force=True) (a plain unset() is a no-op) so a repo-injected key that did not exist at baseline is actually removed on revert. Tests: extend tests/unittest/test_apply_repo_settings.py with cases for flag preservation, non-repo config survival, and revert targeting the effective settings object. Full unit suite: 1717 passed. Co-authored-by: Tomasz Haratynowicz <75249676+tharatynowicz@users.noreply.github.com>
|
|
||
| import pytest | ||
|
|
||
| import pr_agent.config_loader as config_loader |
| # config merged below) so they cannot leak into this call via the shared settings | ||
| # singleton. Only repo-settings-managed keys are touched — see | ||
| # reset_repo_settings_overrides(). | ||
| reset_repo_settings_overrides() |
There was a problem hiding this comment.
1. Stale claude model keys 🐞 Bug ≡ Correctness
With the new selective reset, only keys recorded via note_repo_setting_override() are reverted, but apply_repo_settings() can also mutate config.model_weak and config.fallback_models via set_claude_model() without recording them. This allows repo-specific model_weak/fallback_models to leak into subsequent repos even after config.model is reverted, creating inconsistent model selection.
Agent Prompt
### Issue description
After adding `reset_repo_settings_overrides()` at the start of `apply_repo_settings()`, the reset only reverts keys recorded during TOML merges. However, `set_claude_model()` mutates additional settings (`config.model_weak`, `config.fallback_models`) without recording them, so those values can persist across repos.
### Issue Context
- Ledger entries are only created in the TOML merge loops that call `note_repo_setting_override(section, key)`.
- `set_claude_model()` sets multiple keys directly via `get_settings().set(...)`.
### Fix Focus Areas
- pr_agent/git_providers/utils.py[245-333]
- pr_agent/git_providers/utils.py[452-459]
- pr_agent/config_loader.py[114-155]
### Suggested fix
Before mutating any additional keys in `set_claude_model()`, record their prior values via `note_repo_setting_override("config", "model_weak")` and `note_repo_setting_override("config", "fallback_models")` (and optionally `model` for completeness). This ensures the next `reset_repo_settings_overrides()` fully restores the model-related configuration to its pre-repo state.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
Code review by qodo was updated up to the latest commit 10c720d |
Address the follow-up review on The-PR-Agent#2346: - Qodo 'Stale claude model keys': set_claude_model() also rewrites config.model_weak and config.fallback_models, which the selective revert did not track, so a repo using the 'claude-3-5-sonnet' shorthand leaked those derived keys into later repos. Record them via note_repo_setting_override() before writing, so they revert alongside config.model. - Revert now rebuilds each affected section once instead of calling unset() per key: Dynaconf's unset() cannot drop a nested key (e.g. config.model_weak that did not exist at baseline). The rebuild starts from the section's current contents, so sibling runtime keys (config.is_auto_command, ...) are preserved. - CodeQL (github-advanced-security): tests/unittest/test_apply_repo_settings.py imported pr_agent.config_loader with both 'import' and 'from import'. Use a single 'from ... import' style; the get_settings monkeypatch uses the string target form. Tests: add a regression test that config.model_weak / config.fallback_models do not leak across repos via the claude shorthand. Full unit suite: 1718 passed.
| _OVERRIDE_MISSING = object() # sentinel: key did not exist before the override | ||
| # {"SECTION.KEY" (upper, for dedup): (section, key, <pre-override value or _OVERRIDE_MISSING>)} | ||
| _APPLIED_REPO_OVERRIDES: dict = {} | ||
| # Serializes record/revert so overlapping background webhook tasks in one process |
There was a problem hiding this comment.
1. Override ledger crosses requests 🐞 Bug ⛨ Security
_APPLIED_REPO_OVERRIDES is module-global, but reset_repo_settings_overrides() replays it onto whichever object get_settings() returns on the next call, which can be a different per-request settings clone. If a repo config overrides a request-scoped credential (e.g. gitlab.personal_access_token), a subsequent request can have its injected token overwritten with a prior request’s value during reset.
Agent Prompt
### Issue description
`_APPLIED_REPO_OVERRIDES` is shared across the whole process, but `get_settings()` may return different settings objects across requests (global singleton vs per-request clone). This allows reset to apply “prior values” captured from request A onto request B’s settings object.
### Issue Context
Several servers create a per-request clone via `context["settings"] = copy.deepcopy(global_settings)` and mutate it (e.g., injecting GitLab tokens) before calling `apply_repo_settings()`. Because the override ledger is not scoped to the effective settings object, resets can overwrite request-scoped values.
### Fix Focus Areas
- pr_agent/config_loader.py[96-169]
- pr_agent/git_providers/utils.py[245-335]
- pr_agent/servers/gitlab_webhook.py[206-263]
### Implementation direction
- Make the override ledger **per effective settings object**, not module-global.
- Option A (recommended): use a `weakref.WeakKeyDictionary` mapping `settings_obj -> ledger_dict`, where `settings_obj = get_settings()`.
- Option B: attach a private attribute to the Dynaconf instance (e.g., `settings._pr_agent_repo_overrides = {...}`) if Dynaconf objects allow it reliably.
- Option C: store the ledger in `starlette_context.context` when `context["settings"]` exists, and fall back to a module-global ledger only when using `global_settings`.
- Ensure `note_repo_setting_override()` and `reset_repo_settings_overrides()` both read/write the same per-object ledger.
- Keep locking, but lock should protect the per-object ledger and its associated section rebuild operations.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
|
Code review by qodo was updated up to the latest commit b6d560c |
…nt#2345) Complements the per-request settings clone merged in The-PR-Agent#2351. That fix isolates every webhook server; this one covers callers that run many PRs in one process WITHOUT a per-request clone — notably github_polling — where a previous repo's .pr_agent.toml would otherwise persist in the shared global_settings when the next repo has no config file (the loader early-exits on empty repo settings). Approach: note_repo_setting_override() records the pre-override value of each key a repo/extra .pr_agent.toml writes; reset_repo_settings_overrides(), called at the top of apply_repo_settings(), reverts exactly those keys. Only repo-settings-managed keys are touched, so runtime/base config set outside the merge (config.extra_config_url, config.is_auto_command, ...) is preserved. Details: - Record/revert go through get_settings(), so a per-request context['settings'] clone is handled as well as global_settings. - Revert rebuilds each affected section once: Dynaconf's unset() cannot drop a nested key, and the rebuild preserves sibling keys not in the ledger. - set_claude_model() also rewrites config.model_weak / config.fallback_models; those are recorded too so the claude shorthand doesn't leak derived keys. - Record/revert are guarded by an RLock. Tests: tests/unittest/test_apply_repo_settings.py keeps the clone-based cases from The-PR-Agent#2351 and adds a class covering the no-clone path: leak reverted, runtime flags preserved, non-repo config preserved, revert targets the effective settings object, and no claude-shorthand model-key leak. Full unit suite: 1732 passed. Co-authored-by: Tomasz Haratynowicz <75249676+tharatynowicz@users.noreply.github.com>
b6d560c to
76e3e80
Compare
|
Code review by qodo was updated up to the latest commit 76e3e80 |
|
Hey @tharatynowicz, |
Fixes #2345.
Summary
apply_repo_settings()mutates the module-levelglobal_settingssingleton without resetting it first. When a PR comes from a repo without.pr_agent.toml,get_repo_settings()returnsb"", the loader early-exits onif repo_settings:, and whatever was injected by a previous repo's.pr_agent.tomllingers inglobal_settingsfor the rest of the process. Details, root-cause analysis and a self-contained reproducer are in #2345.Approach
reset_to_startup_defaults()inconfig_loader.py— lazy snapshot on first call (so any post-import startup, e.g.apply_secrets_manager_config(), is captured), full restore on subsequent calls.apply_repo_settings()so every per-repo load starts from a clean state..pr_agent.toml(other than their settings no longer carrying leftovers from a previous repo's load).Alternative I considered was a larger per-request isolation refactor (clone
global_settingsper request viacontext["settings"]set by a FastAPI middleware). Happy to go that route instead if preferred — this PR takes the minimal path.Tests
tests/unittest/test_apply_repo_settings.pywith two tests: a sanity test that.pr_agent.tomlinstructions are applied, and a regression test that a repo without.pr_agent.tomldoes not inherit the previous repo'sextra_instructions.mainwithout this fix and passes with it.main+ this change: 296 passed, 0 failed (the 2 new tests included).Diff: +147 / −1 across 3 files (fix: +36/−1 in 2 files; test: +111/−0 in 1 new file).