You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@maven.apache.org by "arturobernalg (via GitHub)" <gi...@apache.org> on 2026/10/15 04:19:07 UTC

[PR] Fire the DependencyResolutionResult event when the resolution fails (fix #8635) [maven]

arturobernalg opened a new pull request, #13539:
URL: https://github.com/apache/maven/pull/13539

   Fixes #8635
   
   ### What and why
   
   `LifecycleDependencyResolver` sent the `DependencyResolutionResult` to the event spies only after a successful resolution. When the resolution failed, the `DependencyResolutionException` was turned into a `LifecycleExecutionException` before the dispatch, so a listener got the request but no result, and had to look for the result in the cause of an `ExecutionEvent`. The issue asks for the result to be fired when the resolution fails too.
   
   ### How
   
   The result is dispatched right after the resolution, in the success path and in the `catch` block, and the dispatch after the `try` is removed. The order for a successful resolution does not change, and an aggregator which tolerates the failure still gets the result once.
   
   ### Tests
   
   `LifecycleDependencyResolverEventsTest` is new, with a mocked resolver and event dispatcher: the result is fired once when the resolution succeeds, when it fails, and when an aggregator tolerates the failure. The failure test fails on master (the result is never dispatched) and the three pass with the change, three runs in a row. `maven-core` passes (746 tests) and spotless is clean. I did not run the integration tests.
   
   This changes what the listeners receive on a failed resolution, so a backport is up to the maintainers.
   
   ---
   
   To make clear that you license your contribution under
   the [Apache License Version 2.0, January 2004](https://www.apache.org/licenses/LICENSE-2.0)
   check one of the following:
   
   - [ ] I hereby declare this contribution to be licensed under the [Apache License Version 2.0, January 2004](https://www.apache.org/licenses/LICENSE-2.0)
   - [ ] I hereby declare that I have filed an [Apache Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on code in PR #13539:
URL: https://github.com/apache/maven/pull/13539#discussion_r4295883051


##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/EventSpyImplTest.java:
##########
@@ -128,6 +141,94 @@ public void sessionStarted(ExecutionEvent event) {
         assertEquals(1, calls.get());
     }
 
+    @Test
+    void forwardsSuccessfulDependencyResolution() throws Exception {
+        TestContext context = new TestContext(lookup());
+        RecordingResolutionListener listener = new RecordingResolutionListener();
+        context.session.registerListener(listener);
+        Dependency dependency = new Dependency(new DefaultArtifact("g:a:1"), "compile");
+        DependencyResolutionResult result = result(List.of(dependency), List.of(), List.of());
+
+        EventSpyImpl spy = new EventSpyImpl();
+        DependencyResolutionRequest request = context.resolution();

Review Comment:
   Added a Javadoc on the test in 922162f saying it only pins the request pairing and does not exercise the weak reference.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fire the DependencyResolutionResult event when the resolution fails (fix #8635) [maven]

Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6199360470

   Good observation. The fix correctly handles the legacy `EventSpy` path, but `DependencyResolutionRequest`/`DependencyResolutionResult` events are **not** forwarded to Maven 4 API listeners at all — that gap exists both before and after this fix.
   
   `EventSpyImpl` (the bridge in `impl/maven-core`) only handles `ExecutionEvent` objects:
   
   ```java
   public void onEvent(Object arg) throws Exception {
       if (arg instanceof ExecutionEvent ee) {  // only this branch exists
           ...
       }
   }
   ```
   
   When `eventSpyDispatcher.onEvent(result)` is called with a `DependencyResolutionResult`, `EventSpyImpl` receives it but silently ignores it — so Maven 4 API `Listener`s registered on the session never see it.
   
   To properly expose this through the Maven 4 API, we'd need:
   
   1. A `DependencyResolutionEvent` interface in `maven-api-core` (extending `Event`) that exposes the project, the resolution result, and optionally the exception.
   2. A `DependencyResolutionListener` sub-interface of `Listener` with typed callbacks (`onDependencyResolutionStarted`, `onDependencyResolutionSucceeded`, `onDependencyResolutionFailed`), analogous to `ExecutionListener` / `RepositoryListener`.
   3. Forwarding in `EventSpyImpl.onEvent()` for `DependencyResolutionRequest` and `DependencyResolutionResult` instances.
   
   That said, it might be cleaner to handle this as a follow-up rather than blocking this PR — the current fix is already a self-contained, correct improvement. The Maven 4 API side would benefit from a separate issue and PR.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix DependencyResolutionResult not dispatched when resolution fails (fix #8635) [maven]

Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet merged PR #13539:
URL: https://github.com/apache/maven/pull/13539


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix DependencyResolutionResult not dispatched when resolution fails (fix #8635) [maven]

Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6350546227

   <!-- maven-backport-bot -->
   
   **Conflicts — manual resolution needed:**
   - ❌ `maven-4.0.x`: Cherry-pick conflict in: 
   - ❌ `maven-3.10.x`: Cherry-pick conflict in: 
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6287663245

   Thanks for working on this @arturobernalg!
   
   The bug fix in `LifecycleDependencyResolver` (firing the result on failure too) is straightforward and addresses #8635 directly. However, the Maven 4 API additions (`DependencyResolutionEvent`, `DependencyResolutionEventType`, `DependencyResolutionListener`) feel too specific — if we later want to expose settings building, toolchains, or other service calls to Maven 4 listeners, we'd need to create another triplet of types each time.
   
   I've opened #13646 to discuss a generic `RequestEvent` design that reuses the existing `Request`/`Result` hierarchy and scales to any service call, while still allowing specialized listeners like `DependencyResolutionListener` with convenient typed callbacks.
   
   Could you limit this PR to just the bug fix (the `LifecycleDependencyResolver` change and its test) so we can get that merged? The Maven 4 API layer can then be designed and implemented as part of #13646.
   
   _Claude Code on behalf of Guillaume Nodet_


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #13539:
URL: https://github.com/apache/maven/pull/13539#discussion_r4293375769


##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java:
##########
@@ -52,22 +62,47 @@ public void onEvent(Object arg) throws Exception {
             EventType eventType = convert(ee.getType());
             Collection<Listener> listeners = session.getListeners();
             if (!listeners.isEmpty()) {
-                org.apache.maven.api.ExecutionEvent event = new DefaultEvent(session, ee, eventType);
-                for (Listener listener : listeners) {
-                    try {
-                        listener.onEvent(event);
-                    } catch (RuntimeException e) {
-                        LOGGER.warn(
-                                "Failed to notify listener {} about {}",
-                                listener.getClass().getName(),
-                                eventType,
-                                e);
-                    }
+                notify(listeners, new DefaultEvent(session, ee, eventType), eventType);
+            }
+        } else if (arg instanceof DependencyResolutionRequest request) {
+            pendingResolution.set(request);

Review Comment:
   💡 **Defensive suggestion:** `pendingResolution` is set here but only cleaned up when a `DependencyResolutionResult` event arrives. If `dependenciesResolver.resolve()` throws an unexpected `RuntimeException` or `Error` (not `DependencyResolutionException`), `LifecycleDependencyResolver` will propagate the exception without dispatching a result event, leaving the ThreadLocal set for the lifetime of the thread.
   
   In a thread-pool build this is a minor resource leak per failed resolution; in a thread-reuse scenario it could cause a stale request to be matched to the next resolution's result. A `try/finally` around the `resolve()` call in `LifecycleDependencyResolver` would be the cleanest fix, but alternatively the `onEvent(DependencyResolutionResult)` branch could tolerate a missing request by also calling `pendingResolution.remove()` unconditionally (it already does this). The risk is low in practice since the exception would also abort the build, but it's worth a TODO comment at minimum.



##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyResolutionEvent.java:
##########
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.internal.impl;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+
+import org.apache.maven.api.Dependency;
+import org.apache.maven.api.DependencyResolutionEvent;
+import org.apache.maven.api.DependencyResolutionEventType;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.project.DependencyResolutionResult;
+
+/**
+ * Maven 4 view of a dependency resolution, created from the legacy request and result.
+ */
+class DefaultDependencyResolutionEvent implements DependencyResolutionEvent {
+    private final InternalMavenSession session;
+    private final Project project;
+    private final DependencyResolutionEventType type;
+    private final List<Dependency> resolved;
+    private final List<Dependency> unresolved;
+    private final Exception exception;
+
+    /** Creates the event fired before the dependencies of the project are resolved. */
+    DefaultDependencyResolutionEvent(InternalMavenSession session, Project project) {
+        this.session = Objects.requireNonNull(session, "session");
+        this.project = Objects.requireNonNull(project, "project");
+        this.type = DependencyResolutionEventType.STARTED;
+        this.resolved = List.of();
+        this.unresolved = List.of();
+        this.exception = null;
+    }
+
+    /** Creates the event fired once the dependencies of the project have been resolved or have failed to. */
+    DefaultDependencyResolutionEvent(InternalMavenSession session, Project project, DependencyResolutionResult result) {
+        this.session = Objects.requireNonNull(session, "session");
+        this.project = Objects.requireNonNull(project, "project");
+        this.resolved = result.getResolvedDependencies().stream()
+                .map(session::getDependency)
+                .toList();
+        this.unresolved = result.getUnresolvedDependencies().stream()
+                .map(session::getDependency)
+                .toList();
+        Exception failure = null;
+        if (!result.getCollectionErrors().isEmpty()) {
+            failure = result.getCollectionErrors().get(0);
+        } else {
+            for (org.eclipse.aether.graph.Dependency dependency : result.getUnresolvedDependencies()) {
+                List<Exception> errors = result.getResolutionErrors(dependency);
+                if (errors != null && !errors.isEmpty()) {
+                    failure = errors.get(0);
+                    break;
+                }
+            }
+        }
+        this.exception = failure;
+        this.type = failure != null || !unresolved.isEmpty()
+                ? DependencyResolutionEventType.FAILED
+                : DependencyResolutionEventType.SUCCEEDED;

Review Comment:
   🔍 **API contract observation:** When `unresolved` is non-empty but every unresolved dependency has empty `getResolutionErrors()` (and there are no collection errors), `failure` remains `null` yet `type` is set to `FAILED`. Callers of `DependencyResolutionEvent` who follow the documented contract — checking `type() == FAILED` then calling `exception()` — will get `Optional.empty()` in this edge case, which may be surprising.
   
   This scenario is unlikely in practice (a dependency ends up unresolved with no errors), but a brief Javadoc note on `exception()` clarifying that it may be empty even when `type()` is `FAILED` would prevent confusion for API consumers:
   
   ```suggestion
       /**
        * {@return the primary failure of the resolution, if any}
        * This is the first dependency collection error or, when there is none, the first resolution error.
        * May be empty even when {@link #type()} is {@link DependencyResolutionEventType#FAILED}
        * if dependencies failed to resolve without a reported error.
        */
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6214525320

   Applied in 2ea0f23: `pendingResolution.remove()` now runs before `set()` when a new request begins, so a stale entry from a failed resolution is cleared. maven-core tests still pass.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6287872687

   Scoped down in 49979b0 to just the bug fix: `LifecycleDependencyResolver` dispatching the result in the success and failure paths, plus `LifecycleDependencyResolverEventsTest`. Dropped `DependencyResolutionEvent`/`DependencyResolutionEventType`/`DependencyResolutionListener`, `DefaultDependencyResolutionEvent`, the `EventSpyImpl` forwarding and its tests entirely, deferring that to #13646.
   
   Verified against current master: `mvn -pl impl/maven-core test` — 757 tests, 0 failures — and `spotless:check` clean.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6212849020

   Good catch, thanks. In befca4976e the dispatch is skipped when the project has no base directory, as there is no API project to report, and both DefaultDependencyResolutionEvent constructors now fail fast with Objects.requireNonNull. My tests had hidden the problem: new MavenProject() has no base directory, so the event was created with a null project. The helper now gives the project a file, the tests assert that the project is present, and a new test checks that nothing is dispatched for a project without a base directory.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #13539:
URL: https://github.com/apache/maven/pull/13539#discussion_r4293517187


##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java:
##########
@@ -52,18 +67,51 @@ public void onEvent(Object arg) throws Exception {
             EventType eventType = convert(ee.getType());
             Collection<Listener> listeners = session.getListeners();
             if (!listeners.isEmpty()) {
-                org.apache.maven.api.ExecutionEvent event = new DefaultEvent(session, ee, eventType);
-                for (Listener listener : listeners) {
-                    try {
-                        listener.onEvent(event);
-                    } catch (RuntimeException e) {
-                        LOGGER.warn(
-                                "Failed to notify listener {} about {}",
-                                listener.getClass().getName(),
-                                eventType,
-                                e);
-                    }
-                }
+                dispatch(listeners, new DefaultEvent(session, ee, eventType), eventType);
+            }
+        } else if (arg instanceof DependencyResolutionRequest request) {
+            pendingResolution.set(new WeakReference<>(request));

Review Comment:
   💡 **Minor — stale `ThreadLocal` entry on unexpected `RuntimeException`**
   
   If `LifecycleDependencyResolver.getDependencies()` throws an unexpected `RuntimeException` (not caught by `catch (DependencyResolutionException)`), no `DependencyResolutionResult` event is dispatched and `pendingResolution.remove()` is never called. The `WeakReference` mitigates the referent leak, but the `ThreadLocal` slot itself remains set for the life of the thread (e.g. in a thread-pool scenario).
   
   A simple defensive fix: call `remove()` before `set()` so that any stale entry from a prior failed resolution is cleared when a new request begins:
   
   ```suggestion
               pendingResolution.remove();
               pendingResolution.set(new WeakReference<>(request));
   ```
   
   This is a best-effort cleanup — the `WeakReference` already prevents a hard memory leak, so this is purely defensive.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6212185437

   Done in 979cb9e104. The Maven 4 API now has a typed DependencyResolutionEvent (project, resolved and unresolved dependencies, failure), a DependencyResolutionEventType (STARTED, SUCCEEDED, FAILED) and a DependencyResolutionListener with one callback per type, in the style of ExecutionListener and RepositoryListener. EventSpyImpl forwards both the request and the result to the listeners of the session. The result carries neither the project nor the session, so it is matched with the request dispatched just before it on the same thread. EventSpyImplTest covers a successful resolution, a failed one, and a result without a request. maven-core passes, and the title and description are updated.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #13539:
URL: https://github.com/apache/maven/pull/13539#discussion_r4294263221


##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/EventSpyImplTest.java:
##########
@@ -128,6 +141,94 @@ public void sessionStarted(ExecutionEvent event) {
         assertEquals(1, calls.get());
     }
 
+    @Test
+    void forwardsSuccessfulDependencyResolution() throws Exception {
+        TestContext context = new TestContext(lookup());
+        RecordingResolutionListener listener = new RecordingResolutionListener();
+        context.session.registerListener(listener);
+        Dependency dependency = new Dependency(new DefaultArtifact("g:a:1"), "compile");
+        DependencyResolutionResult result = result(List.of(dependency), List.of(), List.of());
+
+        EventSpyImpl spy = new EventSpyImpl();
+        DependencyResolutionRequest request = context.resolution();

Review Comment:
   💡 **Note:** `matchesResultWithTheLatestRequestWhenAnEarlierOneGotNoResult` validates request-replacement logic (the `remove()+set()` pattern), but it would pass identically with a plain `ThreadLocal<DependencyResolutionRequest>`. The `WeakReference`'s GC-prevention-of-retention benefit is not exercised by this test. This is acceptable — deterministic GC-dependent tests are fragile — but worth noting in a comment on the test.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "arturobernalg (via GitHub)" <gi...@apache.org>.
arturobernalg commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6213177426

   Both points addressed in 3853ecc2b2. The pending request is now held through a WeakReference, and the Javadoc explains why a request which got no result can never be matched with a later result: a request is always dispatched before its result and replaces the previous one, so the only thing that could remain is a reference, which no longer keeps the project alive. exception() now documents that it may be empty when the type is FAILED. I also merged the two dispatch branches into one helper and renamed notify to dispatch, so it no longer looks like Object.notify. A new test checks that a result is matched with the latest request when an earlier one got none.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Expose dependency resolution events through the Maven 4 API (fix #8635) [maven]

Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #13539:
URL: https://github.com/apache/maven/pull/13539#discussion_r4293029639


##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java:
##########
@@ -52,22 +61,46 @@ public void onEvent(Object arg) throws Exception {
             EventType eventType = convert(ee.getType());
             Collection<Listener> listeners = session.getListeners();
             if (!listeners.isEmpty()) {
-                org.apache.maven.api.ExecutionEvent event = new DefaultEvent(session, ee, eventType);
-                for (Listener listener : listeners) {
-                    try {
-                        listener.onEvent(event);
-                    } catch (RuntimeException e) {
-                        LOGGER.warn(
-                                "Failed to notify listener {} about {}",
-                                listener.getClass().getName(),
-                                eventType,
-                                e);
-                    }
+                notify(listeners, new DefaultEvent(session, ee, eventType), eventType);
+            }
+        } else if (arg instanceof DependencyResolutionRequest request) {
+            pendingResolution.set(request);
+            InternalMavenSession session = InternalMavenSession.from(request.getRepositorySession());
+            Collection<Listener> listeners = session.getListeners();
+            if (!listeners.isEmpty()) {
+                DependencyResolutionEvent event =
+                        new DefaultDependencyResolutionEvent(session, session.getProject(request.getMavenProject()));

Review Comment:
   ⚠️ **`@Nonnull` contract violation — STARTED path:** `session.getProject(request.getMavenProject())` is declared `@Nullable` (see `InternalMavenSession.getProject`) and returns `null` when the project has no basedir. Passing it directly to the `DefaultDependencyResolutionEvent` constructor violates `DependencyResolutionEvent.project()`'s `@Nonnull` contract and will cause a `NullPointerException` at any listener call site that calls `event.project()`.
   
   Consider skipping the event dispatch when the project is null, or explicitly handling the null case:
   ```suggestion
                   Project project = session.getProject(request.getMavenProject());
                   if (project == null) {
                       return;
                   }
                   DependencyResolutionEvent event =
                           new DefaultDependencyResolutionEvent(session, project);
   ```



##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyResolutionEvent.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.internal.impl;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.apache.maven.api.Dependency;
+import org.apache.maven.api.DependencyResolutionEvent;
+import org.apache.maven.api.DependencyResolutionEventType;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.project.DependencyResolutionResult;
+
+/**
+ * Maven 4 view of a dependency resolution, created from the legacy request and result.
+ */
+class DefaultDependencyResolutionEvent implements DependencyResolutionEvent {
+    private final InternalMavenSession session;
+    private final Project project;
+    private final DependencyResolutionEventType type;
+    private final List<Dependency> resolved;
+    private final List<Dependency> unresolved;
+    private final Exception exception;
+
+    /** Creates the event fired before the dependencies of the project are resolved. */
+    DefaultDependencyResolutionEvent(InternalMavenSession session, Project project) {

Review Comment:
   💡 **Defense-in-depth:** Add `Objects.requireNonNull(project, "project")` in both constructors. Since `project()` is declared `@Nonnull`, the constructor should fail fast with a clear message rather than storing a silent `null` that will cause a cryptic NPE later at the listener call site.
   
   ```suggestion
       DefaultDependencyResolutionEvent(InternalMavenSession session, Project project) {
           this.session = Objects.requireNonNull(session, "session");
           this.project = Objects.requireNonNull(project, "project");
   ```



##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultDependencyResolutionEvent.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.internal.impl;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.apache.maven.api.Dependency;
+import org.apache.maven.api.DependencyResolutionEvent;
+import org.apache.maven.api.DependencyResolutionEventType;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.project.DependencyResolutionResult;
+
+/**
+ * Maven 4 view of a dependency resolution, created from the legacy request and result.
+ */
+class DefaultDependencyResolutionEvent implements DependencyResolutionEvent {
+    private final InternalMavenSession session;
+    private final Project project;
+    private final DependencyResolutionEventType type;
+    private final List<Dependency> resolved;
+    private final List<Dependency> unresolved;
+    private final Exception exception;
+
+    /** Creates the event fired before the dependencies of the project are resolved. */
+    DefaultDependencyResolutionEvent(InternalMavenSession session, Project project) {
+        this.session = session;
+        this.project = project;
+        this.type = DependencyResolutionEventType.STARTED;
+        this.resolved = List.of();
+        this.unresolved = List.of();
+        this.exception = null;
+    }
+
+    /** Creates the event fired once the dependencies of the project have been resolved or have failed to. */
+    DefaultDependencyResolutionEvent(InternalMavenSession session, Project project, DependencyResolutionResult result) {

Review Comment:
   💡 **Defense-in-depth (3-arg constructor):** Same `Objects.requireNonNull` guard needed here.
   
   ```suggestion
       DefaultDependencyResolutionEvent(InternalMavenSession session, Project project, DependencyResolutionResult result) {
           this.session = Objects.requireNonNull(session, "session");
           this.project = Objects.requireNonNull(project, "project");
   ```



##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java:
##########
@@ -52,22 +61,46 @@ public void onEvent(Object arg) throws Exception {
             EventType eventType = convert(ee.getType());
             Collection<Listener> listeners = session.getListeners();
             if (!listeners.isEmpty()) {
-                org.apache.maven.api.ExecutionEvent event = new DefaultEvent(session, ee, eventType);
-                for (Listener listener : listeners) {
-                    try {
-                        listener.onEvent(event);
-                    } catch (RuntimeException e) {
-                        LOGGER.warn(
-                                "Failed to notify listener {} about {}",
-                                listener.getClass().getName(),
-                                eventType,
-                                e);
-                    }
+                notify(listeners, new DefaultEvent(session, ee, eventType), eventType);
+            }
+        } else if (arg instanceof DependencyResolutionRequest request) {
+            pendingResolution.set(request);
+            InternalMavenSession session = InternalMavenSession.from(request.getRepositorySession());
+            Collection<Listener> listeners = session.getListeners();
+            if (!listeners.isEmpty()) {
+                DependencyResolutionEvent event =
+                        new DefaultDependencyResolutionEvent(session, session.getProject(request.getMavenProject()));
+                notify(listeners, event, event.type());
+            }
+        } else if (arg instanceof DependencyResolutionResult result) {
+            DependencyResolutionRequest request = pendingResolution.get();
+            pendingResolution.remove();
+            if (request != null) {
+                InternalMavenSession session = InternalMavenSession.from(request.getRepositorySession());
+                Collection<Listener> listeners = session.getListeners();
+                if (!listeners.isEmpty()) {
+                    DependencyResolutionEvent event = new DefaultDependencyResolutionEvent(
+                            session, session.getProject(request.getMavenProject()), result);

Review Comment:
   ⚠️ **`@Nonnull` contract violation — RESULT path:** Same issue. `session.getProject(request.getMavenProject())` can return `null`, violating `DependencyResolutionEvent.project()`'s `@Nonnull` contract.
   
   ```suggestion
                       Project project = session.getProject(request.getMavenProject());
                       if (project == null) {
                           return;
                       }
                       DependencyResolutionEvent event = new DefaultDependencyResolutionEvent(
                               session, project, result);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix DependencyResolutionResult not dispatched when resolution fails (fix #8635) [maven]

Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #13539:
URL: https://github.com/apache/maven/pull/13539#issuecomment-6350642264

   <!-- maven-backport-bot -->
   
   **Backport PRs created:**
   - ✅ `maven-4.0.x` → #13687
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org