Skip to content

Preserve non-null type variables through wildcard capture - #1837

Merged
msridhar merged 4 commits into
masterfrom
issue-1823
Sep 15, 2026
Merged

msridhar merged 4 commits into
masterfrom
issue-1823

Conversation

@msridhar

@msridhar msridhar commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

When javac substitutes a member type through a captured wildcard, NullAway
restores nullness annotations from the unsubstituted type. That restoration
could replace an explicit @NonNull on a type-variable use with the nullable
implicit upper bound of the corresponding formal type variable. As a result,
sound calls through holders using unbounded, upper-bounded, or lower-bounded
wildcards could produce false-positive nullable-argument diagnostics.

Restore wildcard upper-bound annotations for both wildcard and non-wildcard
counterparts, and handle lower-bounded wildcards alongside unbounded ones.
When an implicit bound must change, create detached wildcard and type-variable
objects instead of mutating javac's shared bounds. Keep the existing cycle
guard for recursive F-bounds and generalize it to all implicit wildcard
bounds.

Also make explicit nullness annotations on formal upper bounds take precedence
over synthetic nullability inferred from library models or unmarked code. This
keeps an explicit @NonNull from being overwritten while retaining the
existing behavior when no explicit annotation is present.

Add regression coverage based on the Caffeine reproducer for explicit type
arguments, extends wildcards, unbounded wildcards, nullable upper bounds, and
super wildcards. Cover inherited members as well, interleaving explicitly
non-null and plain type-variable returns to verify that annotation restoration
does not mutate bounds shared by later member lookups.

Fixes #1823

Assisted-by: Codex (gpt-5)

Summary by CodeRabbit

  • Bug Fixes

    • Improved nullability handling for wildcard type bounds, including explicit non-null and nullable annotations.
    • Restored wildcard upper-bound nullability more consistently during type substitution, including lower-bounded wildcards.
    • Prevented inherited non-null members from incorrectly affecting the nullability of sibling members.
  • Tests

    • Added regression coverage for non-null type-variable returns through wildcard captures.
    • Added coverage confirming that inherited member nullability does not alter unrelated sibling members.

@msridhar

msridhar commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

This change is part of the following stack:

Change managed by git-spice.

@coderabbitai

coderabbitai Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 5a1ae426-b060-4c3a-a1f0-c770f61315ca

📥 Commits

Reviewing files that changed from the base of the PR and between 755c6a8 and 7c3ead0.

📒 Files selected for processing (1)
  • nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.


Walkthrough

The change preserves explicit nullness annotations on wildcard upper bounds. It restores annotations for unbounded and super wildcards during type substitution. Captured types now rebuild detached type-variable bounds when required. New JSpecify tests cover direct and nested non-null type-variable accesses and verify nullable sibling members.

Suggested reviewers: lazaroclapp

Priority: ⚪ Pending latest changes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 5e341

This change preserves explicit nullness through wildcard captures and adds regression coverage for the affected cases; no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preserving non-null type variables during wildcard capture.
Description check ✅ Passed The description directly explains the wildcard-capture bug, the implementation changes, and the regression tests.
Linked Issues check ✅ Passed Issue #1823 requires explicit @NonNull annotations on type-variable uses to survive wildcard capture for direct returns and nested map values. The PR restores wildcard upper-bound annotations, handles…
Out of Scope Changes check ✅ Passed The reviewed changes are limited to generic nullness restoration, wildcard-bound handling, and regression tests for issue #1823. The helper changes prevent shared javac types from being mutated and pr…
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-1823

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.

@msridhar
msridhar marked this pull request as draft September 9, 2026 18:06
@codecov

codecov Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.41176% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.69%. Comparing base (fb578f7) to head (5e341d7).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
.../uber/nullaway/generics/TypeSubstitutionUtils.java 77.41% 2 Missing and 5 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1837      +/-   ##
============================================
- Coverage     87.72%   87.69%   -0.03%     
- Complexity     3449     3453       +4     
============================================
  Files           110      110              
  Lines         11467    11485      +18     
  Branches       2352     2359       +7     
============================================
+ Hits          10059    10072      +13     
- Misses          650      652       +2     
- Partials        758      761       +3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@msridhar
msridhar requested a review from lazaroclapp September 9, 2026 21:30
@msridhar
msridhar marked this pull request as ready for review September 9, 2026 21:30
msridhar and others added 4 commits September 14, 2026 16:49
When javac substitutes a member type through a captured wildcard, NullAway
restores nullness annotations from the unsubstituted type. That restoration
could replace an explicit `@NonNull` on a type-variable use with the nullable
implicit upper bound of the corresponding formal type variable. As a result,
sound calls through holders using unbounded, upper-bounded, or lower-bounded
wildcards could produce false-positive nullable-argument diagnostics.

Restore wildcard upper-bound annotations for both wildcard and non-wildcard
counterparts, and handle lower-bounded wildcards alongside unbounded ones.
When an implicit bound must change, create detached wildcard and type-variable
objects instead of mutating javac's shared bounds. Keep the existing cycle
guard for recursive F-bounds and generalize it to all implicit wildcard
bounds.

Also make explicit nullness annotations on formal upper bounds take precedence
over synthetic nullability inferred from library models or unmarked code. This
keeps an explicit `@NonNull` from being overwritten while retaining the
existing behavior when no explicit annotation is present.

Add regression coverage based on the Caffeine reproducer for explicit type
arguments, extends wildcards, unbounded wildcards, nullable upper bounds, and
super wildcards. Cover inherited members as well, interleaving explicitly
non-null and plain type-variable returns to verify that annotation restoration
does not mutate bounds shared by later member lookups.

Fixes #1823

Assisted-by: Codex (gpt-5)
…s.java

Co-authored-by: Lázaro Clapp <lazaro@uber.com>
@msridhar
msridhar enabled auto-merge (squash) September 14, 2026 23:50
@msridhar
msridhar merged commit bf4cbcd into master Sep 15, 2026
16 checks passed
@msridhar
msridhar deleted the issue-1823 branch September 15, 2026 00:01
vlsi added a commit to vlsi/NullAway that referenced this pull request Sep 15, 2026
nonNullTypeVariableThroughWildcardCapture checked five type arguments in
one test. It is now one test per type argument, with the same sources and
expectations, so a failing test names the wildcard that broke.

apache#1837 also fixed a false negative without a test: for
`interface Holder<V> { List<@nullable V> list(); }`,
`takesNonNull(holder.list().get(0))` through `Holder<?>`,
`Holder<? extends Object>`, or `Holder<? super String>` was not reported.
nullableTypeVariableInTypeArgumentThroughWildcardCaptureStaysNullable
covers it.

Assisted-by: Claude Code (claude-opus-5)
vlsi added a commit to vlsi/NullAway that referenced this pull request Sep 15, 2026
`TypeMetadataBuilder.createWildcardType` built its copy without the `bound`
field of the original wildcard. That field holds the formal type variable
whose upper bound is the implicit upper bound of an unbounded or `super`
wildcard. Since apache#1837, `RestoreNullnessAnnotationsVisitor.visitWildcardType`
restores annotations onto both bounds of a `super` wildcard. It first
replaces `bound` with a type variable that carries the restored upper bound,
and then restores the lower bound through `createWildcardType`, which
dropped that type variable. `GenericsUtils.wildcardUpperBound` then found no
`bound` and returned `Object`, losing a restored `@Nullable` upper bound.
Existing tests such as `WildcardTests.wildcardSuperBoundsAndInference` reach
this path; I found no diagnostic that changes because of it.
`AddAnnotationToNestedTypeVisitor` dropped `bound` the same way when a
library model annotates the lower bound of a `super` wildcard.

`createWildcardType` now copies `bound` in both the JDK 17 and the JDK 21
implementation, so every caller keeps it.

This also adds tests for the behavior apache#1837 introduced, one test per
wildcard, so a failing test names the wildcard that broke. The
`plainTypeVariableThrough<Wildcard>StaysNullable` tests check that an
unannotated `V` read through `Holder<?>`, `Holder<? extends @nullable
Object>`, or `Holder<? super String>` is still reported as nullable, both as
a return value and inside `ConcurrentMap<String, V>`, after `@NonNull V`
members of the same holder were read; the test apache#1837 added expects no
diagnostic at all. The `nonNullTypeVariableThrough<Wildcard>InEnhancedFor`
tests cover a false positive that apache#1837 fixed without a test: an enhanced
`for` over `ConcurrentMap<String, @nonnull V>.values()` through each of the
three wildcards.

The comment in `GenericsUtils.wildcardUpperBound` called the annotation
check on the upper bound "explicit". `Nullness` matches nullness annotations
by name suffix, so the synthetic annotations NullAway adds count too; the
comment and the variable name now say so.

Assisted-by: Claude Code (claude-opus-5)
vlsi added a commit to vlsi/NullAway that referenced this pull request Sep 15, 2026
nonNullTypeVariableThroughWildcardCapture checked five type arguments in
one test. It is now one test per type argument, with the same sources and
expectations, so a failing test names the wildcard that broke.

apache#1837 also fixed a false negative without a test: for
`interface Holder<V> { List<@nullable V> list(); }`,
`takesNonNull(holder.list().get(0))` through `Holder<?>`,
`Holder<? extends Object>`, or `Holder<? super String>` was not reported.
The `nullableTypeVariableInTypeArgumentThrough<Wildcard>StaysNullable`
tests cover it, one per wildcard.

Assisted-by: Claude Code (claude-opus-5)
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.

Preserve @NonNull on type variables through wildcard capture

2 participants