Repository navigation
fix(python): relate a test to an owner only when the test references it - #3980
Conversation
A same-stem test file, a test name, or a fixture name no longer relates a Python test to an owner it never references. In a flat layout (`pricing.py` at the root, `tests/test_pricing.py`) the new, unreferenced `loyalty_price` read `weakly_exposed` with "2 heuristic Python test link(s)" that only call the sibling `discounted_total`; it now reads `no_static_path` with `No Python test references \`loyalty_price(\``, matching the package layout. The heuristics still rank a test that references the owner without a recognized call shape: the bare name outside comments, strings, docstrings, keyword-argument and assignment targets (unless a local shadows it); a renamed import local from the owner module; or a member through an import of the owner module (`pricing.loyalty_price`, `p.loyalty_price`). Method owners need a `.name` attribute reference, dunder methods also accept a reference to their class, and module owners need a local imported from the owner module. Arbitrary object-member uses stay unrelated for free-function owners. `python_same_stem_test`, `python_related_test_name_similarity` and `python_fixture_name_relation` now reference their owner so they keep pinning the heuristic families. The same-stem tests in `python_dynamic_route_registration_limit` and `python_adversarial_changed_sink_non_delta_operand` never reference their owners, so reach moves from weak to no and both stay `static_unknown`. The new `python_same_stem_sibling_owner_not_related` fixture pins the flat-layout case. All are re-blessed under RIPR-SPEC-0028. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018QP9k41E538Xgytw8QCSfM
|
Important Review skippedBot user detected. To trigger a single review, invoke the ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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 |
There was a problem hiding this comment.
Confirmed findings
- Spec must-not list does not enumerate the foreign-receiver attribute case for free-function owners; rule text covers it (order.loyalty_price is not a reference) but no fixture pins it.
- crates/ripr/src/analysis/language/python/related_tests.rs:810 — Asymmetric owner-kind handling: module-symbol path requires both bare-name and module-member; method path requires only
.attr; dunder path requires class-name. A future owner kind (e.g. class withstaticmethod) would silently fall through to the bare-name branch. Either enumerate owner kinds at the top oftest_references_owneror add a default-return-false branch with a debug_assert. - Helper module grows a second string-scanning helper (
inside_triple_quoted_string) that walks the body once per match_indices iteration; on large test files with many identifiers this is O(n*m). Architecture lane concern only; no perf regression shown. - No JavaScript/WASM/ArrayBuffer/TypedArray/resize/detach/transfer code path is touched by this PR; ub-active-view scope is empty for this diff class.
- crates/ripr/src/analysis/language/python/related_tests.rs:858 — test_binds_local does not enumerate walrus (
(loyalty_price := ...)) orfor loyalty_price in ...targets; spec claims walrus shadowing fails closed to unrelated but there is no test pinning it. Add a small negative control asserting that(loyalty_price := 3)inside a same-stem test still does not relateloyalty_priceto satisfy the spec/test-code traceability.
Verification questions
- Confirm contains_name_reference uses byte-level match_indices; backslash-continued lines or escaped string fragments could mis-bound; also the check is run before is_binding_target so
name = expris filtered, but walrus(name:=expr)is not, which spec lists as unsupported and fail-closed. - Confirm fixture python_same_stem_test SPEC still describes the case as 'same-stem pytest file references the changed owner ... without a syntactic call' and the input test was mutated to add
handler = reconcile_total; this is a behavior-affecting fixture edit, not just a golden refresh, and the SPEC text under Given/Must Not now diverges from the prior invariant ('same-stem file exists without a syntactic call'). - Confirm test_references_owner correctly shadows owner-named fixtures and assignment targets: assignment_count plus nested-def/class detection plus fixture-name membership block bare-name matches from qualifying as references.
- Confirm the PR body states this is the Python twin of the TypeScript rule in #3977, but the TypeScript diff is not part of this PR and not visible in this context. Cross-language equivalence cannot be verified from the current diff.
Refuted
- JS-backed memory crossing worker / async / GC / detach / transfer boundaries is touched by this PR and needs a handoff review.; refuted because: The diff is the ripr Python preview analyzer's owner-reference gate and its fixture goldens. No JS or WASM surface exists; only Rust and Python static-analysis code change. ub-worker-handoff invariants do not apply.
- Changing related_test_relation to early-return None on !test_references_owner could leak a previously-kept SameStem/TestName/FixtureName reference whose body was freed or whose test borrow went out of scope before the call.; refuted because: related_test_relation only reads borrowed &PythonTest / &PythonOwner and the callers in this PR pass slice references owned by the caller stack; no owned data is dropped or transferred. The function cannot outlive its inputs.
Evidence gaps
- Model proof intent was rejected by deterministic validation.
A same-stem test that binds a local named after the owner with `:=`, `for ... in` or `as` no longer counts a bare use of that local as an owner reference. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018QP9k41E538Xgytw8QCSfM
|
Disposition for the ub-review of b7cdbb8. One fix was pushed in 35d52c1.
Generated by Claude Code |
Conflict resolution toward current main semantics (forward-only): - 5 fixture expected/CHANGELOG.md journals (python_adversarial_changed_sink_ non_delta_operand, python_dynamic_route_registration_limit, python_fixture_name_relation, python_related_test_name_similarity, python_same_stem_test): both sides appended a pending bless entry at EOF with the same '(2)' heading. Kept the PR's RIPR-SPEC-0028 entry as (2) (blessed 2026-09-23T11:16Z) and renumbered main's RIPR-SPEC-0084 no-default-base entry as (3) (landed in fd572c8, 2026-09-24T02:25Z), preserving the append-only journal chronology and the MD024 unique-heading scheme enforced by next_pending_heading. - Auto-merged and verified by inspection: check.json envelopes (main's base/base_revision null change) combined with PR findings changes; related_tests.rs (PR's test_references_owner gate + #3944's owner_module_paths src-layout broadening, which the gate reuses); tests.rs (both sides' tests present); RIPR-SPEC-0028 (both paragraphs); traceability.toml.
…or the no-default-base envelope The new fixture was blessed against this PR's base before #4002 (fd572c8) landed on main. cargo xtask goldens check on the merged tree showed exactly one drift: this fixture's check.json still carried the pre-#4002 envelope ("base": "origin/main", base_revision "origin/main"). input_identity and all findings were byte-identical. Re-blessed with the same RIPR-SPEC-0084 reason main used for the identical rebless in #4022's series. Proof on the merged tree (b2812a4 + this): - cargo xtask goldens check: exit 0, zero drift - cargo test -p ripr --lib python: 390 passed, 0 failed - cargo fmt --check: pass
|
Conflict repair against main (forward-only merge, no rebase/force-push), pushed as b2812a4 + 8f59084. Main since the branch point landed #3944 (src-layout owner-module paths — this gate reuses
Proof at 8f59084: Bot ub-review dispositions (walrus shadowing fix, foreign-receiver pin, owner-kind fall-through) were re-verified against the merged head; reviewThreads: none open. |
There was a problem hiding this comment.
Confirmed findings
- No pytest was executed (PR body). The 7 negative + positive controls cover the static gate end-to-end, but the static-limit interaction with pytest fixture name shadowing in the real adapter path is not exercised. Acceptable for advisory preview, but a reviewer running pytest --collect-only on the new fixture would close it.
- crates/ripr/src/analysis/language/python/related_tests.rs:1006 — is_binding_target treats any
=(not==/:=) at name end as a kwarg/assignment; a trailing# ... =comment fragment or a slice[loyalty_price:0]=... assignment to a subscript can mis-classify. Worst case: false negative → reachable test leaks as unrelated, conservative for safety but undermines the 'reference must exist' invariant the PR claims. - python_text_hides_code uses line_prefix_before + a per-occurrence walk into inside_triple_quoted_string that re-scans from byte 0 for every match_indices hit; on a 10k-line test with thousands of identifiers this is O(n*m) bytes scanned. Not a security regression, but the GitHub review summary flagged it as an architecture/perf concern only.
- crates/ripr/src/analysis/language/python/related_tests.rs:1018 —
contains_name_referencecallsinside_triple_quoted_stringfor everymatch_indicescandidate. On a body with M occurrences of the candidate name, this is O(N·M) over the byte length. Existing fixtures are tiny so it does not show up; consider memoizing the triple-quote open/close map or hoisting the helper to a single walk that yields(idx, hides_code)pairs. - crates/ripr/src/analysis/language/python/related_tests.rs:828 —
test_references_ownerhas noOwnerKind::Class(non-dunder) arm. The current fall-through reusestest_references_module_symbolkeyed on the class name, so a test that only instantiatesAccount(...)(no bareAccountname) will not relate to a Class owner. The spec text only covers function/class as a single symbol shape. Either add an explicit class arm (construction + attribute access by the owner class) or document the limitation in RIPR-SPEC-0028.
Verification questions
- Confirm owner-kind dispatch in test_references_owner is asymmetric: module-symbol path requires both bare-name and module-member fallbacks; method/class-method path requires only .attr; dunder path requires a class reference. A future OwnerKind (e.g., staticmethod on a class) would silently fall through to the bare-name branch. OwnerKind is a closed enum today, but the asymmetry should be enumerated explicitly to make future additions intentional.
- Confirm ownerKind handling in test_references_owner is asymmetric: Module -> test_references_owner_module (both bare-name and member); Function/Class -> bare-name branch only; Method/ClassMethod -> .attr branch; dunder -> .attr or class-name. A future owner kind (e.g., staticmethod) would silently fall through to the bare-name module-symbol branch.
- Confirm
inside_triple_quoted_stringwalks the body once permatch_indicescall insidecontains_name_referenceandcontains_attribute_reference. On large test bodies with many candidate identifiers, cost is O(n·m). Not exercised by the new tests (bodies are tiny).
Refuted
- Sibling helper that allocates or copies (
Box::from, vec resize, crypto round) was added in this PR and could fail under allocation pressure; refuted because: Diff in related_tests.rs adds only string-scan helpers over&str; noVecgrowth, noBox, no crypto, no JS/WASM paths. Theinside_triple_quoted_stringreturns abool, not an allocation. UB framing does not apply. - The new triple-quote scanner (inside_triple_quoted_string) walks the body once per match_indices iteration and could hold a long-lived borrow that outlives the test.body_text String.; refuted because: inside_triple_quoted_string takes body_text: &str and only returns bool; the borrow of the open delimiter (&str) is dropped on each loop iteration, and the returned bool does not borrow from the input. No lifetime extension.
- A free-function owner named with a dot (e.g., 'module.func') would be misclassified by is_dotted_python_identifier.; refuted because: is_dotted_python_identifier rejects non-identifier segments and would treat such an owner name as not a dotted identifier, causing contains_name_reference / contains_member_reference to return false. python_callee_start_has_boundary and the matching on bare names short-circuit cleanly; no spurious relation, no false-positive route. Owner names emitted by extract_owners match Python identifier rules, so this is a closed-surface guard rather than a real route.
Evidence gaps
- Model proof intent was rejected by deterministic validation.
…e (RIPR-SPEC-0028) The #3980 python_same_stem_sibling_owner_not_related fixture landed on main after this branch's last main merge, so the merge-ref run combines its flat-layout fixture with this PR's boundary rule. The two tests call discounted_total(5000) and discounted_total(20000), which take the same branch on both sides of the amount >= DISCOUNT_THRESHOLD change and never sit on the amount == 10000 boundary where > and >= disagree, so the strong exact-value oracle reaches the owner but does not observe the changed comparison and the finding honestly fails closed to weakly_exposed (infect/discriminate weak, confidence 0.6 -> 0.4). loyalty_price stays no_static_path (4 findings unchanged). The boundary literal is an unresolved module constant, so the recommendation fields stay empty rather than inventing a boundary value, and the downgrade carries the direct-aligned strengthen_existing_test repair card. Local proof at merge 20d8da3 (origin/main 5901c0c + afe0ccd): goldens check passes; cargo fmt --check clean; predicate_boundary 14 passed; same_stem 11 passed (incl. #3980 mirrors).
…t at the boundary (#3955) * fix(python): require boundary evidence before crediting exposed on relational predicates A changed Python relational predicate (`qty > item.on_hand` -> `qty >= item.on_hand`) was reported `exposed` whenever a strong exact-value oracle reached the owner, even when the only test called it far from the boundary (`reserve(Item("a", 10), 3) == 7`), which passes before and after the change. Mirror the Rust activation rule (classify/activation.rs missing_boundary_discriminator): once a strong related test calls the owner with a literal argument, `exposed` requires one such call to bind both comparison operands to equal values (literals, or owner parameters bound via positional, keyword, alias, method-after-self, or literal defaults). Otherwise the finding fails closed to `weakly_exposed`, infection reads weak, and a simple-operand boundary is named as the missing discriminator with the observed operand values. Unresolvable operands (attributes, computed expressions, comprehension locals, multi-comparison lines) never count as observed; computed boundaries are not named as typed repair targets. When no strong call binds any literal argument the oracle verdict stands (as Rust does for empty call_values) and exposed findings carry a named `boundary_activation_unresolved` limitation, keeping the judged-panel structlog construct-call row `exposed`. Literal owner-call arguments and observed boundary equalities now populate `observed_values` for predicate findings. Reblessed five Python fixtures whose only drift is that additive evidence; no classification moved. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018QP9k41E538Xgytw8QCSfM * fix(python): do not name a boundary repair target through an unresolved operand When an operand of the changed comparison is never bound by a strong related call (an attribute such as item.on_hand), the test input may sit on the boundary at runtime. The finding still fails closed to weakly_exposed, but the equality is no longer handed out as a missing discriminator, so no Python repair card asks for a test that may already exist. RIPR-SPEC-0028 states the rule. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018QP9k41E538Xgytw8QCSfM * docs(spec): record observed_values before the failure modes in RIPR-SPEC-0028 Rides the ub-review 'spec sentence order' nit the author parked for the next push: the observed_values sentence sat between two sentences about the unresolved case and read as its artifact. It now follows the rule statement directly; the unresolved-operand and no-literal-input cases follow in order. Meaning unchanged. * test(goldens): bless python_src_layout_package_import under the boundary rule (RIPR-SPEC-0028) * test(python): reconcile src-layout pins with the boundary rule (RIPR-SPEC-0028) The three src-layout unit tests asserted exposed for a strong exact-value oracle whose only call, bulk_discount(101), sits away from the changed quantity == 100 boundary, so the RIPR-SPEC-0028 boundary rule correctly downgrades them to weakly_exposed. Keep the #3944 import-discovery discriminators by pinning the oracle call to the boundary itself (bulk_discount(100) == 0.0, the input where > and >= disagree), and add src_layout_owner_called_off_boundary_does_not_credit_exposed asserting the 101 call fails closed to weakly_exposed with the named quantity == 100 boundary while the import identity stays direct. The boundary-downgraded python_src_layout_package_import finding now carries a direct-aligned repair card, so the repair-card corpus inventory pin moves from (2, 28, 11) to (3, 28, 11). * test(goldens): reconcile sibling-owner fixture under the boundary rule (RIPR-SPEC-0028) The #3980 python_same_stem_sibling_owner_not_related fixture landed on main after this branch's last main merge, so the merge-ref run combines its flat-layout fixture with this PR's boundary rule. The two tests call discounted_total(5000) and discounted_total(20000), which take the same branch on both sides of the amount >= DISCOUNT_THRESHOLD change and never sit on the amount == 10000 boundary where > and >= disagree, so the strong exact-value oracle reaches the owner but does not observe the changed comparison and the finding honestly fails closed to weakly_exposed (infect/discriminate weak, confidence 0.6 -> 0.4). loyalty_price stays no_static_path (4 findings unchanged). The boundary literal is an unresolved module constant, so the recommendation fields stay empty rather than inventing a boundary value, and the downgrade carries the direct-aligned strengthen_existing_test repair card. Local proof at merge 20d8da3 (origin/main 5901c0c + afe0ccd): goldens check passes; cargo fmt --check clean; predicate_boundary 14 passed; same_stem 11 passed (incl. #3980 mirrors). --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Steven Zimmerman, CPA <15812269+EffortlessSteven@users.noreply.github.com>
Requested by Steven · project thread
Summary
Before: in a flat layout (
pricing.pyat the root,tests/test_pricing.py), a PR changesdiscounted_totaland adds a newloyalty_pricethat no test calls.loyalty_pricewas reported asweakly_exposedwithreach weak: 2 heuristic Python test link(s), listing thediscounted_totaltests, which never mentionloyalty_price. The package layout (pricing/__init__.py) saidno_static_pathonly because the stem__init__did not match.After: every
loyalty_priceline readsno_static_pathwith0 related Python test(s)andNo Python test references \loyalty_price(`.discounted_totalstaysexposedwith its 2 direct tests. A test that callsloyalty_priceis related and exposed. A test that references it without calling it (p.loyalty_price, an import-renamedlp,handler = loyalty_price`) keeps a weak heuristic link. The flat and package layouts now agree.How:
related_test_relationinanalysis/language/python/related_tests.rsnow requirestest_references_ownerbefore the same-stem, test-name and fixture-name heuristics. Direct relations are checked first and are unchanged. This is the Python twin of the TypeScript rule in #3977. RIPR-SPEC-0028 defines what counts as a reference::=, afortarget, anastarget, a nesteddeforclass);.namefor method owners, and the class for dunder methods;Findings move to the existing
no_static_pathbranch. No new class was added.Found while fixing the TypeScript twin for the onboarding re-walk (F5-9).
Swarm / Source Boundary
ripr-swarmSource-of-truth Links
Spec: RIPR-SPEC-0028 (rule text and a fixture-evidence bullet)
Issue: none filed. This is the Python follow-up named in #3977.
Scope Classification
Single acceptance criterion:
Decisions (overrule on review)
python_same_stem_test,python_related_test_name_similarityandpython_fixture_name_relationnow reference their owner without a call. They stayweakly_exposedwith the same relation, so theheuristic_only_no_packet_evalrow stays honest.python_dynamic_route_registration_limitandpython_adversarial_changed_sink_non_delta_operandhad same-stem tests that never reference their owners. Reach moves from weak to no, and both staystatic_unknown. Their SPEC.md files say so..nameattribute reference. This matches the direct rule, which already relates any.name(call for them.Support-tier Impact
Policy Impact
weakly_exposedtono_static_path, advisory to advisory.Proof
At 35d52c1:
Additionally at b7cdbb8:
fixtures,check-fixture-contracts,check-evidence-promotion-honesty,check-python-judged-panelandcheck-traceabilitypassed, andcargo test -p xtask -- python_real_repo_eval honestygave 18 passed.forandasshadowing, with a control.repo::evidencetest fail.python_same_stem_sibling_owner_not_relatedpins the flat layout.python-judged-panel replaygives identical results with and without the gate: 3 replayed, 3 pre-existing synthetic mismatches, 8 not run. No judged row flipped.git merge-treeis clean against fix(python): link src-layout tests to their owner module #3944, fix(python): a changed comparison is exposed only when a test calls it at the boundary #3955 and fix(typescript): relate a test to an owner only when the test references it #3977.Not established:
import_source_module_matches_owner, which this gate reuses, in the intended direction.mod.Outer.Innermember paths.Claim Boundary
May claim: Python no longer relates a test to an owner it never references. Must not claim: Python relation is call-precise.
Rollback
Revert both commits. The goldens, fixture and spec text revert with them.
Spec-Test-Code Traceability
analysis/language/python/tests.rs,python_tests.rs,repo/evidence.rsanalysis/language/python/related_tests.rsStatic Language Check
killed,survived,untested,proven, andadequate.CI Economics
n/a
Engineering Check
panic,unwrap,expect,todo, orunimplementedin production code or tests.🤖 Generated with Claude Code
https://claude.ai/code/session_018QP9k41E538Xgytw8QCSfM