Repository navigation
fix(python): narrow mocked_module to patches that can reach the owner - #9053
EffortlessSteven wants to merge 6 commits into
Conversation
A related test that only patches a string-literal dotted target the owner's
file never names (for example patch("os.getcwd") against an owner that does
not use os or getcwd) no longer raises the mocked_module static limit.
patch.object, patch.multiple, setitem/delattr, object-form setattr,
non-literal/f-string/concatenated targets, bare @patch, any target segment
present in the owner's file or module name, and a missing owner source all
keep the limit.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AMgxgeL3JK2XZPNNoEB9Y6
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
Warning Review limit reachedEnable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing. Next included review available in 23 minutes. View limit details
Comment |
| const OPAQUE_FORMS: [&str; 4] = [ | ||
| "patch.object(", | ||
| "patch.multiple(", | ||
| "monkeypatch.setitem(", | ||
| "monkeypatch.delattr(", | ||
| ]; |
There was a problem hiding this comment.
OPAQUE_FORMS and is_patch_decorator_name do not cover patch.dict(...) / mock.patch.dict(...) / mocker.patch.dict(...), nor other mutation helpers such as monkeypatch.setenv.
form_sites(body, "patch(") does not match patch.dict(. A test combining a readable disjoint @patch("os.getcwd") with @patch.dict("sys.modules", {...}) is therefore treated as fully disjoint. The mocked_module limit is dropped even though an unreadable substitution site exists. This breaks the fail-closed guarantee.
Add the missing forms to the opaque list and to the decorator-name check:
const OPAQUE_FORMS: [&str; N] = [
"patch.object(", "patch.multiple(", "patch.dict(",
"monkeypatch.setitem(", "monkeypatch.delattr(", "monkeypatch.setenv(", /* ... */
];
// and in is_patch_decorator_name:
["patch", "patch.object", "patch.multiple", "patch.dict"]Spotted by Graphite
Is this helpful? React 👍 or 👎 to let us know.
There was a problem hiding this comment.
Confirmed and fixed in 8662371: patch.dict( is now an opaque form and a recognized patch decorator name, so a readable disjoint @patch beside patch.dict / mock.patch.dict keeps the limit (three new negative cases). monkeypatch.setenv is not added: it never counted as a mock site before and substitutes no code, so listing it would widen the limit rather than preserve it.
Generated by Claude Code
A readable disjoint patch next to patch.dict(...) was treated as fully disjoint; patch.dict is an unreadable substitution site, so it is now an opaque form and a patch decorator name. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AMgxgeL3JK2XZPNNoEB9Y6
There was a problem hiding this comment.
Reporter summary
All five lanes landed on changes_requested, and the deciding fact is the late cargo-test failure (exit 101) under cargo test -p ripr --lib analysis::language::python, which directly contradicts the PR body's '747 passed, 0 failed' claim. The mock_patch.rs surface review is favorable: the Graphite-flagged patch.dict gap was fixed in 8662371 (OPAQUE_FORMS and is_patch_decorator_name both list patch.dict, three negative cases cover it, monkeypatch.setenv is correctly excluded), and the owner-source plumbing through classify.rs and repo/evidence.rs is consistent. Remaining concerns beyond the failing test: minor literal_target gaps (b/r/u string prefixes not rejected), a documented residual that name-disjointness cannot see cross-module callees, and an architectural fragility where any future PythonTest construction site that omits decorator_texts silently fails closed (which is good defense but not an invariant — no test pins it). Approval is blocked until the exit-101 test failure is identified, fixed, and the same cargo-test invocation exits 0, ideally with clippy and precommit re-run on the post-fix tree.
|
Re the exit-101 note: on the current head 8662371, The Generated by Claude Code |
|
Independent review (multi-angle): changes needed
Generated by Claude Code |
|
Review scope note: the review above was done against head Generated by Claude Code |
…ther file A class-level @patch is not retained on the test, and an owner that imports beyond self-contained stdlib modules or calls super() may reach the patched name through another file, so both keep the limit. SPEC-0028 documents the narrowing. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AMgxgeL3JK2XZPNNoEB9Y6
There was a problem hiding this comment.
Decision
- Needs reviewer attention before upstream: findings remain.
Confirmed findings
- Test_has_mocked_module itself is unchanged per rollback note; spec at RIPR-SPEC-0028 lists patched helpers but does not enumerate mock.patch( / mocker.patch( forms explicitly, only patch( / monkeypatch.setattr(. A doc nit, not a correctness issue.
Parked follow-ups
- PythonTest gained an unconditional decorator_texts field; six PythonTest literals in python_tests.rs/owners_tests.rs were updated, but no compile-time barrier prevents a future construction site from omitting it (silently Vec::new() → fail-closed for mock_patch). Defense-in-depth, not invariant.
Evidence gaps
- Model proof intent was rejected by deterministic validation.
…argets Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AMgxgeL3JK2XZPNNoEB9Y6
|
Closing without merge. An independent review of head f4af8e3 found two false-actionable holes that no further narrowing of this rule can close:
Fixtures and conftest-supplied patches are also unscanned. Dropping Generated by Claude Code |
There was a problem hiding this comment.
Confirmed findings
- test_has_mocked_module itself is unchanged per the rollback note and the changelog fragment only lists patched helpers; the new mock.patch( / mocker.patch( forms are not enumerated in RIPR-SPEC-0028's mocked_module bullet or in the test name list of mock_patch_tests.rs. Doc/test nit, not a correctness issue, since the helper mechanically covers them via LITERAL_TARGET_FORMS test.
- docstring/comment in mock_patch.rs:42-45 enumerates seven defensive conditions (decorator-only, no body machinery, dunder kept, opaque forms kept, owner-name overlap kept, missing source kept, test methods kept, non-self-contained imports kept). The unit tests cover each, but the integration path through build_behavior_item -> static_limit_for_focused_change is only exercised by the single end-to-end test in mock_patch_tests.rs ('given_related_test_with_disjoint_patch_then_mocked_module_limit_is_dropped'). Repo-mode behavior is therefore under-covered relative to classifier-mode.
- The changelog fragment (
changelog.d/python-mock-patch-unrelated-target.md) anddocs/specs/RIPR-SPEC-0028-python-preview-static-facts.mdagree on scope, but the spec still classifiesmocked_moduleby patched-helper list rather than the four new opaque-form spellings (patch.dict,monkeypatch.setitem,monkeypatch.delattr, computed/object targets). Doc nit, not a code defect.
Verification questions
- Confirm @patch('os.getcwd', side_effect=...) parses target successfully; literal_target only checks the slice after the first arg ends (',' or ')'), so the trailing kwargs are ignored and the decorator still counts as disjoint.
- Confirm end-to-end
given_related_test_with_disjoint_patch_then_mocked_module_limit_is_droppedasserts both directions (None vs MockedModule) including owner-source absent keeps prior limit; the single positive is the spec's accepted example.
Refuted
- helper shape is too granular (mock_sites_are_disjoint_from_owner) and should live on PythonTest to avoid cross-module coupling.; refuted because: The function depends on owner + owner_source, not just test data; placing it on PythonTest would leak owner context into the test struct and broaden that type's contract. Module-private free function is the smaller API surface.
Evidence gaps
- The packet lacks the scheduled late cargo-test receipt, so the PR body's exact focused-test result remains unverified in this review context.
- Model proof intent was rejected by deterministic validation.
Parked follow-ups
- No compile-time invariant pins
decorator_texts != default; a future site omitting it silently Vec::new()s and fails closed (defense-in-depth but not invariant). PR-confirmed rollback note: test_has_mocked_module itself unchanged, so regression safety rests on this surface. - crates/ripr/src/analysis/language/python/mock_patch.rs:75 — SELF_CONTAINED_IMPORTS hardcodes 14 stdlib names; the docstring/CLAUDE.md acceptance only requires 'short list of self-contained standard-library modules', but adding a new self-contained module (e.g. 'pathlib', 'datetime' in pure-functional use) requires changing this constant and a test. No sibling import check guards the list.
- Ripple-through requires both
is_patch_decorator_namecandidates anddecorator_sitesto match; any future test-building site that constructs aPythonTestwithoutdecorator_texts(silently empty Vec) loses the readable-arguments safety net: a decorator may namepatchyet contribute zero sites to the scan and thepatch_decorators > decorator_sitesguard returns false. Addingdecorator_texts: Vec::new()defaults in sixpython_tests.rs/owners_tests.rsliterals is mechanical but is not a compile-time invariant. CarryingMockPatchSurfaceor a typed builder would prevent this. - Seeded Steven review point #2 (class-level @patch) is structurally out of scope and the code fails closed: collect_tests_from_statements only retains decorators on the method's function, methods have qualified_name != name via the early gate in mock_sites_are_disjoint_from_owner, and a tested case pins it. Defense-in-depth, not invariant.
Requested by Steven Zimmerman · project thread
Summary
test_has_mocked_modulemarked any related, oracle-using Python test containingpatch/patch.object/patch.multiple/mock.patch(/monkeypatch.setattr(... as themocked_modulestatic limit (verdictstatic_unknown), whatever was patched. This narrows it, fail closed, for one shape: a string-literal dotted target none of whose segments the owner's file uses.python/mock_patch.rsdecides by name only. Every mock site in the test must be apatch(/mock.patch(/mocker.patch(/monkeypatch.setattr(call whose first argument (ortarget=) is a single-line, unprefixed, non-concatenated"a.b"literal with at least two identifier segments, and no segment may equal any identifier token of the owner's source file, the owner's name/class path/callees/imports/re-exporting modules, or the owner module's file stem (package name for__init__.py).patch.dictis an opaque form and keeps the limit.PythonTestgainsdecorator_texts(source text of each decorator).static_limit_for_focused_changefrom the check path (classify.rs) and from repo mode (repo/evidence.rs) so both agree. Without owner source the limit is kept.Swarm / Source Boundary
ripr-swarmSource-of-truth Links
Spec: RIPR-SPEC-0028 (Python static limits); prior art #4565 / #4612 (patch.object, patch.multiple)
Governing issue or accepted claim: #9098 (related: #6344)
Acceptance delta (one sentence): a related test that patches only names the owner's file never mentions no longer forces
mocked_module.Equivalent-change search: open/closed PRs and issues for
mocked_module,patch targetandstatic_unknownshowed only the original limit (#641, #828, #2272, #4565/#4612); no PR narrows it by target.Candidate Relationships
Candidate branch:
claude/py-narrow-mock-patch-limit. Stack parent / replacement: none.Scope
mock_patch.rs,static_limits.rs,classify.rs,repo/evidence.rs,owners_tests.rs,python.rs(field + module).mock_patch_tests.rs; test literals updated for the new field.Scope Classification
Production delta:
mocked_moduleis skipped when every mock site is a literal dotted target disjoint from the owner's names.Evidence/support delta: unit/integration tests (positive, discriminating negatives incl.
patch.dict, end-to-end throughstatic_limit_for_focused_change).Single acceptance criterion:
@patch("os.getcwd")against an owner not usingos/getcwdis notmocked_module; every ambiguous shape still is.Non-goals: TypeScript,
admission.rs, miss-reason producers (#5491/#5495), class-level@patch, runtime resolution.Support-tier Impact
Policy Impact
Proof
Not run locally: full
cargo xtask fixtures/goldens check(offline sandbox); hosted CI is the exact-head proof. No new fixture: both existing fixtures patchsrc.service.remote_totalagainst owner moduleservice, so they correctly stay limited.Claim Boundary
May claim: a purely name-disjoint literal patch target no longer limits a finding.
Must not claim: that no substitution can reach the owner. Residual, by design: a patched name reached only through another file's code (the owner calls a callee in a different module that itself uses the patched name, or inherits from a base class in another file) is invisible to a name check.
Rollback
Revert this PR;
test_has_mocked_moduleitself is unchanged.Spec-Test-Code Traceability
crates/ripr/src/analysis/language/python/mock_patch_tests.rscrates/ripr/src/analysis/language/python/mock_patch.rsStatic Language Check
killed,survived,untested,proven, andadequate.CI Economics
n/a
Engineering Check
panic,unwrap,expect,todo, orunimplementedin production code.panic,unwrap,expect,todo, orunimplementedin tests.Generated by Claude Code