Skip to content

fix(python): relate a test to an owner only when the test references it - #3980

Merged
EffortlessSteven merged 4 commits into
mainfrom
claude/language-quality-kairya-py-related
Sep 24, 2026
Merged

EffortlessSteven merged 4 commits into
mainfrom
claude/language-quality-kairya-py-related

Conversation

@claude

@claude claude Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Steven · project thread

Summary

Before: in a flat layout (pricing.py at the root, tests/test_pricing.py), a PR changes discounted_total and adds a new loyalty_price that no test calls. loyalty_price was reported as weakly_exposed with reach weak: 2 heuristic Python test link(s), listing the discounted_total tests, which never mention loyalty_price. The package layout (pricing/__init__.py) said no_static_path only because the stem __init__ did not match.

After: every loyalty_price line reads no_static_path with 0 related Python test(s) and No Python test references \loyalty_price(`. discounted_totalstaysexposedwith its 2 direct tests. A test that callsloyalty_price is related and exposed. A test that references it without calling it (p.loyalty_price, an import-renamed lp, handler = loyalty_price`) keeps a weak heuristic link. The flat and package layouts now agree.

How: related_test_relation in analysis/language/python/related_tests.rs now requires test_references_owner before 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:

  • the bare name outside comments, strings and docstrings, unless it is a keyword-argument or assignment target, or a local shadows it (a parameter or fixture, an assignment, :=, a for target, an as target, a nested def or class);
  • an import-renamed local from the owner module;
  • a member reached through an import of the owner module;
  • .name for method owners, and the class for dunder methods;
  • an imported local for module owners.

Findings move to the existing no_static_path branch. No new class was added.

Found while fixing the TypeScript twin for the onboarding re-walk (F5-9).

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 (rule text and a fixture-evidence bullet)
Issue: none filed. This is the Python follow-up named in #3977.

Scope Classification

  • One production behavior

Single acceptance criterion:

  • A Python test that does not reference an owner is not related to it by file stem, test name or fixture name.

Decisions (overrule on review)

  • Heuristic fixtures keep their family. python_same_stem_test, python_related_test_name_similarity and python_fixture_name_relation now reference their owner without a call. They stay weakly_exposed with the same relation, so the heuristic_only_no_packet_eval row stays honest.
  • Two fixtures re-blessed. python_dynamic_route_registration_limit and python_adversarial_changed_sink_non_delta_operand had same-stem tests that never reference their owners. Reach moves from weak to no, and both stay static_unknown. Their SPEC.md files say so.
  • Method owners accept any .name attribute reference. This matches the direct rule, which already relates any .name( call for them.

Support-tier Impact

  • none. This is Python preview classification.

Policy Impact

  • none. The flip is weakly_exposed to no_static_path, advisory to advisory.

Proof

At 35d52c1:

cargo test -p ripr --lib -- python                 # 383 passed
cargo xtask goldens check                          # 0 drift
cargo clippy -p ripr --all-targets -- -D warnings  # pass
cargo xtask check-spec-format                      # pass
cargo xtask precommit                              # pass

Additionally at b7cdbb8: fixtures, check-fixture-contracts, check-evidence-promotion-honesty, check-python-judged-panel and check-traceability passed, and cargo test -p xtask -- python_real_repo_eval honesty gave 18 passed.

Not established:

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

  • Spec: RIPR-SPEC-0028
  • Tests: analysis/language/python/tests.rs, python_tests.rs, repo/evidence.rs
  • Code: analysis/language/python/related_tests.rs
  • Golden outputs: listed above

Static Language Check

  • Static output avoids killed, survived, untested, proven, and adequate.

CI Economics

n/a

Engineering Check

  • No new panic, unwrap, expect, todo, or unimplemented in production code or tests.

🤖 Generated with Claude Code

https://claude.ai/code/session_018QP9k41E538Xgytw8QCSfM

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
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: f8cc85cb-fb6b-4a88-b7ec-70bb516a131c

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

❤️ Share

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

@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

  • 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 with staticmethod) would silently fall through to the bare-name branch. Either enumerate owner kinds at the top of test_references_owner or 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 := ...)) or for 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 relate loyalty_price to 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 = expr is 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
@claude

claude Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Disposition for the ub-review of b7cdbb8. One fix was pushed in 35d52c1.

  • Walrus shadowing: fixed. The finding was right, and the PR body's "fails closed" was wrong for walrus: (loyalty_price := ...) counted as a reference, which gave a weak heuristic link. test_binds_local now also treats name :=, for name in and as name (with, except, an in-body import) as shadowing locals. The new test walrus_loop_and_as_targets_shadow_the_owner_name covers all three, plus a control where a bare handler = loyalty_price still relates. It fails at b7cdbb8 and passes at 35d52c1. RIPR-SPEC-0028 lists the new binding forms. Python lib tests: 383 passed. goldens check, clippy and precommit pass.
  • Foreign receiver not pinned. It is pinned: owner_names_in_titles_fixtures_comments_strings_and_foreign_members_are_not_references asserts that order.loyalty_price and b.loyalty_price (via import billing as b) do not relate. The spec's closing sentence says the same.
  • Owner-kind fall-through. OwnerKind is a closed enum (domain/language.rs:91). For Python, only Method and ClassMethod take the attribute path. Everything else is a module-level symbol (function, class or module function), for which the bare-name, renamed-import and module-member path is the correct test. A new kind would be a new enum variant and would be reviewed where matches! sits. No change.
  • O(n·m) triple-quote scan. Accepted as is. It runs only on heuristic candidates, after direct relations fail, over one test body at a time.
  • python_same_stem_test stimulus edit. It was intended. Its SPEC.md now says the test references the owner without a syntactic call, which is the only way that family can exist under this rule.

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
@EffortlessSteven
EffortlessSteven marked this pull request as ready for review September 24, 2026 08:11
@EffortlessSteven

Copy link
Copy Markdown
Member

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 import_source_module_matches_owner, broadened in the intended direction), #4002 (no-default-base envelope) and #4022 (stale-golden rebless).

Proof at 8f59084: cargo xtask goldens check exit 0 (zero drift, combined tree); cargo test -p ripr --lib python 390 passed / 0 failed; cargo fmt --check pass. The two known stale goldens (python_src_layout_package_import, tail_comparison_boundary) are already repaired on main by #4022 and pass here — not reblessed in this PR.

Bot ub-review dispositions (walrus shadowing fix, foreign-receiver pin, owner-kind fall-through) were re-verified against the merged head; reviewThreads: none open.

@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

  • 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_reference calls inside_triple_quoted_string for every match_indices candidate. 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_owner has no OwnerKind::Class (non-dunder) arm. The current fall-through reuses test_references_module_symbol keyed on the class name, so a test that only instantiates Account(...) (no bare Account name) 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_string walks the body once per match_indices call inside contains_name_reference and contains_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; no Vec growth, no Box, no crypto, no JS/WASM paths. The inside_triple_quoted_string returns a bool, 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.

@EffortlessSteven
EffortlessSteven merged commit d05160e into main Sep 24, 2026
24 of 25 checks passed
@EffortlessSteven
EffortlessSteven deleted the claude/language-quality-kairya-py-related branch September 24, 2026 09:54
EffortlessSteven added a commit that referenced this pull request Sep 24, 2026
…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).
EffortlessSteven added a commit that referenced this pull request Sep 24, 2026
…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>
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