Skip to content

fix(rust): credit an unwrapped Ok tail after early Err returns - #7940

Merged
EffortlessSteven merged 3 commits into
mainfrom
claude/project-thread-svy0f3
Oct 14, 2026
Merged

EffortlessSteven merged 3 commits into
mainfrom
claude/project-thread-svy0f3

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Summary

Before: ledger-receipt-remaining read as a false gap. Inventory::ship returns Ok(Receipt { .. }) after two early return Err(..) exits. Its test does let receipt = inv.ship(..).unwrap(); assert_eq!(receipt, Receipt { .., remaining: 7 }), and both runtime mutants are killed. RIPR-SPEC-0225 refused any owner containing return, and it never read .unwrap()/.expect(..) of the owner call as the wrapped payload.

After: that row reads credited. An early exit is admitted only when it returns the variant the tail does not build: return Err(..) beside an Ok(T { .. }) tail, and return None beside Some(T { .. }). That is the same thing ? already does, so every Ok/Some the owner returns is the tail literal. The test may compare owner(..).unwrap() or owner(..).expect("plain literal") with the bare literal T { .. }, either inline or through a once-used let. The expected value is then checked as Ok(T { .. })/Some(T { .. }) against every existing gate.

How:

  • whole_value_tail (owner_pin.rs) records any returns. It keeps the owner only when there is a wrapper, the AST return count equals the masked-text count, and every exit passes returns_other_variant.
  • WholeValueTail.early_exit names Err/None when there are early exits. Like the tail's Ok/Some, that constructor must not be rebound anywhere in the workspace (wrapper_may_be_rebound).
  • WholeValueField::admits reads an unwrapped_call operand on both the direct and the bound path (bound_owner_initializer), then rewraps the expected literal.

Swarm / Source Boundary

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

Source-of-truth Links

  • Proposal: none
  • Spec: RIPR-SPEC-0225 adds decision 6 (unwrapped Ok/Some tails and their early exits), extends example 3, and updates the implementation mapping.
  • ADR: none
  • Plan item: none
  • Governing issue or accepted claim: false-verdict cluster 3 (whole-value equality), row ledger-receipt-remaining, under rust: a field set in a hand-written Clone and checked by whole-value assert_eq reads weakly_exposed #6692.
  • Acceptance delta (one sentence): ledger-receipt-remaining moves from gap to credited, and no other Rust corpus row moves.

Candidate Relationships

Scope Classification

  • One production behavior: whole-value field credit for unwrapped Ok/Some owners with other-variant early exits.

Support-tier Impact

  • none

Proof

cargo xtask precommit                              # exit 0 on this head
cargo test -p ripr --lib owner_pin                 # 188 passed
cargo xtask verdict-corpus check --language rust   # 44/449 false, 0 contradictions; only ledger-receipt-remaining moved

New test: an_unwrapped_ok_tail_with_early_err_returns_pins_its_field.

  • Credits:
    • Ok(..);
    • .unwrap() in both operand orders;
    • .expect("parses");
    • a let-bound unwrap;
    • maybe(3).unwrap() beside return None.
  • Refuses:
    • unwrap compared with Ok(literal);
    • unwrap_or_default;
    • expect(&msg);
    • a bare literal without unwrap;
    • let mut;
    • an unwrapped bare-tail owner.
  • Early exits that refuse:
    • return Ok(..);
    • return parse(..);
    • return Err(..).or(..);
    • return Some(..);
    • return maybe(..);
    • return FALLBACK;
    • an Err rebound by fn Err or by use std::result::Result::Ok as Err.

Negative controls (each makes the test fail):

  • returns_other_variant always true;
  • the expect literal check removed;
  • the None path check loosened;
  • the Err/None rebinding check dropped.

The review of record is in the PR comments.

Claim Boundary

  • May claim: an early Err/None exit no longer blocks whole-value credit for an unwrapped owner call.
  • Must not claim: credit for any other early return, unwrap_or*, computed expect messages, or raw-string messages (these are conservative misses).

🤖 Generated with Claude Code

https://claude.ai/code/session_01U7GbrVC98fTYnLnhe3vhFM


Generated by Claude Code

A whole-value owner that returns `Ok(T { .. })` after an early
`return Err(..)` (or `Some(T { .. })` after `return None`) now gets the
same field credit as one that uses `?`, when the test compares
`owner(..).unwrap()` or `.expect("..")` with the bare literal. Other
early exits, a workspace-rebound `Err`/`None`, unwrap_or* and computed
expect messages still refuse (RIPR-SPEC-0225 decision 6, #6692).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U7GbrVC98fTYnLnhe3vhFM
@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: d4bcf398-bb7c-4173-8a14-b6c1f9400c1b
📥 Commits

Reviewing files that changed from the base of the PR and between 285b105 and aaf92a0.

📒 Files selected for processing: 3
  • crates/ripr/src/analysis/classify/owner_pin/tests.rs
  • fixtures/rust-verdict-corpus/spec-coverage.toml
  • xtask/src/reports/dx_scoreboard/population_tests.rs
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

Summary by CodeRabbit

  • New Features
    • Whole-value field comparisons can receive credit when a returned Result or Option has a success-value tail and early exits return only the opposite variant. Supported comparisons include unwrap() and eligible expect() calls, inline or through a once-used immutable binding.
  • Documentation
    • Updated the specification and changelog to describe accepted comparison patterns and their limits.
  • Tests
    • Added coverage for supported and rejected return paths and comparison patterns. Oracle accuracy expectations were updated.

Walkthrough

The owner-pin classifier now allows whole-value field credit for Ok or Some tails with qualifying opposite-variant early returns. It recognizes supported unwrap() and expect() comparisons. Regression tests and specification updates cover accepted and rejected forms.

Changes

Whole-value field credit

Layer / File(s) Summary
Qualify wrapped tails with early returns
crates/ripr/src/analysis/classify/owner_pin.rs
The classifier accepts Ok or Some tails with early returns only when each return constructs the opposite variant. It also checks whether variant names may be rebound.
Recognize unwrapped owner comparisons
crates/ripr/src/analysis/classify/owner_pin.rs
Whole-value pin matching recognizes supported direct or once-bound unwrap() and expect() owner calls. It reconstructs the corresponding wrapper for validation.
Cover and document the admission rules
crates/ripr/src/analysis/classify/owner_pin/tests.rs, docs/specs/RIPR-SPEC-0225-whole-value-equality-field-credit.md, .ripr/traceability.toml, changelog.d/6692-unwrapped-ok-tail-pins.md, fixtures/rust-verdict-corpus/expected/rows/ledger-receipt-remaining.json, fixtures/rust-verdict-corpus/spec-coverage.toml, xtask/src/reports/dx_scoreboard/population_tests.rs
Tests cover accepted and rejected return paths and comparison forms. The specification, traceability entry, changelog, expected corpus row, and oracle accuracy expectations record the updated behavior.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to aaf92

The known early-return alias path is guarded at the current head, and the supplied change context establishes no remaining actionable blocker. Mergeability risk is minimal.

Security architecture risk: 🔵 Low · up to 285b1

A narrow constructor-shadowing case may overstate what a test proves. The inspected change does not introduce broader runtime privileges or deployment exposure.

Retained concerns

  • Low · architecture · inferred: The new opposite-variant rule can infer constructor identity from spelling without rejecting owner-local callable bindings. For example, let Err = std::result::Result::Ok can make return Err(Config { .. }) return a successful value before the changed tail initializer. The field-specific establishment path bypasses the general owner binding guard, so an equality test of that early result may receive credit for a tail field it never evaluated. This is an inferred evidence-integrity defect, not a verified security vulnerability.
Security review details

Security Blast Radius

  • inferred — The supported exposure is the field-credit output derived from an analyzed workspace. The inspected path changes classification, not the analyzed program’s privileges or runtime state; broader tenant, credential, or deployment effects are not established.

Security Findings and Attack Paths

  • inferred — A contributor controlling analyzed owner source could potentially use a local Err callable binding to present an early successful result as an opposite-variant exit. This can undermine reported test evidence if credited, but no execution, privilege escalation, or downstream security-enforcement dependency was demonstrated.

Trust Boundaries and Controls

  • observed — Existing controls still require the declared wrapped return type and derived field equality, reject recognized constructor rebinding, and check expected wrapper declarations in the test’s source. These controls narrow admission but do not establish that the general owner binding guard covers the separately dispatched field path.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description provides a strong summary, scope, source-of-truth context, proof results, and claim boundary. It omits several template sections, including Scope, Support-tier Impact, Policy Impact, R… Add the missing template sections and complete each applicable item. Mark non-applicable sections explicitly, such as CI Economics: n/a, and record rollback, traceability, engineering checks, and gate results.
Passed Passed checks: 4 passed
Check name Status Explanation
Docstring Coverage Passed Docstring coverage is 90.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 3 files. (1 skipped: 1 …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely describes the main change: crediting an unwrapped Ok tail after early Err returns.
Full details: Description check

Explanation

The description provides a strong summary, scope, source-of-truth context, proof results, and claim boundary. It omits several template sections, including Scope, Support-tier Impact, Policy Impact, Rollback, Spec-Test-Code Traceability, Static Language Check, CI Economics, Engineering Check, and Gates.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

A rabbit checks each wrapped tail,
And marks the paths that pass the test.
Err and None may leave the trail,
While plain unwrap() confirms the rest.
New cases join the traceability line,
The burrow hums: the pins align.

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request implements RIPR-SPEC-0225 decision 6, which grants whole-value field credit to Rust owners returning Ok(T { .. }) or Some(T { .. }) despite early exits of the opposite variant (such as return Err(..) or return None). The analysis is updated to support tests comparing unwrapped values via .unwrap() or .expect("...") with bare literals, either inline or through a once-used local binding. The changes span classification logic in owner_pin.rs, spec documentation, unit tests, and fixture expectations. There are no review comments, and no additional feedback is provided.

coderabbitai[bot]

This comment was marked as resolved.

@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

  • WholeValueTail early_exit only feeds wrapper_may_be_rebound; equal-armed match of return expr for Option variants doesn't gate nested path-expr like None. (path tail). Unlikely but tightens with explicit PathExpr child check.

Verification questions

  • Confirm test exercises Err/None rebinding by fn Err and use Ok as Err, satisfying claim-bound must-not-claim; missing: rebinding through Err as a local variable/type/const path.

Refuted

  • An early 'return' that the masked-pass misses (inside "..." or //! comment) could let a non-Err/None exit survive returns_other_variant and credit a tail whose only Ok is not the literal.; refuted because: whole_value_tail parses the real source to rust-analyzer AST and collects ast::ReturnExpr from the parsed function body; the AST never contains tokens inside string literals or comments. The subsequent length check compares AST return count to whole_word_offsets(&masked, 'return') and requires equality; a masked-text-only 'return' makes masked count > AST count and returns None, refusing the pin.

Parked follow-ups

  • unwrapped_call rejects only " and \ inside the expect("...") message; \n/\t/\u{...} pass. Literal is still constant so panic semantics are preserved; spec text says 'plain string-literal message' without enumerating escapes.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

Covers the #7940 review gaps: a std-rooted `use .. as Err` inside the
owner, a rebound `None` beside a `Some` tail, and a positive control for
the early-`Err` literal fixture.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U7GbrVC98fTYnLnhe3vhFM
Main at a26f107 fails oracle_committed_rates_keep_labeled_and_unlabeled_cases
(rows give 40/41). Same two lines as #7932; they no-op once it lands.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U7GbrVC98fTYnLnhe3vhFM

Copy link
Copy Markdown
Member Author

Review of record

Head: aaf92a030462c197b24fb58a169ebc6271aaf21b on main a26f107.

Angles and findings

  1. Correctness / fail-open edges (independent agent, reviewed 42ad16a before squash).
    • Blocking, confirmed by execution: returns_other_variant trusted the text Err/None. A workspace fn Err(..) -> Result<..> { Ok(..) }, or use std::result::Result::Ok as Err;, let an early return Err(T{..}) hand back an Ok and still get credit.
      • Fixed: WholeValueTail.early_exit sends Err/None through wrapper_may_be_rebound, the same gate the tail's Ok/Some already uses.
    • Refused, read or run:
      • return Err(x)?, .into(), .or(..);
      • a return hidden in a macro (the masked count is higher than the AST count);
      • closures and nested fns;
      • .map(..).unwrap() and .unwrap().clone();
      • double expect;
      • escaped or raw expect messages (any \ refuses, which also answers the \n note);
      • an Ok vs Some mix-up.
    • Panic check: no panics on non-ASCII input.
  2. Tests, spec, contract parity (independent agent).
    • Nothing blocking.
    • Non-blocking test gaps, now covered:
      • the Some/return None arm (rows for return None, return Some(..), return maybe(..), return FALLBACK);
      • the rebinding paths.
    • All mapped names exist in the spec, and the corpus row's credit is correct: Inventory::ship has two return Err exits and an Ok(Receipt{..}) tail, the test unwraps it, and both runtime mutants are killed.
  3. Re-review of the exact fix and rebase (independent agent, reviewed 285b105).
    • Nothing blocking.
    • Rebind fix, refused by execution:
      • const/static Err;
      • a local enum { Err } glob import;
      • use crate::m::Err;
      • use dep::*;
      • a fn-local fn Err.
      • let Err = .. is not a real case: rustc rejects it (E0530).
    • Conflict resolution: correct. The rendered-scalar arm and the unwrapped arm are gated on disjoint ReturnPathGates.
    • Gaps, now covered: an in-test positive control and a None-side rebinding row.
  4. Bots.
    • CodeRabbit, owner-local std alias: already refused, because file_renames_to reads fn-local use .. as Err from any root. 85205f6 adds the row. The thread is answered and resolved.
    • Gemini: no findings.
    • ub-review:
      • "path tail like None.": return None.x is not a PathExpr, and None::<T> text is not None, so both refuse.
      • "local variable/type/const Err": const and type are covered by the keyword gate, and a local variable is E0530.

Negative controls (each fails the test)

  • returns_other_variant always true;
  • the expect-literal check removed;
  • the None path check loosened;
  • the Err/None rebinding chain dropped, run once with the Err rows and once with the None row isolated.

Proof

Disposition: nothing blocking. Ready for the required check.


Generated by Claude Code

@EffortlessSteven
EffortlessSteven marked this pull request as ready for review October 14, 2026 11:43

@devin-ai-integration devin-ai-integration 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.

Devin Review found 1 potential issue.

Devin Review

@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

  • Out-of-scope lane: ub-active-view concerns (ResizableBuffer/ArrayBuffer/TypedArray resize, detach, transfer, stale length snapshots) do not apply to a pure Rust static analyzer PR with no JS/WASM/FFI surface touched.

Refuted

  • An early return Err(..)/None could make owner(..).unwrap() read an active view backed by a partial/dead buffer (stale length, detached region).; refuted because: unwrap/expect panic on Err/None and yield the inner payload only on Ok/Some. returns_other_variant restricts early exits to the opposite variant and wrapper_may_be_rebound rejects any Err/None rebound (fn Err or use .. as Err), so the only values that flow into the unwrap are tail-literal Ok/Some. No resizable-buffer surface exists in this PR.
  • wrapped_expected rewrap could over-credit when unwrap_wrapper is None; refuted because: The (true, None) arm returns false, refusing credit; the (false, _) arm leaves expected unchanged. The rewrap is only constructed when a WholeValueField gate yielded Some(wrapper), so the unreachable rewrap branch never executes outside the admitted path.
  • returns_other_variant misses an Option return None<...> path-expr with trailing tokens (e.g., return None.unwrap_or(x)), letting a non-None exit slip through and credit an Option tail.; refuted because: In Option case, exit.expr() must be a PathExpr whose text equals exactly "None"; any trailing method call or qualifier renders path.syntax().text() != "None", so the early exit refuses. A nested return None.unwrap_or(..) therefore refuses outright rather than crediting — the inverse skip is the issue, not a credit leak.

Parked follow-ups

  • Parked opposition note: equal-armed match of return expr for Option variants doesn't gate nested path-expr like None. (path tail). Unlikely but could tighten with explicit PathExpr child check; out of memory-lifetime scope.
  • Parked: whether assert_eq!(owner(..).unwrap_or(default_with_field_x), T{..}) should ever credit when the default is the literal; out of decision 6 scope.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

@EffortlessSteven
EffortlessSteven merged commit 251e4e4 into main Oct 14, 2026
41 checks passed
@EffortlessSteven
EffortlessSteven deleted the claude/project-thread-svy0f3 branch October 14, 2026 12:51
EffortlessSteven pushed a commit that referenced this pull request Oct 14, 2026
Resolves owner_pin.rs beside #7940's unwrapped Ok tail: the projection
fallbacks stay on the rendered chain and unwrapped_direct follows it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019DhTE9QaZFAYeqtp9XRAGK
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