Skip to content

fix(config): prevent .pr_agent.toml state leak between repositories - #2346

Closed
tharatynowicz wants to merge 1 commit into
The-PR-Agent:mainfrom
tharatynowicz:fix/apply-repo-settings-state-leak
Closed

tharatynowicz wants to merge 1 commit into
The-PR-Agent:mainfrom
tharatynowicz:fix/apply-repo-settings-state-leak

Conversation

@tharatynowicz

Copy link
Copy Markdown

Fixes #2345.

Summary

apply_repo_settings() mutates the module-level global_settings singleton without resetting it first. When a PR comes from a repo without .pr_agent.toml, get_repo_settings() returns b"", the loader early-exits on if repo_settings:, and whatever was injected by a previous repo's .pr_agent.toml lingers in global_settings for the rest of the process. Details, root-cause analysis and a self-contained reproducer are in #2345.

Approach

  • Add reset_to_startup_defaults() in config_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.
  • Call it at the top of apply_repo_settings() so every per-repo load starts from a clean state.
  • Additive change: no existing call sites modified, no signatures changed, no behaviour change for repos that do have a .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_settings per request via context["settings"] set by a FastAPI middleware). Happy to go that route instead if preferred — this PR takes the minimal path.

Tests

  • Added tests/unittest/test_apply_repo_settings.py with two tests: a sanity test that .pr_agent.toml instructions are applied, and a regression test that a repo without .pr_agent.toml does not inherit the previous repo's extra_instructions.
  • The regression test fails on main without this fix and passes with it.
  • Full existing unit suite on 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).

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Review Summary by Qodo

Prevent .pr_agent.toml state leak between repositories

🐞 Bug fix

Grey Divider

Walkthroughs

Description
• 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
Diagram
flowchart 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"]
Loading

Grey Divider

File Changes

1. pr_agent/config_loader.py 🐞 Bug fix +32/-0

Add state reset mechanism for global settings

• Import copy module for deep copying settings
• Add _STARTUP_SETTINGS_SNAPSHOT module-level variable to store initial state
• Implement reset_to_startup_defaults() function with lazy snapshot on first call
• Restore global_settings by removing injected sections and restoring pre-existing ones

pr_agent/config_loader.py


2. pr_agent/git_providers/utils.py 🐞 Bug fix +4/-1

Call reset function in apply_repo_settings

• Import reset_to_startup_defaults from config_loader
• Call reset_to_startup_defaults() at start of apply_repo_settings() function
• Add comment explaining the purpose of the reset call

pr_agent/git_providers/utils.py


3. tests/unittest/test_apply_repo_settings.py 🧪 Tests +111/-0

Add regression tests for settings state isolation

• Create new test file with TestApplyRepoSettings class
• Add test_repo_settings_from_toml_are_applied() sanity test verifying config loading
• Add test_repo_without_toml_does_not_inherit_previous_repo_settings() regression test
• Implement FakeGitProvider mock and fresh_global_settings fixture for test isolation

tests/unittest/test_apply_repo_settings.py


Grey Divider

Qodo Logo

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (9) 📘 Rule violations (0) 📎 Requirement gaps (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Override ledger crosses requests 🐞 Bug ⛨ Security
Description
_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.
Code

pr_agent/config_loader.py[R105-108]

+_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
Evidence
The PR introduces a module-global override ledger and applies it at the start of every
apply_repo_settings() call. In the GitLab webhook flow, a per-request context["settings"] clone
is created and mutated with personal_access_token before apply_repo_settings() is invoked, so a
reset that replays prior-request values can overwrite the current request’s token/settings.

pr_agent/config_loader.py[96-169]
pr_agent/git_providers/utils.py[245-334]
pr_agent/servers/gitlab_webhook.py[206-263]
pr_agent/servers/gitlab_webhook.py[50-70]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


2. Stale Claude model keys 🐞 Bug ≡ Correctness
Description
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.
Code

pr_agent/git_providers/utils.py[252]

+    reset_repo_settings_overrides()
Evidence
The reset at the top of apply_repo_settings only reverts keys recorded during TOML merges, but
set_claude_model mutates additional config keys without recording them, so they can persist across
requests/repos.

pr_agent/git_providers/utils.py[217-229]
pr_agent/git_providers/utils.py[245-259]
pr_agent/git_providers/utils.py[452-459]
pr_agent/config_loader.py[114-155]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


3. Auto flag wiped 🐞 Bug ≡ Correctness
Description
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.
Code

pr_agent/git_providers/utils.py[R14-19]

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)
Evidence
Servers set config.is_auto_command=True and then call agent.handle_request(), but
PRAgent._handle_request() calls apply_repo_settings() again first; with the new unconditional reset,
the flag is restored to the startup snapshot (typically False) before tools check it to decide
whether to publish comments/progress output.

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]
pr_agent/servers/bitbucket_server_webhook.py[159-217]
pr_agent/tools/pr_reviewer.py[69-75]
pr_agent/tools/pr_reviewer.py[152-154]
pr_agent/tools/pr_code_suggestions.py[105-107]
pr_agent/tools/pr_description.py[101-103]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


View more (1)
4. Reset misses context settings 🐞 Bug ≡ Correctness
Description
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.
Code

pr_agent/config_loader.py[R102-122]

+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)
Evidence
get_settings() returns context["settings"] when available. Some servers explicitly set
context["settings"] to a deep-copied clone of global_settings. apply_repo_settings() reads/writes
via get_settings(), but reset_to_startup_defaults() always operates on global_settings, leaving the
context clone untouched.

pr_agent/config_loader.py[48-62]
pr_agent/config_loader.py[102-122]
pr_agent/servers/bitbucket_app.py[266-273]
pr_agent/git_providers/utils.py[14-20]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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



Remediation recommended

5. Unnormalized section names 🐞 Bug ☼ Reliability ⭐ New
Description
note_repo_setting_override() records the section name with caller-provided casing, but
reset_repo_settings_overrides() later uses that recorded spelling to unset/set sections, while other
call sites may record the same logical section under different casing (e.g., config vs CONFIG). This
makes the reset behavior depend on Dynaconf’s case semantics and can cause the same logical section
to be rebuilt multiple times during a single reset.
Code

pr_agent/config_loader.py[R131-133]

+        _APPLIED_REPO_OVERRIDES[dedup_key] = (
+            section, key, prior if prior is _OVERRIDE_MISSING else copy.deepcopy(prior)
+        )
Evidence
The ledger stores the raw section string, and the reset logic groups and unsets/sets by that
stored value; meanwhile, call sites pass section from multiple sources with potentially different
casing (Dynaconf as_dict vs raw TOML vs hardcoded). This creates casing inconsistency for the same
logical section and makes reset behavior depend on Dynaconf’s case-handling.

pr_agent/config_loader.py[114-169]
pr_agent/git_providers/utils.py[218-228]
pr_agent/git_providers/utils.py[362-384]
pr_agent/git_providers/utils.py[452-464]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The repo-override ledger stores `(section, key, prior)` with `section` as provided by the caller. Callers pass `section` from mixed sources (parsed TOML section names, Dynaconf `as_dict()` keys, and hardcoded strings), so the same logical section can be represented with different casing (e.g. `config` vs `CONFIG`). During reset, the code groups and unsets/sets sections by this stored `section` value, making correctness rely on Dynaconf’s case-insensitive behavior and potentially causing redundant section rebuilds.

### Issue Context
- `note_repo_setting_override()` dedupes by `SECTION.KEY` uppercased, but it stores the original `section` string in the ledger.
- `reset_repo_settings_overrides()` groups by the stored `section` string.
- Call sites pass `section` with inconsistent casing across paths.

### Fix Focus Areas
- pr_agent/config_loader.py[114-169]
- pr_agent/git_providers/utils.py[218-228]
- pr_agent/git_providers/utils.py[362-384]
- pr_agent/git_providers/utils.py[452-464]

### Suggested implementation direction
- Normalize/canonicalize `section` when recording and when grouping/resetting (e.g., store `section_upper = section.upper()` in the ledger tuple, and group/reset by that canonical value).
- Optionally canonicalize `key` similarly for the stored tuple (while still removing existing keys case-insensitively as you already do).
- Keep the dedup key as-is, but ensure the stored tuple uses the same canonical casing used by reset so one logical section is rebuilt exactly once per reset.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Test ledger state leaks 🐞 Bug ☼ Reliability
Description
test_repo_settings_from_toml_are_applied() calls apply_repo_settings() once but doesn’t clear
_APPLIED_REPO_OVERRIDES, so later tests can start with stale ledger entries and their first
apply_repo_settings() will reset using prior-test data. This makes the test module order-dependent
and brittle for future additions.
Code

tests/unittest/test_apply_repo_settings.py[R72-75]

+    def test_repo_settings_from_toml_are_applied(
+        self, fresh_global_settings, monkeypatch
+    ):
+        """Sanity: ``apply_repo_settings()`` loads ``extra_instructions`` from a
Evidence
The test module defines a fixture to isolate _APPLIED_REPO_OVERRIDES, but the first test does not
use it and performs only a single apply_repo_settings() call; the ledger is only cleared on a
subsequent reset, so it can persist into later tests.

tests/unittest/test_apply_repo_settings.py[57-87]
tests/unittest/test_apply_repo_settings.py[88-121]
pr_agent/config_loader.py[114-169]
pr_agent/git_providers/utils.py[245-253]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
One test leaves the module-level repo-override ledger populated, which can influence subsequent tests that call `apply_repo_settings()` (they will consume the leftover ledger during `reset_repo_settings_overrides()`).
### Issue Context
A `clean_repo_overrides` fixture exists specifically to isolate `_APPLIED_REPO_OVERRIDES`, but `test_repo_settings_from_toml_are_applied` doesn’t use it.
### Fix Focus Areas
- tests/unittest/test_apply_repo_settings.py[57-87]
### Suggested fix
- Add `clean_repo_overrides` to the parameters of **every** test that calls `apply_repo_settings()`, or
- Make `clean_repo_overrides` an `autouse=True` fixture in this module so the ledger is always cleared/restored per test.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Extra config cleared on failure 🐞 Bug ☼ Reliability
Description
Because _apply_settings_from_file() now records its overrides for later reset, apply_repo_settings()
will revert previously-applied extra config at the start of the next call even if the extra config
cannot be resolved/loaded. This can drop provider-critical configuration mid-process and turn
transient extra-config fetch/load errors into hard failures.
Code

pr_agent/git_providers/utils.py[R223-226]

+                # Record the pre-override value first so it can be reverted on the
+                # next apply_repo_settings() (prevents cross-repo state leaks).
+                note_repo_setting_override(section, key)
              section_dict[key] = value
Evidence
apply_repo_settings() resets previously recorded overrides before attempting to resolve/apply extra
config; _resolve_extra_config_to_file() can return None and _apply_settings_from_file() can
early-return/log and not apply, leaving reverted state in effect despite extra config being
described as provider-critical.

pr_agent/git_providers/utils.py[170-243]
pr_agent/git_providers/utils.py[245-268]
pr_agent/config_loader.py[136-155]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`_apply_settings_from_file()` now records overrides into the same ledger used to prevent cross-repo repo-settings leaks. Since `apply_repo_settings()` resets that ledger *before* attempting to resolve/apply the extra config, a transient failure to resolve or load the extra config will leave the process with the reverted (cleared) state rather than the last known-good extra config.
### Issue Context
The code comment states extra config can carry provider-critical settings needed before provider initialization; clearing them before confirming the new extra config is successfully applied can cause transient outages.
### Fix Focus Areas
- pr_agent/git_providers/utils.py[170-243]
- pr_agent/git_providers/utils.py[245-280]
- pr_agent/config_loader.py[114-155]
### Suggested fix
Separate ledgers for (a) repo-local settings (must never leak cross-repo) and (b) operator extra config (shared). Alternatively, stage extra-config application: only clear/revert previously-applied extra-config keys after the new extra config is successfully resolved+validated+applied, or keep last-known-good extra config when resolution/loading fails.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (2)
8. Unset force kwarg unguarded 🐞 Bug ☼ Reliability
Description
reset_repo_settings_overrides() unconditionally calls settings.unset(dotted, force=True), but the
codebase explicitly includes fallback logic for older Dynaconf APIs elsewhere. If an environment
uses a Dynaconf where unset() doesn’t accept force, this will raise TypeError during reset when
reverting previously-missing keys.
Code

pr_agent/config_loader.py[R150-153]

+            if prior is _OVERRIDE_MISSING:
+                # force=True is required: Dynaconf's unset() is a no-op otherwise.
+                settings.unset(dotted, force=True)
+            else:
Evidence
The reset path uses an unconditional unset(force=True), while the extra-config loader contains
explicit fallback logic for older Dynaconf API differences, making this an unhandled compatibility
edge case.

pr_agent/config_loader.py[136-155]
pr_agent/git_providers/utils.py[170-215]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`settings.unset(dotted, force=True)` is not guarded, while other parts of the codebase already handle older Dynaconf API differences. This can cause reset to crash under older Dynaconf versions when reverting keys that were missing prior to override.
### Issue Context
`_apply_settings_from_file()` contains compatibility handling for older Dynaconf constructor parameters, indicating some intent to tolerate API/version variance.
### Fix Focus Areas
- pr_agent/config_loader.py[136-155]
- pr_agent/git_providers/utils.py[170-215]
### Suggested fix
Wrap the `unset(..., force=True)` call with a `try/except TypeError` and fall back to `unset(dotted)` (or another version-compatible deletion path) when `force` is unsupported.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Non-atomic global reset 🐞 Bug ☼ Reliability
Description
reset_to_startup_defaults() performs many unset/set operations on the module-level singleton, which
can race with other in-flight webhook processing and cause mid-run configuration changes. This risk
increases because the reset runs even when a repo has no .pr_agent.toml (previously that path was a
no-op).
Code

pr_agent/config_loader.py[R114-122]

+    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)
Evidence
The reset iterates sections and mutates global_settings repeatedly, with no synchronization. Webhook
servers schedule background tasks that can overlap across requests in the same process; those tasks
call PRAgent.handle_request() which calls apply_repo_settings(), so another request can reset global
settings while a prior request’s tools are still running and reading get_settings().

pr_agent/config_loader.py[114-122]
pr_agent/git_providers/utils.py[14-20]
pr_agent/servers/bitbucket_server_webhook.py[190-217]
pr_agent/agent/pr_agent.py[54-57]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Resetting `global_settings` via multiple `unset()`/`set()` calls is not atomic. Under concurrent webhook processing (especially with background tasks), one request can reset settings while another is executing tools that read `get_settings()`, leading to inconsistent behavior.
### Issue Context
This PR increases the frequency of global resets by running them for every `apply_repo_settings()` call, even when the repo has no `.pr_agent.toml`.
### Fix Focus Areas
- pr_agent/config_loader.py[114-122]
- pr_agent/git_providers/utils.py[14-20]
- pr_agent/servers/bitbucket_server_webhook.py[190-217]
### Suggested fix direction
Mitigate cross-request interference by either:
- Enforcing per-request settings isolation everywhere (preferred), or
- Adding a process-wide lock around reset+apply operations so `global_settings` cannot be mutated concurrently.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context used
  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment on lines 14 to 19
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)

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.

Action required

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

Comment thread pr_agent/config_loader.py Outdated
Comment on lines +102 to +122
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)

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.

Action required

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

@tharatynowicz

Copy link
Copy Markdown
Author

Thanks for the review. Going through the three findings:

1. "Auto flag wiped" ‚ confirmed bug, introduced by this PR.

The flow in bitbucket_server_webhook.py sets config.is_auto_command=True after the first apply_repo_settings(), then _process_command() calls apply_repo_settings() again per command, and my unconditional reset now wipes the flag before tools read it. Same shape exists in the GitHub/GitLab webhook paths. This needs to be addressed before merge.

2. "Reset misses context settings" ‚ architecturally valid.

In deployments that install a per-request context["settings"] clone (notably bitbucket_app.py), my reset mutates the unused global_settings while apply_repo_settings() writes into the clone. Worth noting that in those deployments the leak this PR targets doesn't occur in the first place (each request starts from a fresh clone of the current global_settings), so the reset is a no-op rather than incorrect ‚ÄĒ but making it operate on get_settings() is the cleaner design.

3. "Non-atomic global reset" ‚ theoretical in the current webhook deployments.

In single-worker async servers the event loop serializes; in multi-worker (--workers N) each process has its own singleton. The concern applies to concurrent background tasks within one process; acknowledged but I don't have a deterministic reproducer.

Two directions to fix #1 and #2

a) Minimal iteration on this PR: reset_to_startup_defaults() operates on get_settings() (addresses #2), and preserves a known set of runtime flags ‚ at least config.is_auto_command and config.is_new_pr ‚ÄĒ across the reset (addresses #1). ~15 extra lines, keeps the PR tight.

b) Larger refactor: push per-request settings isolation through RawContextMiddleware in every webhook target, so get_settings() always returns a per-request clone. Eliminates the singleton-mutation class of bug entirely and makes #3 moot. Much bigger change, touches every server entry point.

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?

@tomaszharatynowiczABS

Copy link
Copy Markdown

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 tests/unittest/test_apply_repo_settings.py.

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

@naorpeled

naorpeled commented Jun 6, 2026 •

Copy link
Copy Markdown
Member

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 tests/unittest/test_apply_repo_settings.py.

@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

@tharatynowicz

Copy link
Copy Markdown
Author

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.

@naorpeled
naorpeled force-pushed the fix/apply-repo-settings-state-leak branch from d7bb776 to 10c720d Compare August 8, 2026 16:49
naorpeled added a commit to tharatynowicz/pr-agent that referenced this pull request Aug 8, 2026
…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>
@github-actions github-actions Bot added the bug label Aug 8, 2026

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()

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.

Action required

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 10c720d

naorpeled added a commit to tharatynowicz/pr-agent that referenced this pull request Aug 8, 2026
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.
Comment thread pr_agent/config_loader.py
Comment on lines +105 to +108
_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

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.

Action required

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

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>
@naorpeled
naorpeled force-pushed the fix/apply-repo-settings-state-leak branch from b6d560c to 76e3e80 Compare August 8, 2026 18:24
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 76e3e80

@naorpeled

Copy link
Copy Markdown
Member

Hey @tharatynowicz,
Thanks for your work on this 🙏
After more thought, I ended up going with the other approach of per provider.
Feel free to follow up with any thoughts

@naorpeled naorpeled closed this Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

apply_repo_settings() leaks .pr_agent.toml state across PRs from different repositories

4 participants