Skip to content

Explicit @Nullable return on an annotated override is ignored since #1758 #1769

Closed

Description

@vlsi

Since #1758, an explicit @Nullable return annotation on an override of a method that carries a nullImpliesNull library model is ignored in annotated code, and the dereference error NullAway used to report disappears. The regression is on 0.14.1-SNAPSHOT only; 0.14.0 does not have it.

Reproducer

Added to a class extending NullAwayTestsBase, so com.uber is an annotated package:

@Test
public void annotatedOverrideWithExplicitNullableReturn() {
  defaultCompilationHelper
      .addSourceLines(
          "Probe.java",
          "package com.uber;",
          "import java.util.HashMap;",
          "import javax.annotation.Nullable;",
          "class MyMap extends HashMap<String, String> {",
          "  @Override",
          "  public @Nullable String getOrDefault(Object key, String defaultValue) { return null; }",
          "}",
          "class Probe {",
          "  void f(MyMap m) {",
          "    // BUG: Diagnostic contains: dereferenced",
          "    m.getOrDefault(\"a\", \"b\").length();",
          "  }",
          "}")
      .doTest();
}

At f455521, the parent of the squash merge, the test passes: NullAway reports the dereference. At 94003d2 it fails with Did not see an error on line 11 matching dereferenced. There were no errors.

Mechanism

OptimizedLibraryModels.nullImpliesNullParameters hard-codes the inheritance flag (LibraryModelsHandler.java:1687):

ImmutableSet<Integer> nullImpliesNullParameters(Symbol.MethodSymbol symbol, Types types) {
  Symbol.MethodSymbol modelSymbol =
      lookupHandlingOverrides(
          symbol, types, nullImpliesNullParams, /* allowInheritedModelLookup= */ true);

hasNonNullReturn and hasNullableReturn beside it receive !isMethodAnnotated, so MyMap.getOrDefault inherits Map.getOrDefault's model although MyMap is annotated code. onDataflowVisitMethodInvocation tests nullImpliesNull before it consults isMethodAnnotated at all, and returns FORCE_NONNULL because the default argument is non-null. NullAway.mayBeNullExpr ends with return exprMayBeNull && nullnessFromDataflow(state, expr); (NullAway.java:2957), so that FORCE_NONNULL wins over the annotation the user wrote.

Two places state the older rule and still stand: the comment at LibraryModelsHandler.java:229-233, a dozen lines above the changed call site, and the javadoc on LibraryModels#nullImpliesNullParameters, which describes the model as equivalent to @Contract("!null -> !null") @Nullable on the listed method and says nothing about overriders.

Scope

java.util.Map.getOrDefault is the only entry in NULL_IMPLIES_NULL_PARAMETERS (LibraryModelsHandler.java:1071) that user code can override: Class.cast and Optional.orElse sit on final classes, Closer is final, and Objects.toString is static. An entry supplied through the LibraryModels SPI has no such limit, and one placed on an interface now covers every implementation in the user's own annotated code.

The question

Should an explicit @Nullable return in annotated code win over a nullImpliesNull model inherited from an overridden library method?

If it should, lookupHandlingOverrides already returns the model symbol, so the caller can distinguish an inherited model from an exact one and drop the inherited one when the callee is annotated and carries a nullable return annotation. That leaves #1758's fix in place, since HashMap.getOrDefault's nullability comes from the astubx nullableRet model rather than a source annotation. I can send a PR with that plus the two documentation updates.

If the current behavior is what you want, the comment and the javadoc still need to change, and a test should pin it.

Activity

  1. msridhar commented on Aug 28, 2026

    @msridhar
    Contributor

    Hi @vlsi the right fix here is to check contract overriding, which is #803. What we should be enforcing is:

    1. MyMap.getOrDefault should be declared with a _, !null -> !null contract; the missing contract itself should be an error.
    2. Once 1 is addressed, with checking of contracts enabled, we should report a warning that we cannot verify the contract on MyMap.getOrDefault.

    For this case, we also need to reason about library models, of course, since there is no explicit contract on Map.getOrDefault.

    We should fix this, but I don't think it's the highest priority. Do you have specific changes to documentation you'd like to see in the meantime?

  2. vlsi commented on Aug 28, 2026

    @vlsi
    ContributorAuthor

    That framing makes sense: the model is the contract, and the missing piece is verification of the override rather than precedence between the model and the annotation.

    Two comments state the older rule, and both sit where I looked while working out what happened. Concretely:

    diff --git a/nullaway/src/main/java/com/uber/nullaway/LibraryModels.java b/nullaway/src/main/java/com/uber/nullaway/LibraryModels.java
    index 2f4642a9..2ea80663 100644
    --- a/nullaway/src/main/java/com/uber/nullaway/LibraryModels.java
    +++ b/nullaway/src/main/java/com/uber/nullaway/LibraryModels.java
    @@ -108,6 +108,9 @@ public interface LibraryModels {
        *
        * <pre><code>@Contract("!null -&gt; !null") @Nullable</code></pre>
        *
    +   * <p>The model applies to any method that overrides the listed method. NullAway does not check
    +   * that such an override obeys the contract (issue #803).
    +   *
        * @return map from the names of null-in-implies-null out methods to the indexes of the arguments
        *     that determine nullness of the return.
        */
    diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java
    index 17566f20..b28aa960 100644
    --- a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java
    +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java
    @@ -226,11 +226,11 @@ public class LibraryModelsHandler implements Handler {
           return exprMayBeNull;
         }
         OptimizedLibraryModels optLibraryModels = getOptLibraryModels(state.context);
    -    // When looking up library models of annotated code, we match the exact method signature only;
    -    // overriding methods in subclasses must be explicitly given their own library model.
    -    // When dealing with unannotated code, we default to generality: a model applies to a method
    -    // and any of its overriding implementations.
    -    // see https://github.com/uber/NullAway/issues/445 for why this is needed.
    +    // A model of a method's return nullness matches the exact signature when the method is
    +    // annotated: the overriding method carries its own annotations, and an inherited model must
    +    // not override them (issue #445). Unannotated code has no annotations to defer to, so there a
    +    // model covers every overriding implementation. A nullImpliesNull model is a conditional
    +    // contract, and applies to an overriding implementation in annotated code too.
         boolean isMethodUnannotated =
             getCodeAnnotationInfo(state.context)
                 .isSymbolUnannotated(methodSymbol, this.config, mainHandler);

    On the first one: the comment cites #445, where the whole point was that an annotated subclass narrowing Throwable.getMessage() must win over the inherited model. Since #1758 that rule holds for return nullness and not for nullImpliesNull, so the comment reads as a claim about both. The rewrite records the asymmetry as intentional, which is what your answer says it is.

    On the second: LibraryModels is a published SPI, so the reader implementing it cannot look at the lookup code to find out that a model on an interface method reaches every implementation, or that nothing checks those implementations yet.

    Happy to send this as a PR.

  3. msridhar commented on Aug 28, 2026

    @msridhar
    Contributor

    Yes, please send as a PR, thanks!

  4. msridhar commented on Aug 29, 2026

    @msridhar
    Contributor

    I'm going to close this one in favor of #803

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions