Skip to content

fix(python): narrow mocked_module to patches that can reach the owner - #9053

Closed
EffortlessSteven wants to merge 6 commits into
mainfrom
claude/py-narrow-mock-patch-limit
Closed

EffortlessSteven wants to merge 6 commits into
mainfrom
claude/py-narrow-mock-patch-limit

Conversation

@EffortlessSteven

@EffortlessSteven EffortlessSteven commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Requested by Steven Zimmerman · project thread

Summary

  • test_has_mocked_module marked any related, oracle-using Python test containing patch/patch.object/patch.multiple/mock.patch(/monkeypatch.setattr(... as the mocked_module static limit (verdict static_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.
  • New python/mock_patch.rs decides by name only. Every mock site in the test must be a patch( / mock.patch( / mocker.patch( / monkeypatch.setattr( call whose first argument (or target=) 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.dict is an opaque form and keeps the limit.
  • Decorator arguments were not retained (only names), so PythonTest gains decorator_texts (source text of each decorator).
  • The owner source is plumbed into static_limit_for_focused_change from 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

  • ordinary feature, analyzer, editor, docs, spec, fixture, badge, dependency, or repo-ops development for ripr-swarm

Source-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 target and static_unknown showed 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

  • Production: mock_patch.rs, static_limits.rs, classify.rs, repo/evidence.rs, owners_tests.rs, python.rs (field + module).
  • Tests: mock_patch_tests.rs; test literals updated for the new field.
  • Changelog fragment.

Scope Classification

  • One production behavior

Production delta: mocked_module is 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 through static_limit_for_focused_change).

Single acceptance criterion: @patch("os.getcwd") against an owner not using os/getcwd is not mocked_module; every ambiguous shape still is.

Non-goals: TypeScript, admission.rs, miss-reason producers (#5491/#5495), class-level @patch, runtime resolution.

Support-tier Impact

  • none

Policy Impact

  • none

Proof

cargo test -p ripr --lib analysis::language::python      # 747 passed, 0 failed (head 86623719)
cargo xtask precommit                                    # exit 0 (head 86623719)
cargo clippy -p ripr --all-targets -- -D warnings        # exit 0
cargo xtask fixtures python_mocked_module_limit          # exit 0
cargo xtask fixtures python_monkeypatch_module_limit     # exit 0

Not run locally: full cargo xtask fixtures / goldens check (offline sandbox); hosted CI is the exact-head proof. No new fixture: both existing fixtures patch src.service.remote_total against owner module service, 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_module itself is unchanged.

Spec-Test-Code Traceability

  • Spec: RIPR-SPEC-0028
  • Tests: crates/ripr/src/analysis/language/python/mock_patch_tests.rs
  • Code: crates/ripr/src/analysis/language/python/mock_patch.rs
  • Golden outputs: unchanged

Static Language Check

  • Static output avoids killed, survived, untested, proven, and adequate.
  • Unknowns include stop reasons where applicable.

CI Economics

n/a

Engineering Check

  • No new panic, unwrap, expect, todo, or unimplemented in production code.
  • No new panic, unwrap, expect, todo, or unimplemented in tests.
  • No new non-Rust programming files, generated, dependency, process or network surfaces.
  • Public JSON/schema unchanged.

Generated by Claude Code

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
@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@EffortlessSteven EffortlessSteven self-assigned this Oct 21, 2026
@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 78 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: 00a1b149-52a5-4b76-b6f3-7c86ac640ca6
📥 Commits

Reviewing files that changed from the base of the PR and between 96a2022 and f4af8e3.

📒 Files selected for processing: 11
  • changelog.d/python-mock-patch-unrelated-target.md
  • crates/ripr/src/analysis/language/python.rs
  • crates/ripr/src/analysis/language/python/assertion_selection_tests.rs
  • crates/ripr/src/analysis/language/python/classify.rs
  • crates/ripr/src/analysis/language/python/mock_patch.rs
  • crates/ripr/src/analysis/language/python/mock_patch_tests.rs
  • crates/ripr/src/analysis/language/python/owners_tests.rs
  • crates/ripr/src/analysis/language/python/python_tests.rs
  • crates/ripr/src/analysis/language/python/repo/evidence.rs
  • crates/ripr/src/analysis/language/python/static_limits.rs
  • docs/specs/RIPR-SPEC-0028-python-preview-static-facts.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

Comment on lines +37 to +42
const OPAQUE_FORMS: [&str; 4] = [
"patch.object(",
"patch.multiple(",
"monkeypatch.setitem(",
"monkeypatch.delattr(",
];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@github-actions github-actions Bot left a comment

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.

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.

Copy link
Copy Markdown
Member Author

Re the exit-101 note: on the current head 8662371, cargo test -p ripr --lib analysis::language::python exits 0 locally (747 passed, 0 failed), and cargo xtask precommit also exits 0. The failing run was most likely against the pre-fix head 5ac11aa, whose patch.dict case the follow-up commit fixed. If a run on 8662371 still exits 101, please attach the failing test name.

The b/r/u string-prefix gap in literal_target stays as is: those prefixes only make the target non-literal, which keeps the limit (fail-closed).


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Independent review (multi-angle): changes needed

  1. Blocking: false-actionable risk from the name-based disjointness check. mock_sites_are_disjoint_from_owner drops the mocked_module limit when no segment of the patch target appears among the owner file's own tokens/imports/callees. If the owner calls an imported helper that uses requests, and the test patches requests.get, the owner file never names requests, the limit is dropped, and a mocked strong assertion can read as exposed instead of static_unknown. The module doc calls this "Residual" but the changelog shows only the benign os.getcwd case. Per CLAUDE.md a wrong actionable signal is worse than missed advisories. Keep the limit when the owner has a non-builtin call into a workspace module unless provably unreachable, or restrict narrowing accordingly. Add a negative test for this shape.
  2. Class-level @patch is invisible. decorator_texts comes only from the function's decorators, so @patch("pkg.service.load") on the enclosing class plus a disjoint patch in the body drops the limit. Carry class decorators or fail closed.
  3. Spec/docs: RIPR-SPEC-0028 (~line 420) still defines mocked_module as any patch/patch.object/monkeypatch.setattr, with no update. The changelog should say what the finding becomes (classified from remaining evidence rather than static_unknown) and state the residual risk. Link new tests in .ripr/traceability.toml.
  4. Tests only cover static_limit_for_focused_change; nothing checks the resulting class/actionability change or repo mode (build_behavior_item now passes Some(source)). static_limit_for_change still passes None, so callers can disagree.
  5. Merge: adds a field to PythonTest and a parameter to static_limit_for_focused_change; feat(python): map related-test row evidence to typed RelatedTestMiss (#5491) #9055 touches classify.rs/row_miss_tests.rs and may need the field. Land before feat(python): map related-test row evidence to typed RelatedTestMiss (#5491) #9055 and re-run goldens check.

Generated by Claude Code

Copy link
Copy Markdown
Member Author

Review scope note: the review above was done against head 866237195aa1663db1ea38fec144fa9710d01efa. It is valid only for that head; a push or conflict resolution needs a fresh review.


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

@github-actions github-actions Bot left a comment

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.

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.

Copy link
Copy Markdown
Member Author

Closing without merge. An independent review of head f4af8e3 found two false-actionable holes that no further narrowing of this rule can close:

  1. The disjointness test only reads identifier tokens in the owner file. A test that passes values into the owner (duck-typed arguments or injected collaborators, e.g. total(Money(1), Money(2)) where Money.__add__ calls the patched shop.money.convert) reaches the patched name without the owner naming it.
  2. The "self-contained stdlib" allowlist does not hold: dataclasses.asdict reaches copy.deepcopy, fractions.Fraction reaches math.gcd, and similar.

Fixtures and conftest-supplied patches are also unscanned. Dropping mocked_module on these shapes would turn a conservative static_unknown into a wrong actionable signal, which the product contract treats as worse than missed advisories. #9098 stays open; the limit stays as is until a sound reach proof exists.


Generated by Claude Code

@github-actions github-actions Bot left a comment

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.

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) and docs/specs/RIPR-SPEC-0028-python-preview-static-facts.md agree on scope, but the spec still classifies mocked_module by 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_dropped asserts 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_name candidates and decorator_sites to match; any future test-building site that constructs a PythonTest without decorator_texts (silently empty Vec) loses the readable-arguments safety net: a decorator may name patch yet contribute zero sites to the scan and the patch_decorators > decorator_sites guard returns false. Adding decorator_texts: Vec::new() defaults in six python_tests.rs/owners_tests.rs literals is mechanical but is not a compile-time invariant. Carrying MockPatchSurface or 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants