Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Compare extra parameters of a varargs method reference with its varargs element - #1953

Closed
vlsi wants to merge 1 commit into
apache:masterfrom
vlsi:varargs-method-ref-param-index
Closed

vlsi wants to merge 1 commit into
apache:masterfrom
vlsi:varargs-method-ref-param-index

Conversation

@vlsi

@vlsi vlsi commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Previously, a method reference to a varargs method whose functional interface has more parameters than the referenced method, such as BiConsumer<String, @Nullable String> c = Test::nullableElements with static void nullableElements(@Nullable String... elements), crashed the override check of the parameters in checkParamOverriding:

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

The check indexed the referenced method's parameters and its library-model parameter overrides by the functional-interface parameter's position. Both now take the index from getMemberRefParamIndex, as the rest of the method-reference check already does, so each extra parameter is compared with the varargs parameter. Fixing only the parameter lookup moves the crash to the library-model lookup, as ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1.

Caller sees:

  • parameter elements of referenced method is @NonNull where a @Nullable functional-interface parameter reaches a varargs element that excludes null, and no diagnostic where the element is @Nullable, instead of an IndexOutOfBoundsException from NullAway.

The new tests in VarargsTests (default mode), JSpecifyVarargsTests, and VarargsLibraryModelsTests fail on master with the exception above; the JSpecify one also covers a fixed parameter before the varargs, where parameter first of referenced method is @NonNull and parameter rest of referenced method is @NonNull are each reported for their own position.

Split out of #1834.

Assisted-by: Claude Code (claude-opus-5-5)

Summary by CodeRabbit

  • Bug Fixes
    • Corrected nullness checking for method references that pass multiple arguments to varargs methods. Nullable and non-null varargs elements are now checked against the corresponding parameters, including when the method has fixed parameters before its varargs parameter.
    • Improved handling of nullness annotations and library models in these cases, so incompatible argument mappings produce diagnostics.

…gs element

Previously, a method reference to a varargs method whose functional interface has more parameters than the referenced method, such as `BiConsumer<String, @nullable String> c = Test::nullableElements` with `static void nullableElements(@nullable String... elements)`, crashed the override check of the parameters in `checkParamOverriding`:

    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

The check indexed the referenced method's parameters and its library-model parameter overrides by the functional-interface parameter's position. Both now take the index from `getMemberRefParamIndex`, as the rest of the method-reference check already does, so each extra parameter is compared with the varargs parameter. Fixing only the parameter lookup moves the crash to the library-model lookup, as `ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1`.

Caller sees:
- `parameter elements of referenced method is @NonNull` where a `@Nullable` functional-interface parameter reaches a varargs element that excludes null, and no diagnostic where the element is `@Nullable`, instead of an `IndexOutOfBoundsException` from NullAway.

Assisted-by: Claude Code (claude-opus-5-5)
@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: uber/NullAway/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 578e403f-b068-4fec-a3d0-1e79f569ea4a

📥 Commits

Reviewing files that changed from the base of the PR and between 2b25d0f and 0773ad7.


📒 Files selected for processing (4)
  • nullaway/src/main/java/com/uber/nullaway/NullAway.java
  • nullaway/src/test/java/com/uber/nullaway/VarargsTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyVarargsTests.java
  • test-library-models/src/test/java/com/uber/nullaway/VarargsLibraryModelsTests.java

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



Walkthrough

checkParamOverriding now maps functional-interface parameter indices to referenced method parameter indices when checking method references that pass varargs elements individually. The mapping is used for parameter selection and handler-provided nullness overrides. Tests cover standard and JSpecify checks, plus modeled varargs methods.

Suggested reviewers: msridhar

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 0773a

The varargs method-reference change has no identified merge-blocking regression. The separate whole-array behavior remains worth addressing independently.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 4 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 identifies the main change: comparing extra functional-interface parameters with the referenced varargs element in a method reference.
Description check Passed The description explains the crash, the index-mapping fix, the library-model update, the expected behavior, and the added tests. It is directly related to the changeset.
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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🧪 Generate unit tests (beta)
  • Create a new PR

🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@codecov

codecov Bot commented Oct 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.75%. Comparing base (2b25d0f) to head (0773ad7).

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1953      +/-   ##
============================================
+ Coverage     87.72%   87.75%   +0.02%     
- Complexity     3531     3535       +4     
============================================
  Files           110      110              
  Lines         11756    11759       +3     
  Branches       2428     2428              
============================================
+ Hits          10313    10319       +6     
  Misses          662      662              
+ Partials        781      778       -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 commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

#2003 fixed this crash on master: checkParamOverriding now maps the position with getMemberRefParamIndex before it reads both the parameter symbol and the library-model override, so this change is redundant and conflicts with master in the same lines. The three tests added here pass on current master without the change in NullAway.java. I'm moving this PR to draft and will close it; the fixed-parameter-before-varargs case and the library-model case are not covered by a test on master yet, and I can send them as a tests-only PR if that's useful.

@vlsi
vlsi marked this pull request as draft October 21, 2026 20:31
@vlsi vlsi closed this Oct 21, 2026
msridhar pushed a commit that referenced this pull request Oct 22, 2026
In JSpecify mode, an explicitly typed lambda parameter was checked against the functional interface method only at the top level. The nullness of its array elements and type arguments was never compared, while an anonymous class overriding the same method gets that comparison. So `(Object[] inputs) -> {}` against `void apply(@nullable Object[] inputs)` was accepted, while `new Fi() { public void apply(Object[] inputs) {} }` was reported, and the same held for `(List<String> list) -> {}` against `apply(List<@nullable String> list)`. This is a variation of #1994, which #2003 fixed for the top-level parameter check only.

`matchLambdaExpression` now gives each explicitly typed parameter the check an overriding method's parameters get: the declared type may be a supertype of the interface method's parameter type, and type arguments must have identical nullness. The interface method type is taken as a member of the lambda's target type, with library models applied as for an override. An implicitly typed parameter takes the interface method's type and is skipped.

For an explicitly typed lambda passed to a generic method, call inference now takes constraints from the declared parameter types, nested types only. Without them, a type variable that only a declared parameter type mentions, such as `T` in `take((List<@nullable String> list) -> {})` against `<T extends @nullable Object> void take(Consumer<List<T>> c)`, defaulted to non-null, and the new check reported correct code. Top-level nullness stays out of inference, so a top-level mismatch is still reported at the parameter as `parameter s is @nonnull, but parameter in functional interface method ... is @Nullable`.

Caller sees: `Parameter has type List<String>, but overridden method has parameter type List<@nullable String>, which has mismatched type parameter nullability` at an explicitly typed lambda parameter whose array element or type argument nullness differs from the functional interface method's parameter.

`JSpecifyVarargsTests#restrictiveAnnotationsVarargsLambdaUsesArrayNullness` asserted that `(Object[] inputs) -> {}` against `@NullUnmarked void apply(@nullable Object @nonnull... inputs)` is clean. It now expects this warning, which the anonymous-class form of the same code already gets.

The constraint solver ignores the type arguments of an enclosing type, so `take((Outer<@nullable String>.Inner x) -> {})` against `Consumer<Outer<T>.Inner>` is still reported; a plain argument and a method reference with the same types are reported the same way before this change. No test covers a library model that adds nested annotations to a functional interface method parameter, since the test library models have none.

The open #1953 changes `NullAway.checkParamOverriding` for method references to varargs methods. This change does not touch that method; both add tests to `JSpecifyVarargsTests`, in different methods.

Assisted-by: Claude Code (claude-opus-5-5)

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

- **Bug Fixes**
  - Improved JSpecify nullness analysis for explicitly typed lambda parameters.
  - Detects mismatches between nullable and non-null generic, array, and varargs parameter types.
  - Applies correct type checking when assigning lambdas to functional interfaces or inferring generic method arguments.

- **Tests**
  - Added coverage for generic lambdas, arrays, wildcards, raw types, `BiConsumer`, and code outside JSpecify mode.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
vlsi added a commit to vlsi/NullAway that referenced this pull request Oct 22, 2026
Two oracles found apache#1990 to apache#1995 and apache#2004 by running NullAway over sources taken from its own tests, but they lived in an uncommitted pilot, so nothing reran them after a change. The crash oracle compiles every `addSourceLines` chain of the test sources (1049 seeds), plus three random annotation mutants of each, under three configurations, and NullAway must not throw on any source javac accepts. The metamorphic oracle compiles each seed against rewrites Java gives no meaning to, such as added parentheses, a cast to the expression's own type, `!(x == null)` for `x != null`, a lambda turned into an anonymous class, or a unit compiled against the others' class files, and NullAway must report the same warnings.

The harness is the `oracles` source set of the nullaway module, with its unit tests in `oraclesTest`, so `:nullaway:test`, diffCoverage, and pitestDiff do not see it. It compiles seeds against the test dependencies, which `oraclesImplementation` inherits from `testImplementation`. `check` runs `oraclesTest` (77 tests, a few seconds) so that a NullAway change that breaks the harness fails its own pull request. The aggregate coverage report collects execution data only from Test tasks that run the `test` classes, which keeps `oraclesTest` out of it.

`./gradlew :nullaway:runOracles` runs the oracles on JDK 21 (`-PoraclesJdk` picks another) with `-XX:-OmitStackTraceInFastThrow`, and writes `build/oracles/report.md`, a shorter `summary.md`, `new-findings.tsv`, and one directory of sources per finding. It accepts `--configs`, `--relations`, `--mutants`, `--limit`, `--filter`, `--max-minutes`, and `--random-seed`, and rejects any other option.

What changed from the pilot:

- A crash signature is the class of the last exception in the `Caused by` chain and its first `com.uber.nullaway` method, with no line number and with javac's lambda and anonymous-class ordinals masked as `$_`. The pilot took the first NullAway frame of the outermost exception, and the Checker Framework's dataflow analysis wraps what a transfer function throws, so the NPE of apache#2004 got the frame of apache#1990, `RunOnceForwardAnalysisImpl.performAnalysis`.
- `src/oracles/known-findings.tsv` lists the findings a person has triaged and that are still open: the crash signatures of apache#2004 and of the `checkParamOverriding` IndexOutOfBoundsException that apache#1953 fixes, and one `package-null-marked` divergence that is by design, since `UnannotatedSubPackages` overrides a package-level `@NullMarked` and not a class-level one. A divergence group is keyed by relation, seed, the side that reported the warning, and the masked message. Every finding not listed is reported as new, and `new-findings.tsv` holds it as a line to triage into the file. The findings of apache#1990 to apache#1995 are not listed, since their fixes have merged.
- Each seed's mutants come from a hash of the seed name, the configuration, and `--random-seed`, and a seed name holds the test file and method without a line number, so adding a test leaves the other seeds' mutants and baseline keys unchanged.
- javac's limit of 100 warnings is lifted, the mutator no longer annotates an anonymous class body, the relations skip rewrites that change meaning or move a warning to another line (an operator inside a comment, an expression or comparison that spans lines, a cast around a parenthesized generic call or a conditional, a lambda body that uses a member name of its interface, a copied type whose nullness default would change), and a rewrite that throws is counted and logged instead of ending the run.

The `NullAway oracles` workflow runs on every push to master and on `workflow_dispatch`, never on a pull request or a merge queue entry. It runs all configurations with `--mutants 3` and a 40-minute budget inside a 60-minute job, writes `summary.md` to the job summary, and uploads `build/oracles` as the `oracle-report` artifact. It fails only when the run sees a crash signature the file does not list; known crashes and every divergence are report-only, since telling a NullAway defect from a rewrite artifact takes a person.

A full run on JDK 21 at 2f72807 covers 1094 seeds and sees no crash; the mutants of `--random-seed 1` reach neither of the two listed signatures. It took 8 min 30 s on a laptop running other builds, and 4 min 30 s on the same laptop idle before the rebase. It reports the listed `package-null-marked` group as known and 33 groups as new. These 33 remain after the fixes for apache#1993 and apache#1994 merged, and each is a false positive of the rewritten form or a warning the plain form misses:

- 28 `cast` groups: a cast to the expression's own type around a map key or a constant argument of an access-path call (`AccessPath.argumentToMapKeySpecifier` and `buildAccessPathRecursive` match the argument's tree kind before removing casts), a primitive cast to the operand's own type (`AccessPath.stripCasts` keeps it), `return (boolean) (false);` in an `@EnsuresNonNullIf` method or a stream `filter` callback, and `(boolean) (x != null)` as an argument of a multi-argument `@Contract`.
- 4 `parentheses` groups: a parenthesized lambda passed to `Futures.transform` (`FluentFutureHandler`), a parenthesized lambda or method reference passed to `Stream.map` after `filter` (`GenericsChecks` records inferred types only for an unwrapped argument), and `containsKey((k))` in the gRPC `Metadata` handler.
- 1 `lambda-to-anonymous-class` group: an explicitly typed lambda parameter `Object[]` is not checked against `@Nullable Object[]` element nullness, which an anonymous class override is.

Jazzer and seeds from the Hephaestus program generator, which the pilot also tried, are not part of this change.

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

1 participant