Skip to content

Infer inline generic method references from their argument targets - #2175

Open
msridhar wants to merge 31 commits into
masterfrom
fix-2063-inline-method-reference
Open

msridhar wants to merge 31 commits into
masterfrom
fix-2063-inline-method-reference

Conversation

@msridhar

@msridhar msridhar commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Infer omitted type-argument nullability before checking a generic method reference passed directly, or in parentheses, as an argument to a method or constructor whose corresponding parameter type is a functional interface. Cache the result and reuse it when resolving the referenced method type.

Fix both publisher reproducers in #2063, including parenthesized references and explicit enclosing-call type arguments. Include direct-argument coverage for static, bound, unbound, and varargs references, incompatible targets, and explicit reference type arguments.

To avoid reporting duplicate misleading errors in cases with multiple method references passed within the context of joint inference, change ConstraintSolverImpl to only report inference errors at the call to solve(), rather than eagerly during constraint generation. This way, all constraints for the joint inference get generated, and an inference failure gets associated with all relevant method references.

Generic calls whose parameter is a bare type variable, such as wrap(Test::id) or List.of(Test::id), remain follow-up work in #2176, alongside assignments, returns, conditionals, and lambdas that return a reference.

#2188 is a follow up that renames variables like allCalls to reflect the fact that method references may also be present.

Fixes #2063

Assisted-by: Codex (gpt-6)

Infer omitted type-argument nullability before checking a generic method reference passed to a method or constructor. Cache the result on the reference, preserve joint enclosing-call inference, and reuse it when resolving the referenced method type.

Fix both publisher reproducers in #2063, including parenthesized references and explicit enclosing-call type arguments. Include direct-argument coverage for static, bound, unbound, and varargs references, incompatible targets, and explicit reference type arguments.

Validation: the two extracted regression tests fail on master and pass with this change; :nullaway:test and :nullaway:buildWithNullAway pass. Diff-scoped PIT kills all 7 mutants.

Assisted-by: Codex (gpt-6)
@msridhar
msridhar requested a review from vlsi November 17, 2026 03:05
@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

Walkthrough

An inline generic method reference could report a nullability mismatch when passed as a functional-interface argument. The change includes dependent references in enclosing-call inference and infers omitted type arguments from target types. It caches results by reference. When inference warnings are enabled and a failure is reported, follow-up compatibility and override checks are skipped. Tests cover reference forms, warning settings, and joint inference.

Possibly related issues

  • uber/NullAway#2181 — The issue requests an additional receiver-substituted upper-bound check for method-reference inference. The PR adds inference but does not include that check.
  • uber/NullAway#2176 — The issue reports remaining failures for references in field initializers, assignments, returns, conditionals, and lambda results. The PR adds inference for call arguments, not these positions.

Severity of issue fixed: Medium

Merge Risk: Low · previous review ebdc5

Inline generic method references now infer omitted type-argument nullability from their targets. One narrow case remains: the receiver's type arguments are not applied to the method's type-parameter bounds, so a bound violation can be missed. This is tracked in #2181 and is low risk to merge.

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

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.75000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 89.64%. Comparing base (af5ba08) to head (899008c).

Files with missing lines Patch % Lines
...ava/com/uber/nullaway/generics/GenericsChecks.java 98.30% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #2175      +/-   ##
============================================
+ Coverage     89.58%   89.64%   +0.06%     
- Complexity     4031     4054      +23     
============================================
  Files           113      113              
  Lines         13208    13245      +37     
  Branches       2729     2736       +7     
============================================
+ Hits          11832    11874      +42     
+ Misses          621      619       -2     
+ Partials        755      752       -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.

@vlsi vlsi 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.

One thing blocks the merge for me: the description promises the fix for a generic method reference passed to any method or constructor, and one passed to a generic call such as List.of(Test::id) still gets the false positive (F1).

F6 and F7 are one change: state the contract of inferMethodReferenceTypeArguments in its Javadoc, and let okToCacheInferenceResult guard the cache write in place of the paragraph about its callers. The rest are small.

Reviewed at 8c40e57a.

vlsi added a commit to vlsi/qubership-ai-packages that referenced this pull request Nov 17, 2026
…d case that failed before the change

A case that a change's description, commit message, or closed issue claims to handle is a change finding however old
the code that breaks it, and a change finding had one remedy: handle the case. Where the case fails at the base too and
handling it needs a design decision or more code than the change, that remedy grows the change past its purpose. On
apache/nullaway#2175 the description claimed the fix for method references "passed to a method or constructor", the
review asked the author to add a condition for references passed to a generic call, and a follow-up issue already
tracked the same cause for assignments and returns.

origin.md now gives such a case two outcomes: handle it, or withdraw the claim. The proposed solution asks for the
handling where it meets the extend_scope conditions (a few lines in the files the change touches, no new decision).
Otherwise it asks to narrow the description or commit message, or to replace a closing link with one that leaves the
issue open, and names where the other cases go; the retest accepts either outcome. Where the narrowed claim would leave
the change without its purpose, as when the closed issue's own reproducer still fails, the handling is still asked
for. Step 1 now reads the base for a claimed case, since the remedy depends on whether the case failed there, and the
verifier rewrites the proposed solution and retest of such a finding.

Not changed:
Such a finding keeps origin change and its severity, so the change does not merge until the claim is narrowed or the
case handled.

Assisted-by: Claude Code (claude-opus-5-5)
An unsatisfiable method-reference target reports an inference failure and then checks the uninferred signature, producing additional compatibility diagnostics such as "parameter value of referenced method is @nonnull".

Give the inference diagnostic precedence over all parameter and return compatibility checks for the reference. A failed joint inference run suppresses these checks for every participating reference, including positions and references with independent mismatches. This deliberately avoids tracking inference dependencies for individual comparisons. Keep compatibility checks enabled when inference warnings are disabled.

Assisted-by: Codex (gpt-6)
Generic method references passed to diamond constructor calls need the enclosing constructor's inferred nullability, just as references passed to generic methods do. Exercise new Holder<>(Test::box, null) so falling back to the reference's declared method type is caught.

Assisted-by: Codex (gpt-6)
Successful bound, unbound, and varargs references can infer nullability from their return targets even when parameter constraints are missing. Exercise nullable inputs against non-null type-variable bounds with Object return targets, so only the parameter relations can trigger inference failures, and retain non-null input counterparts.

Assisted-by: Codex (gpt-6)
The method-reference inference contract omitted its early exits and failure reporting. Describe inference from the functional-interface target, cached results from enclosing calls, and failure diagnostics without relying on assumptions about its caller.

Assisted-by: Codex (gpt-6)
Method-reference inference currently runs without provisional lambda parameter types, but its cache write should honor the same policy as other inference paths. Guard success and failure writes with okToCacheInferenceResult(false) so a future caller using provisional parameter types cannot persist its result.

The path that skips caching is defensive and unreachable from the current invocation-checking caller.

Assisted-by: Codex (gpt-6)
The cache contract did not identify whose explicit type arguments constrain an enclosing call or whether the corresponding reference is a key. State that method references with explicit type arguments remain keys when their types constrain an enclosing generic call.

Assisted-by: Codex (gpt-6)
@msridhar
msridhar requested a review from vlsi November 18, 2026 21:40
@msridhar

Copy link
Copy Markdown
Contributor Author

@vlsi thanks for the feedback, this is ready for another look

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

Actionable comments posted: 1

@vlsi vlsi 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.

Out of scope: the positions tracked in #2176 and the receiver-substituted bounds tracked in #2181.

On the policy you asked about: precedence of the inference failure is fine for a reference whose types the failed run infers; F10 is about the references it does not constrain, which now lose errors that master reports. Nothing here blocks the merge.

Reviewed at 9211c9f7.

When WarnOnGenericInferenceFailure is enabled, a failed joint inference run suppresses override diagnostics for every method reference argument, including references whose checks do not depend on the run. An error in another argument can therefore hide a valid WRONG_OVERRIDE_PARAM or WRONG_OVERRIDE_RETURN diagnostic.

Share the cached inference result only with references that infer omitted generic method type arguments or whose ground target type mentions an inference variable registered with the solver. Independent references retain their parameter and return compatibility checks.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
The checkOverriding return contract says NO_MATCH means no error, but a method reference with a reported inference failure also skips override diagnostics. Describe that exception and link GenericsChecks.hasReportedInferenceFailure for the suppression policy.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
Existing diagnostic cases put each call and its method references on one line, so a failure reported at the enclosing call or a different argument goes undetected. Add a call with two references on separate lines and require the inference diagnostic on the failing reference's line. Check the compatibility diagnostics at that reference when inference warnings are disabled.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
@msridhar
msridhar requested a review from vlsi November 21, 2026 00:22
@msridhar msridhar added this to the v0.14.5 milestone Nov 21, 2026

@vlsi vlsi 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.

Out of scope: the positions tracked in #2176 and the receiver-substituted bounds tracked in #2181.

F17 and F18 are one change: describe the references of a failed run as 1496fce left them, in the cache Javadoc and in the test name. Nothing here blocks the merge.

Reviewed at d6fe2b2c.

A contradiction could stop constraint generation before a later method
reference joined the enclosing call's inference run. The reference
could then report a second `inference failure` from standalone inference
or a compatibility warning that depended on the failed inference.

Save the first contradiction in the solver and report it from solve().
This lets the remaining dependent references share the call's failure
while preserving the original diagnostic for the call.

Refs: #2175 (comment)
Assisted-by: Codex (gpt-6)
The inference cache Javadoc implied that every method-reference argument shared the enclosing result. Describe when a reference depends on an inference variable so readers can tell which references share a cached failure.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
The test expects independent compatibility errors alongside inference failures. Name it for the suppression rule that its assertions exercise.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
The inference failure tests did not require recognizing a nested call’s type variable in a method reference’s target. Add nested calls in which a nullable supplier depends on the nested call’s inference variable and a function’s parameter check is independent. Check the diagnostic locations with inference warnings enabled and disabled.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
The method-reference comments used several names for sites whose constraints are solved together. Use inference problem and inference variables to match the solver terminology.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
@msridhar
msridhar requested a review from vlsi November 25, 2026 00:59
@msridhar msridhar removed this from the v0.14.5 milestone Nov 25, 2026

@vlsi vlsi 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.

One thing blocks the merge for me. Deferring the contradiction to solve() gives a generic call nested in a later argument the outer call's inference failure, so code with no method reference now gets a false passing @Nullable parameter error at that nested call, with WarnOnGenericInferenceFailure on or off (F21).

F21 and F22 are one change: decide which nested calls share a failed inference, and pin that decision with cases that have no method reference. The rest are small.

Reviewed at 18704284.

Deferring a constraint contradiction lets collection visit later nested
calls. Caching the enclosing failure for those calls made a valid
`box(null)` report `passing @nullable parameter 'null' where @nonnull
is required`.

Keep ordinary nested calls reached after a deferred contradiction
eligible for separate inference. Continue registering method references
so their diagnostics can depend on the enclosing inference result.

Assisted-by: Codex (gpt-6)
An expectation for a diagnostic on a marked line can still pass when
NullAway emits an extra diagnostic on that line. Check the full
diagnostic set for two plain nested calls after an outer contradiction.
A valid `box(null)` produces no nested diagnostic. An invalid
`nn(null)` still reports its own inference failure.

Assisted-by: Codex (gpt-6)
The contract for adding constraints could be read as promising to
report every contradiction. State that the solver records the first,
discards later constraints, and throws the recorded failure from
`solve()`.

Assisted-by: Codex (gpt-6)
Standalone and joint inference made the same decision with different
checks. Use one predicate for both paths and for applying inferred
nullness in the resolver. Document javac's representation of omitted
type arguments at the predicate.

Assisted-by: Codex (gpt-6)
@msridhar
msridhar requested a review from vlsi November 27, 2026 00:13
@msridhar

Copy link
Copy Markdown
Contributor Author

Thanks @vlsi this is ready for another look

@vlsi vlsi 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.

Out of scope: the positions tracked in #2176 and the receiver-substituted bounds tracked in #2181.

One thing blocks the merge for me. A chain of nested generic calls whose inference fails now costs work quadratic in its depth where master is linear: after the contradiction the outer inference still walks each later nested call, drops what it generates, and the call is then inferred again (F26).

The rest are small.

Reviewed at ae2610c4.

A failed inference problem still descended into later nested generic
calls even though those calls were inferred separately. Repeating that
work at each level produced 2,016 executable-type lookups for a chain
of 63 failing calls.

Leave later nested generic calls to their own inference once the
solver records a contradiction. Continue processing direct lambda and
method-reference arguments of the failing call.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
A nested call visited before its enclosing inference fails can inherit
that failure. This hides a parameter mismatch on a method reference
and produces false positives on a valid box(null) call.

Assert the full diagnostic set for both cases and link the guard to
the follow-up issue for diagnosing independent calls separately.

Link: #2175 (comment)
Link: #2198
Assisted-by: Codex (gpt-6)
@msridhar
msridhar requested a review from vlsi November 27, 2026 17:25

@vlsi vlsi 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.

Out of scope: the positions tracked in #2176 and the receiver-substituted bounds tracked in #2181.

One thing blocks the merge for me. A chain of failing generic calls nested through lambdas still costs work quadratic in its depth, and overflows the stack at depth 40 where master reports every failure: after the contradiction, each later lambda argument's return expressions are still refined with dataflow (F29).

The rest are small.

Reviewed at 8631d4c4.

Two incompatible arguments can constrain different type variables.
Assert the exact warning names the first variable. A method reference
with incompatible return and parameter types exercises the same rule
within a single argument.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
Refining a later lambda return can rerun dataflow under a new path and
re-enter inference for the next failing call. Nested lambda chains
can then trigger quadratic work and a StackOverflowError.

Once the solver records a contradiction, follow conditional branches
and lambda returns to register dependent method references. Skip
argument type refinement and lambda parameter constraints.

**User-visible changes.**
Failing calls nested in lambdas can report their own inference failures without repeated lambda dataflow runs.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
A failing chain needs one lookup per call. The balanced expression's
limit allowed 1,512 lookups for 63 calls, enough for some repeated
constraint generation to pass. Bound the chain at two lookups per call.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
The allCalls parameter description omitted the conditions for adding a
reference. Document omitted generic method type arguments, inference
variables in the ground target type, and null for standalone inference.

Link: #2175 (comment)
Assisted-by: Codex (gpt-6)
@msridhar

msridhar commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

FYI #2199 is another false negative caused by this PR discovered via local review. It's filed as a follow-up to keep the scope of this one narrow, but I do plan to fix it soon in a follow up.

@vlsi vlsi 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.

Out of scope: the cases tracked in #2176, #2181, and #2198.

Nothing blocks the merge for me; F33 is small.

Reviewed at 899008c7.

Comment on lines +2263 to 2264
} else if (hasOmittedMethodReferenceTypeArguments(memberReferenceTree, overridingMethod)) {
result = getInferredMethodTypeForGenericMethodReference(result, state);

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.

F33 minor The false negative this change introduces for rejectsNull(InlineBound::forward) is deferred to #2199 with no test that pins it, and #2199 does not name its cause: the solver never relates two inference variables through a declared bound such as T extends U

Problem: The accepted program throws an NPE at run time (#2199). Deferring the fix is reasonable, since the solver gap is older than this change and JSpecify mode is documented as under development; but without a test marked (#2199) the follow-up has no failing case to flip, and #2199 describes only the method-reference path, which invites a reference-specific check that leaves the direct call and the joint-inference path unsound.

Reproducer
@NullMarked
class InlineBound {
  static <U extends @Nullable Object, T extends U> T forward(T value, Consumer<U> consumer) { consumer.accept(value); return value; }
  static void rejectsNull(BiFunction<@Nullable String, Consumer<String>, @Nullable String> fn) {}
  static <X extends @Nullable Object> void rejectsNullGeneric(BiFunction<@Nullable String, Consumer<String>, X> fn) {}
  static void directCall(Consumer<String> c) {
    forward(null, c);                         // base: no error; head: no error; expected: an error
  }
  static void viaRef() {
    rejectsNull(InlineBound::forward);        // base: "parameter value of referenced method is @NonNull ..."; head: no error (#2199)
  }
  static void viaGeneric() {
    rejectsNullGeneric(InlineBound::forward); // base: no error; head: no error; expected: an error
  }
}

Proposed solution: Accept the deferral to #2199. The decision that goes wrong is the solver's: it solves T and U independently, though T extends U requires a @nullable T to have a @nullable U; it should add the subtype constraint T <: U between the two inference variables when it registers them, which restores all three cases of the reproducer. This change can do without it, given two things: a test marked (#2199) that pins the current result for rejectsNull(InlineBound::forward), so the follow-up flips an existing expectation; and the direct call forward(null, c) and the solver as the place of the fix added to #2199.

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.

False positive for inline generic method references

2 participants