Skip to content

feat: optional provider-side request attribution via the OpenAI user field - #2584

Merged
naorpeled merged 3 commits into
The-PR-Agent:mainfrom
FabrizioCafolla:feature/add-user-to-requests
Aug 1, 2026
Merged

naorpeled merged 3 commits into
The-PR-Agent:mainfrom
FabrizioCafolla:feature/add-user-to-requests

Conversation

@FabrizioCafolla

Copy link
Copy Markdown
Contributor

🤖 This was written by an AI agent on behalf of @FabrizioCafolla.

Why

Requests recorded on the provider side carry no link back to the PR that generated them. Attributing cost or debugging a single PR against a provider's activity log requires timestamp correlation between PR-Agent logs and the provider dashboard, which breaks down on deployments serving many repositories: one PR event alone produces several calls (describe, review, improve, retries, fallbacks).

PR-Agent already knows the command and the PR URL at call time, in the logging context that PRAgent.handle_request sets. This PR forwards that information to the provider, opt-in.

What

[config]
add_user_to_requests = false  # default: off, requests unchanged

When enabled, chat_completion sends the current command and PR URL in the OpenAI-compatible user request field, as a compact JSON string:

{"command":"improve","pr_url":"https://gitlab.example.com/group/project/-/merge_requests/171"}

OpenRouter records it as external_user in the generation details and in the activity export; other providers that persist the field get the same benefit. When the setting is off, requests are byte-identical to today's (unit-tested).

How

The context is read with the same loguru-sink mechanism add_litellm_callbacks uses, so it works from the webhook servers and from the CLI, with no extra API calls.

Where the field goes depends on what LiteLLM supports for the target model, checked at runtime via litellm.get_supported_openai_params(model):

Provider Behavior
OpenAI, Azure, Anthropic, Bedrock standard user parameter
openrouter/* extra_body (LiteLLM's OpenRouter transformation drops the user parameter; extra_body reaches the request body verbatim)
Providers without user support (e.g. Gemini, DeepSeek) skipped with a debug log, so the setting can never break a call regardless of litellm.drop_params

The value is truncated to 256 characters as a defensive bound.

Privacy

Enabling the setting shares the PR URL with the model provider, so it is off by default and documented as an explicit operator choice (docs/docs/usage-guide/additional_configurations.md).

Testing

  • 5 unit tests in tests/unittest/test_litellm_request_user_field.py (off-by-default no-op, field set with context, extra_body routing for openrouter/*, unsupported-provider skip, no-context no-op), mirroring the style of test_litellm_openrouter_controls.py.
  • Full unit suite: 1550 passed. Ruff: no new findings.
  • Exercised end to end against OpenRouter from the CLI: the generation log records the payload in external_user.

…r field

When config.add_user_to_requests is enabled, chat_completion sends the current
command and PR URL in the OpenAI-compatible "user" request field, as a compact
JSON string, so provider logs and usage exports can be attributed to a specific
PR and command without timestamp correlation. OpenRouter records it as
external_user and includes it in the activity export.

The context comes from the logging extras set by PRAgent.handle_request, the
same mechanism add_litellm_callbacks uses. For openrouter/* models the value is
also placed in extra_body, because LiteLLM's OpenRouter transformation does not
forward the standard user parameter.

Disabled by default: it shares request-attribution data with the model
provider, so enabling it is an explicit operator choice.

Assisted-by: claude-code/claude-fable-5
@github-actions github-actions Bot added the feature 💡 label Jul 31, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Optional provider-side request attribution via OpenAI "user" field

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Add opt-in config to attach PR command/URL attribution to LLM requests.
• Route attribution via OpenAI user field or OpenRouter extra_body fallback.
• Document privacy implications and add unit tests for no-op and routing behavior.
Diagram

graph TD
  A["Loguru context"] --> B["LiteLLM chat_completion"] --> C{"Add request user?"}
  C -- "disabled" --> G["litellm.acompletion"] --> H["Provider logs"]
  C -- "supports user" --> D["Set kwargs.user"] --> G
  C -- "openrouter/*" --> E["Set extra_body.user"] --> G
  C -- "unsupported" --> F["Skip + debug"] --> G
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use provider-specific request IDs/headers
  • ➕ Keeps attribution out of model-visible request fields in some providers
  • ➕ Can be standardized as an internal correlation ID across logs
  • ➖ Not uniformly supported across providers/proxies
  • ➖ Often not persisted into provider usage exports/activity logs
2. Rely solely on observability callbacks (Langfuse/LangSmith)
  • ➕ Centralized attribution without sharing PR URLs with the model provider
  • ➕ No dependency on provider parameter mappings
  • ➖ Does not solve provider-dashboard attribution/cost analysis use case
  • ➖ Requires operating a separate observability stack to query attribution
3. Add an explicit PR-Agent correlation ID field (non-OpenAI param)
  • ➕ Clear semantic contract under PR-Agent control
  • ➕ Avoids overloading the meaning of OpenAI user
  • ➖ Likely dropped by many adapters/providers unless tunneled (e.g., extra_body)
  • ➖ More complex compatibility story than using an existing OpenAI parameter

Recommendation: Keep the current opt-in approach using the OpenAI-compatible user field with an OpenRouter extra_body passthrough fallback. It best matches the goal (provider-side attribution in dashboards/exports) while remaining safe-by-default (disabled) and defensive (skip when unsupported).

Files changed (4) +189 / -0

Enhancement (1) +57 / -0
litellm_ai_handler.pyInject PR attribution into LiteLLM requests via OpenAI 'user' +57/-0

Inject PR attribution into LiteLLM requests via OpenAI 'user'

• Introduces a helper to build a compact JSON 'user' value from the current logging context (command + PR URL, truncated). When enabled by config, 'chat_completion' conditionally sets 'kwargs.user', routes via 'extra_body' for 'openrouter/*', or skips for unsupported providers.

pr_agent/algo/ai_handlers/litellm_ai_handler.py

Tests (1) +109 / -0
test_litellm_request_user_field.pyAdd unit coverage for request 'user' attribution routing +109/-0

Add unit coverage for request 'user' attribution routing

• Adds async unit tests validating the feature is a no-op by default, sets 'user' when enabled and context exists, uses 'extra_body' for OpenRouter models, and skips unsupported providers without breaking calls.

tests/unittest/test_litellm_request_user_field.py

Documentation (1) +22 / -0
additional_configurations.mdDocument opt-in provider-side request attribution +22/-0

Document opt-in provider-side request attribution

• Adds documentation for the new 'add_user_to_requests' setting, including the JSON payload format and a privacy note that enabling shares attribution data with the provider.

docs/docs/usage-guide/additional_configurations.md

Other (1) +1 / -0
configuration.tomlAdd 'add_user_to_requests' config flag (default off) +1/-0

Add 'add_user_to_requests' config flag (default off)

• Adds a new configuration option to enable/disable provider-side request attribution via the OpenAI-compatible 'user' request field.

pr_agent/settings/configuration.toml

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

qodo-free-for-open-source-projects Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. capture_logs may raise AttributeError ✓ Resolved 📘 Rule violation ☼ Reliability
Description
_get_request_user_field() dereferences record.get("extra", None).get(...), which can raise if
extra is missing, breaking request attribution and potentially the request flow when enabled. This
violates the robust error-handling requirement for edge cases in runtime logging context extraction.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R439-442]

+            if record.get("extra", None).get("command", None) is not None:
+                log_entry.update({"command": record["extra"]["command"]})
+            if record.get("extra", {}).get("pr_url", None) is not None:
+                log_entry.update({"pr_url": record["extra"]["pr_url"]})
Evidence
PR Compliance ID 3 requires handling edge cases without unhandled exceptions. The added
capture_logs() function calls .get() on the result of record.get("extra", None), which can be
None and cause an unhandled exception at runtime.

Rule 3: Robust Error Handling
pr_agent/algo/ai_handlers/litellm_ai_handler.py[436-442]

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

## Issue description
`_get_request_user_field()` uses `record.get("extra", None).get(...)`, which can raise `AttributeError` if `extra` is absent/None.
## Issue Context
This code runs when `config.add_user_to_requests` is enabled and is meant to be a safe, optional, non-breaking enhancement.
## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[436-443]

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


2. Logger sink removal not guaranteed ✓ Resolved 📘 Rule violation ☼ Reliability
Description
_get_request_user_field() adds a temporary loguru sink but does not use try/finally to ensure
get_logger().remove(handler_id) always runs. If an exception occurs between add() and
remove(), the sink could leak and capture unrelated logs, impacting reliability/performance.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R445-447]

+        handler_id = get_logger().add(capture_logs)
+        get_logger().debug("Capturing logs for the request user field")
+        get_logger().remove(handler_id)
Evidence
PR Compliance ID 3 requires graceful handling of error scenarios. The code adds a log sink
(get_logger().add(...)) and then removes it, but without a try/finally, failures can prevent
cleanup and leave the process in a bad state.

Rule 3: Robust Error Handling
pr_agent/algo/ai_handlers/litellm_ai_handler.py[445-447]

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

## Issue description
Temporary loguru sink added in `_get_request_user_field()` is removed without a `try/finally`, so exceptions can leave the sink installed.
## Issue Context
This method is called from `chat_completion()` when `config.add_user_to_requests` is enabled; it should never leave global logging state altered.
## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[445-447]

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



Remediation recommended

3. Swallowed param-check errors 🐞 Bug ◔ Observability
Description
In LiteLLMAIHandler.chat_completion, exceptions from litellm.get_supported_openai_params() are
swallowed and treated as “no supported params,” which can silently disable request attribution for
non-OpenRouter models. This also makes the later “unsupported … skipped” debug message misleading
because it conflates real lack of support with probe failures.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R662-665]

+                        try:
+                            supported_params = litellm.get_supported_openai_params(model=model) or []
+                        except Exception:
+                            supported_params = []
Evidence
The new code explicitly suppresses all exceptions from the supported-params probe and treats the
result as empty, which drives the “skip” branch for non-OpenRouter models and provides no log signal
that the probe itself failed.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[653-681]

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

## Issue description
`chat_completion()` wraps `litellm.get_supported_openai_params(model=...)` in a broad `except Exception:` and then proceeds with `supported_params = []` without logging the exception. For non-OpenRouter models this results in skipping the attribution field with no way to distinguish “provider truly doesn’t support `user`” vs “capability probe failed.”
### Issue Context
- The attribution feature is opt-in and intended to be safe; however, probe failures currently degrade behavior silently for most providers.
- OpenRouter models still work via the `model.startswith("openrouter/")` fallback path even when the probe fails, so the issue is primarily for non-OpenRouter providers.
### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[662-681]
### Recommended fix
- In the `except Exception as e:` branch:
- Emit a debug (or warning) log including the exception (`get_logger().debug(..., exc_info=True)` / `get_logger().exception(...)` depending on preferred style), so operators can see probe failures.
- Optionally adjust the later “unsupported … skipped” log to differentiate between:
  - probe failure (e.g., `add_user_to_requests: failed to check supported params for {model}, skipped`) and
  - confirmed unsupported param.
- Add/extend a unit test that patches `litellm.get_supported_openai_params` to raise, and asserts:
- for a non-OpenRouter model, no `kwargs["user"]` is set and a diagnostic log is produced;
- for an OpenRouter model, the value still ends up in `kwargs["extra_body"]["user"]` even if the probe raises.

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


4. Cross-request attribution leak ✓ Resolved 🐞 Bug ⛨ Security
Description
LiteLLMAIHandler._get_request_user_field temporarily attaches a process-wide Loguru sink and then
uses the first captured log record, so concurrent requests can win the race and cause another
request’s command/pr_url to be sent as this request’s OpenAI-compatible "user" field. This breaks
attribution correctness and can disclose a different PR URL/command to the model provider when the
feature is enabled.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R434-450]

+        captured_extra = []
+
+        def capture_logs(message):
+            record = message.record
+            log_entry = {}
+            if record.get("extra", None).get("command", None) is not None:
+                log_entry.update({"command": record["extra"]["command"]})
+            if record.get("extra", {}).get("pr_url", None) is not None:
+                log_entry.update({"pr_url": record["extra"]["pr_url"]})
+            captured_extra.append(log_entry)
+
+        handler_id = get_logger().add(capture_logs)
+        get_logger().debug("Capturing logs for the request user field")
+        get_logger().remove(handler_id)
+
+        context = captured_extra[0] if len(captured_extra) > 0 else {}
+        if not context:
Evidence
The new method installs a global sink and then uses the first captured record as the request
context; because the logger is a singleton used across concurrent request handlers, other requests
can log while the sink is installed, resulting in the wrong context being chosen and forwarded to
the provider.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[427-460]
pr_agent/log/init.py[65-66]
pr_agent/agent/pr_agent.py[101-107]
pr_agent/servers/bitbucket_server_webhook.py[29-43]

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

## Issue description
`_get_request_user_field()` adds a global Loguru sink and then reads `captured_extra[0]`. In concurrent webhook/server usage, unrelated log records from other requests can be captured first, causing the wrong `command`/`pr_url` to be serialized and sent to the provider as the request attribution.
### Issue Context
- `get_logger()` returns the global Loguru logger (shared across concurrent requests).
- Multiple servers run request handlers concurrently (async/background tasks) while using `logger.contextualize()`.
### Fix approach
Make the capture request-scoped so it can only capture the record emitted by this method:
- Add a `filter=` to `get_logger().add(...)` that only accepts a uniquely-identifiable record (e.g., match the message text, or bind a unique marker in `extra` and filter on it).
- Prefer selecting the matching captured record (or the last one) rather than `captured_extra[0]`.
- Wrap `remove(handler_id)` in `try/finally` to avoid leaking the sink if anything raises.
### Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[427-460]

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


5. Single quotes in _get_request_user_field ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
New Python code uses single-quoted strings and mixed quoting, which violates the repo style
requirement to prefer double quotes and may trigger Ruff lint failures.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R439-442]

+            if record.get('extra', None).get('command', None) is not None:
+                log_entry.update({"command": record['extra']["command"]})
+            if record.get('extra', {}).get('pr_url', None) is not None:
+                log_entry.update({"pr_url": record['extra']["pr_url"]})
Evidence
PR Compliance ID 13 requires Ruff/isort style conformance and explicitly prefers double quotes. The
added code uses single-quoted string literals and dict keys (e.g., record.get('extra', None) and
record['extra']).

AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes)
pr_agent/algo/ai_handlers/litellm_ai_handler.py[439-442]

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

## Issue description
New code in `LiteLLMAIHandler._get_request_user_field()` uses single quotes (and mixed quote styles) for string literals and dict keys, conflicting with the repo’s Ruff/formatting conventions that prefer double quotes.
## Issue Context
This is a style/lint compliance issue and may introduce new Ruff findings.
## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[439-442]

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


View more (2)
6. Overlong debug f-string line ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
A newly added debug log line appears to exceed the 120 character limit, which violates the
repository Ruff line-length policy.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R663-664]

+                            get_logger().debug(
+                                f"add_user_to_requests: 'user' not supported for model {model}, skipping")
Evidence
PR Compliance ID 13 requires adherence to Ruff formatting including a 120 character line limit. The
added debug f-string is a single long line within the new block and likely exceeds that limit.

AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes): AGENTS.md: Conform to Ruff/Isort Style (Line Length 120, Import Ordering, Prefer Double Quotes)
pr_agent/algo/ai_handlers/litellm_ai_handler.py[663-664]

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

## Issue description
A newly added debug log message is very long and likely exceeds the configured Ruff line length limit (120).
## Issue Context
The repository compliance checklist requires line length 120 for Python code.
## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[663-664]

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


7. Invalid JSON truncation ✓ Resolved 🐞 Bug ≡ Correctness
Description
LiteLLMAIHandler._get_request_user_field truncates the serialized JSON with [:256], which can cut
mid-string and produce invalid JSON when command/pr_url are long. This breaks the documented/tested
expectation that the provider attribution value is a compact JSON string.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[452]

+        return json.dumps(context, separators=(",", ":"))[:256]
Evidence
The implementation slices the serialized JSON string, which can produce malformed JSON, while
docs/tests treat the value as parseable JSON.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[427-452]
tests/unittest/test_litellm_request_user_field.py[78-84]
docs/docs/usage-guide/additional_configurations.md[123-130]

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

## Issue description
`_get_request_user_field()` currently does `json.dumps(... )[:256]`. If the JSON exceeds 256 characters, slicing can remove closing quotes/braces and yield an invalid JSON string.
## Issue Context
The feature is documented as sending a compact JSON string in the OpenAI-compatible `user` field.
Tests also parse the value with `json.loads(...)`, reinforcing the expectation that it remains valid JSON.
## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[427-452]
## Implementation guidance
- Do **not** slice the serialized JSON.
- Instead, enforce the 256-character cap by truncating individual values (e.g., `command`, `pr_url`) *before* serialization, then `json.dumps` the final dict.
- Ensure the final output is always valid JSON (and ideally add a unit test that uses an artificially long `pr_url` to assert: `len(user_field) <= 256` and `json.loads(user_field)` succeeds).

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


Grey Divider

  • 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

Review findings from the PR bot: slicing the serialized JSON at 256 chars
could cut through closing quotes and braces, contradicting the docs and the
tests that parse the value. The cap now applies to the individual values
before serialization (command 30 chars, pr_url 200), with a unit test
asserting the result stays parseable and within bounds on an oversized URL.
The helper also switches to double quotes per the repository style rule.

Assisted-by: claude-code/claude-fable-5
@FabrizioCafolla

Copy link
Copy Markdown
Contributor Author

🤖 This was written by an AI agent on behalf of @FabrizioCafolla.

Both review findings addressed in e10f995:

  • Valid JSON under the cap: the truncation finding was correct. The cap now applies to the individual values before serialization (command 30 chars, pr_url 200), and a new unit test asserts the output stays parseable and within 256 chars on an oversized URL.
  • Quote style: the new helper now uses double quotes throughout.

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

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit e10f995

Review findings from the PR bot on the context capture:

- Cross-request attribution leak: the temporary loguru sink is process-wide,
  so under concurrent requests the first captured record could belong to
  another request, sending someone else's PR URL as this request's user
  field. The probe record is now matched by identity (an object() token
  passed through the record extras), so a sink can only ever capture its own
  request's context. Covered by a new concurrency test with two interleaved
  contexts.
- AttributeError guard: record extras are read with (record.get("extra") or {}).
- The sink is removed in a try/finally, so a logging failure cannot leak it.
- The unsupported-provider debug message drops the inner quotes and fits the
  line limit.

Assisted-by: claude-code/claude-fable-5
@FabrizioCafolla

Copy link
Copy Markdown
Contributor Author

🤖 This was written by an AI agent on behalf of @FabrizioCafolla.

All four findings from the updated review addressed in 91cbd77:

  • Cross-request attribution leak (the substantive one): confirmed. The temporary sink is process-wide, so under concurrency the first captured record could belong to another request. The probe record is now matched by identity (an object() token passed through the record extras), so each sink can only capture its own request's context. A new concurrency test runs two interleaved contexts and asserts no cross-attribution; it fails on the previous implementation.
  • AttributeError on missing extras: reads now go through record.get("extra") or {}.
  • Sink removal: wrapped in try/finally.
  • Overlong debug line: reworded within the limit, inner quotes dropped.

Full unit suite: 1552 passed. For what it is worth, the same process-wide-sink race exists in add_litellm_callbacks, which this helper originally mirrored; happy to file it separately.

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

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 91cbd77

@naorpeled
naorpeled merged commit e46707d into The-PR-Agent:main Aug 1, 2026
5 checks passed
@naorpeled

Copy link
Copy Markdown
Member

Thanks @FabrizioCafolla !!

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.

2 participants