Fix request lookup when frame locals mutate - #120
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe request call-stack inspection now iterates over a snapshot of frame locals. A FastAPI regression test verifies safe behavior when tracing mutates those locals. ChangesRequest stack safety
Estimated code review effort: 2 (Simple) | ~10 minutes Mergeability Score: ⚪ Minimal · up to This localized change prevents request lookup failures when frame locals are modified during tracing, with regression coverage and reported checks passing; no actionable merge-blocking risk remains. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
PR Summary by QodoSnapshot frame locals during request lookup to avoid mutation errors
AI Description
Diagram
High-Level Assessment
Files changed (2)
|
Code Review by Qodo
1. Extra locals snapshot allocations
|
| for key in f_locals: | ||
| if key not in {'request', 'req'} and isinstance(f_locals[key], class_type): | ||
| return f_locals[key] | ||
| for key, value in tuple(f_locals.items()): |
There was a problem hiding this comment.
1. Extra locals snapshot allocations 🐞 Bug ➹ Performance
get_request_from_call_stack() now allocates tuple(f_locals.items()) for every inspected frame, creating an O(n) tuple of 2-tuples per frame walked. This increases CPU/memory overhead for correlation-id lookup during log formatting in FastAPI, where the library falls back to stack scanning (no global request object).
Agent Prompt
## Issue description
`RequestUtil.get_request_from_call_stack()` snapshots `tuple(f_locals.items())`, which allocates a tuple plus a 2-tuple per local entry for every frame visited.
## Issue Context
This codepath is exercised from `JSONLogWebFormatter` via `request_util.get_correlation_id(within_formatter=True)`. For FastAPI, `support_global_request_object()` is `False`, so correlation-id lookup may frequently fall back to scanning the call stack.
## Fix Focus Areas
- json_logging/util.py[180-200]
### Suggested approach
Preserve mutation-safety but reduce allocations by snapshotting only values:
- Keep the existing fast-path checks for `request` and `req`.
- Replace `for key, value in tuple(f_locals.items()): ...` with `for value in tuple(f_locals.values()): ...` (and drop the key filter), since you only need to detect any local whose value is an instance of `class_type`.
- Ensure the regression test still passes.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
There was a problem hiding this comment.
LlamaPReview — No blocking issues found
This PR safely fixes the RuntimeError by snapshotting frame locals before scanning, with a regression test that fails on the old code and no PR-caused correctness or security regressions found.
1 non-blocking finding retained — highest: Optional: per-frame tuple allocation in logging hot path.
Review details and evidence
| Priority | File | Finding | Evidence |
|---|---|---|---|
| P2 | json_logging/util.py |
Optional: per-frame tuple allocation in logging hot path | needs verification |
Finding details
P2 · Optional: per-frame tuple allocation in logging hot path
json_logging/util.py
The fix snapshots frame locals with tuple(f_locals.items()), adding a new O(n) allocation per scanned frame. The old loop already did O(n) work per frame, and typical frame-local counts are small; there is no evidence this is a material regression. Profiling of high-volume logging would determine if a follow-up optimization is warranted; this is not a merge blocker.
Owner action: Optionally profile high-volume logging to assess the tuple allocation cost; only optimize if a regression is measured.
Verification boundary: needs verification; scope: changed region.
Material unknowns
- Exact-head CI evidence for pytest/flake8/build is not independently present; only CodeRabbit status is available. Would confirm the change passes full CI rather than only statically analyzed; does not change the clear verdict.
- Check: Confirm CI run results on the final commit before merge for completeness.
LlamaPReview checks
- Read the complete PR-head file
json_logging/util.py. - Read the complete PR-head file
tests/test_fastapi.py.
LlamaPReview reviewed this pull request at its exact head commit. Inspect the source or share feedback.
Summary
frame.f_localsfrom a trace hook after iteration startsFixes #89
Testing
python -m pytest --ignore tests/smoketests -q(24 passed)backend=fastapi python -m pytest tests/smoketests/test_run_smoketest.py -q(1 passed)python -m flake8 json_logging tests --count --select=E9,F63,F7,F82 --show-source --statisticspython -m buildpython -m pip checkSummary by CodeRabbit
Bug Fixes
Tests