You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@maven.apache.org by "gnodet (via GitHub)" <gi...@apache.org> on 2026/09/22 11:58:22 UTC

[PR] Fix PathConflictResolver OOM on dense dependency graphs [maven-resolver]

gnodet opened a new pull request, #2153:
URL: https://github.com/apache/maven-resolver/pull/2153

   ## Problem
   
   `PathConflictResolver` runs out of memory (`OutOfMemoryError: Java heap space`) on highly connected dependency graphs, such as a 813-module reactor where each module depends on ~9 others.
   
   Reproduced with `-Xmx512m`:
   ```
   java.lang.OutOfMemoryError: Java heap space
       at PathConflictResolver$Path.addChildren(PathConflictResolver.java:699)
       at PathConflictResolver$State.gatherCRNodes(PathConflictResolver.java:363)
   ```
   
   Workaround: `-Daether.conflictResolver.impl=classic`
   
   ## Root Cause
   
   `gatherCRNodes` performs a BFS/DFS traversal that creates a new `Path` object for **every edge** in the expanded dependency tree — not just one per `DependencyNode`. When the same node is reachable via N different parent paths, its entire subtree is traversed N times, leading to exponential `Path` allocation.
   
   For 813 modules × ~9 avg deps, this produces millions of `Path` objects instead of the ~7,500 that actually represent unique graph edges.
   
   ## Fix
   
   Two complementary changes:
   
   **1. Expansion deduplication** (the OOM fix):  
   Track which `DependencyNode` instances have already been expanded in an `IdentityHashMap<DependencyNode, Integer>` (mapped to expansion depth). When the same `DependencyNode` is encountered again via a different parent path, a `Path` entry is still created for it (so all occurrences appear in the conflict partition for winner selection), but its subtree is **not re-traversed**. If the same node is later reached at a shallower depth, it is re-expanded and the recorded minimum is updated.
   
   **2. Remove per-Path `HashSet` copy** (CPU/memory fix):  
   The `HashSet<String> conflictIdsOnPath` that was copied on every `Path` construction is dropped. Since expansion deduplication already bounds total path count to O(graph edges), the O(depth) parent-chain walk for `hasConflictIdOnPathToRoot` is sufficient and cheaper. This also eliminates the per-node allocation that was identified as a JFR hotspot in the prior PR #2075.
   
   ## Testing
   
   - All 452 existing `maven-resolver-util` tests pass
   - The 813-module reproducer that previously OOMed with 512m heap now completes in ~20s
   - Both `path` and `classic` resolvers produce identical results on the reproducer
   
   _Hermes Agent (Claude Sonnet 4.6) 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] Fix PathConflictResolver OOM on dense dependency graphs [maven-resolver]

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


-- 
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 PathConflictResolver OOM on dense dependency graphs [maven-resolver]

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


##########
maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictResolverTest.java:
##########
@@ -879,6 +879,75 @@ private static DependencyNode makeDependencyNode(
         return node;
     }
 
+    /**
+     * Regression test for exponential Path creation (OOM) in dense dependency graphs.
+     * <p>
+     * Constructs a graph where N hub nodes are each reachable via M distinct parent paths:
+     * <pre>
+     *   root → p0, p1, … p(M-1)          (M parent modules)
+     *   each pi → hub0, hub1, … hub(N-1)  (N shared hub modules)
+     * </pre>
+     * Without the {@code expandedNodes} guard in {@link PathConflictResolver}, each hub node
+     * would be expanded M times, causing exponential Path creation and OutOfMemoryError.
+     * <p>
+     * The test also verifies that {@link PathConflictResolver} produces the same resolution
+     * result as {@link ClassicConflictResolver} on this topology.
+     */
+    @ParameterizedTest
+    @MethodSource("conflictResolverSource")
+    void denseGraphDoesNotOom(ConflictResolver conflictResolver) throws RepositoryException {
+        // 20 parents × 20 hubs = 400 edges; each hub reachable via 20 paths.
+        // Without the fix this creates ~20^20 Paths and OOMs instantly.

Review Comment:
   ⚠️ **Test topology does not exercise the `expandedNodes` guard**
   
   The comment says "Without the fix this creates ~20^20 Paths and OOMs instantly" but the math is wrong for this topology, and more importantly: **the test would pass even if the `expandedNodes` guard were removed**.
   
   The guard is inside `if (!children.isEmpty())`:
   
   ```java
   if (!children.isEmpty()) {
       List<Path> added = node.addChildren(children);
       for (int i = added.size() - 1; i >= 0; i--) {
           Path child = added.get(i);
           Integer prevDepth = expandedNodes.get(child.dn);
           if (prevDepth == null || child.depth < prevDepth) {  // ← guard
               expandedNodes.put(child.dn, child.depth);
               stack.add(child);
           }
       }
   }
   ```
   
   Hub nodes (`hub-0` … `hub-19`) are leaf nodes — `getChildren()` returns empty — so the `if (!children.isEmpty())` block is never entered for them. The `expandedNodes` map is never consulted, and every hub Path is already in the partition via `addChildren`. Without the fix, 20 parents × 20 hubs = 400 Path objects (linear, not `20^20`), which would not OOM with any reasonable heap.
   
   A test that actually validates the guard needs hub nodes that **have their own shared children**. Example:
   
   ```java
   // Add shared sub-hubs as children of each hub
   List<DependencyNode> subHubs = new ArrayList<>(K);
   for (int s = 0; s < K; s++) {
       subHubs.add(makeDependencyNode("test", "sub-hub-" + s, "1.0"));
   }
   for (DependencyNode hub : hubs) {
       hub.setChildren(new ArrayList<>(subHubs)); // shared instances
   }
   ```
   
   With M=20 parents, N=20 hubs, K=20 sub-hubs, each sharing instances:
   - Without fix: 20 parents push 20 hubs → each hub pushes 20 sub-hubs → 20×20×20=8,000 sub-hub expansion entries on stack. The guard prevents re-pushing hubs and sub-hubs at equal-or-deeper depth — demonstrating actual exponential bounding.
   
   Also fix the comment: with 2-level topology it is not `20^20` paths — that would require 20 levels of shared recursion. With the proposed 3-level topology above, without the fix you get 400 stack pushes for hubs and 8,000 for sub-hubs.



-- 
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 PathConflictResolver OOM on dense dependency graphs [maven-resolver]

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


##########
maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictResolverTest.java:
##########
@@ -879,6 +879,88 @@ private static DependencyNode makeDependencyNode(
         return node;
     }
 
+    /**
+     * Regression test for exponential Path creation (OOM) in dense dependency graphs.
+     * <p>
+     * Constructs a 3-level graph where hub nodes (which have their own shared children)
+     * are each reachable via M distinct parent paths:
+     * <pre>
+     *   root → p0, p1, … p(M-1)              (M parent modules)
+     *   each pi → hub0, hub1, … hub(N-1)      (N shared hub nodes, with children)
+     *   each hub → sub0, sub1, … sub(K-1)     (K shared sub-hub leaf nodes)
+     * </pre>
+     * Without the {@code expandedNodes} guard in {@link PathConflictResolver#gatherCRNodes},
+     * each hub node would be pushed onto the expansion stack M times (once per parent),
+     * causing its K sub-hubs to be expanded M times each — M×N×K stack entries instead of N+K.
+     * With M=N=K=20 that is 20×20×20=8,000 redundant expansions for sub-hubs alone, and
+     * grows polynomially with more levels. The guard prevents this by skipping re-expansion
+     * of a node already expanded at the same or shallower depth.
+     */
+    @ParameterizedTest
+    @MethodSource("conflictResolverSource")
+    void denseGraphDoesNotOom(ConflictResolver conflictResolver) throws RepositoryException {

Review Comment:
   ⚠️ **Test parameters too small to detect OOM regression**
   
   The 3-level topology is now correct — hubs have children, so the `expandedNodes` guard is actually exercised. But with `M=N=K=20`, the pathological case without the guard produces at most `M×N = 400` hub-expansion stack entries and `M×N×K = 8,000` sub-hub entries. That's trivially fast and uses negligible memory. If someone removes the `expandedNodes` guard tomorrow, this test still passes — it only validates correctness (all nodes survive), not the memory bound.
   
   To make this a genuine regression guard, either bump the parameters so the un-fixed path is slow/OOM on CI heap, or assert on a proxy for expansion count (e.g. a counter injected into `gatherCRNodes`, or a `@Timeout` that would expire on the pathological case). A practical approach:
   
   ```suggestion
           int M = 50; // parent modules
           int N = 50; // hub modules (shared, each with children)
           int K = 50; // sub-hub leaf modules (shared across hubs)
   ```
   
   With `M=N=K=50`, without the fix: `50×50 = 2,500` hub expansions and `50×50×50 = 125,000` sub-hub stack entries — still not an OOM, but slow enough that adding a `@Timeout(value = 5, unit = TimeUnit.SECONDS)` would fail reliably. Alternatively, use a counter that asserts the fix's O(N+K) expansion bound:
   
   ```java
   // Assert expansion is bounded — without the fix this would be M*N*K
   assertTrue(expandedNodes.size() <= N + K, "expandedNodes grew beyond O(N+K)");
   ```
   
   (The `expandedNodes` field is `private` so this requires either package-private test access or a subclass hook — but the intent is clear.)



-- 
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 PathConflictResolver OOM on dense dependency graphs [maven-resolver]

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


##########
maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/PathConflictResolver.java:
##########
@@ -42,27 +41,24 @@
 import static java.util.Objects.requireNonNull;
 
 /**
- * A high-performance dependency graph transformer that resolves version and scope conflicts among dependencies.
- * This is the recommended conflict resolver implementation that provides O(N) performance characteristics,
- * significantly improving upon the O(N²) worst-case performance of {@link ClassicConflictResolver}.
+ * A dependency graph transformer that resolves version and scope conflicts among dependencies.
+ * This resolver builds a cycle-free parallel path tree from the dependency graph, then processes
+ * conflict groups in topologically sorted order to select winners.
  * <p>
  * For a given set of conflicting nodes, one node will be chosen as the winner. How losing nodes are handled
  * depends on the configured verbosity level: they may be removed entirely, have their children removed, or
  * be left in place with conflict information. The exact rules by which a winning node and its effective scope
  * are determined are controlled by user-supplied implementations of {@link ConflictResolver.VersionSelector}, {@link ConflictResolver.ScopeSelector},
  * {@link ConflictResolver.OptionalitySelector} and {@link ConflictResolver.ScopeDeriver}.
  * <p>
- * <strong>Performance Characteristics:</strong>
- * <ul>
- * <li><strong>Time Complexity:</strong> O(N) where N is the number of dependency nodes</li>
- * <li><strong>Memory Usage:</strong> Creates a parallel tree structure for conflict-free processing</li>
- * <li><strong>Scalability:</strong> Excellent performance on large multi-module projects</li>
- * </ul>
- * <p>
  * <strong>Algorithm Overview:</strong>
  * <ol>
  * <li><strong>Path Tree Construction:</strong> Builds a cycle-free parallel tree structure from the input
- *     dependency graph, where each {@code Path} represents a unique route to a dependency node</li>
+ *     dependency graph, where each {@code Path} represents a unique route to a dependency node.
+ *     To avoid exponential memory use in highly connected graphs, each {@link DependencyNode} instance
+ *     is expanded (its children recursively visited) at most once: when the same node is reached again

Review Comment:
   ⚠️ **Inaccurate Javadoc — 'at most once' is not guaranteed**
   
   The claim is wrong for DFS order. With an iterative DFS, consider:
   ```
   root → A → B → X (depth 3)   [A is processed first]
   root → C → X   (depth 2)     [C is processed later]
   ```
   In DFS, `X@depth3` is pushed and fully expanded (its children go on the stack) _before_ the DFS backtracks to process `C`. When `C → X@depth2` is discovered, `child.depth (2) < prevDepth (3)` is true, so X is pushed again and expanded a second time. Its subtree is traversed twice.
   
   The algorithm guarantees that the total number of expansions is bounded (proportional to graph edges, not exponential), but a single `DependencyNode` instance **can** be expanded more than once when a shallower occurrence is discovered after a deeper one. The same inaccuracy appears at line 359 (same phrase in `gatherCRNodes` Javadoc) and in the `expandedNodes` field Javadoc.
   
   Suggested fix: replace "at most once" with language that accurately describes the bound:
   ```suggestion
    *     To avoid exponential memory use in highly connected graphs, subtree expansion of each
    *     {@link DependencyNode} instance is bounded: when the same node is reached again via a
    *     different parent path, a {@code Path} entry is still created for it (so all occurrences
    *     appear in the conflict partition), but its subtree is only re-traversed if reached at a
    *     strictly shallower depth than before.
   ```



##########
maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/PathConflictResolver.java:
##########
@@ -334,6 +335,7 @@ private State(
             this.partitions = new HashMap<>(conflictIdCount * 4 / 3 + 1);
             this.resolvedIds = new HashMap<>(conflictIdCount * 4 / 3 + 1);
             this.scopeContext = new ScopeContext(null, null);
+            this.expandedNodes = new IdentityHashMap<>(conflictIdCount * 4 / 3 + 1);

Review Comment:
   ⚠️ **Wrong initial capacity hint for `expandedNodes`**
   
   `conflictIdCount` is the number of unique conflict IDs (unique `groupId:artifactId:classifier:extension` tuples). `expandedNodes` stores one entry per unique `DependencyNode` **instance**, which in a dense reactor (the exact scenario this PR fixes) can be 5–50× larger than the number of distinct artifacts. This causes repeated resizes of the `IdentityHashMap` precisely on the large-graph inputs you're trying to optimize.
   
   For `partitions` and `resolvedIds`, `conflictIdCount` is the right hint (one entry per conflict ID). For `expandedNodes`, consider using the actual node count or simply the default capacity — the resize cost is minor compared to the OOM it prevents, but the comment on line 334 (`"conflictIdCount gives exact number of partitions and resolved entries"`) makes the intent clear and `expandedNodes` should not reuse it.
   
   ```suggestion
               this.expandedNodes = new IdentityHashMap<>();
   ```



##########
maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/PathConflictResolver.java:
##########
@@ -353,6 +355,12 @@ private Path build(DependencyNode node) throws RepositoryException {
          * Iteratively builds {@link Path} graph by observing each node associated {@link DependencyNode}.
          * Uses an explicit stack instead of recursion to avoid {@link StackOverflowError} on very deep
          * dependency graphs (reported in large multi-module projects with 13+ levels of recursion).
+         * <p>
+         * Each {@link DependencyNode} instance is expanded (its children visited) at most once.
+         * When the same node is reached again via a different parent path, a {@link Path} entry is
+         * still created for it (so all occurrences appear in the conflict partition for winner selection),
+         * but the subtree below it is not re-traversed. This prevents exponential {@link Path} creation
+         * in highly connected graphs (e.g. a 813-module reactor where each module depends on ~9 others).

Review Comment:
   ⚠️ **Missing regression test for the dense-graph OOM scenario**
   
   The PR body describes a concrete reproducer (813-module reactor, `OutOfMemoryError` with `-Xmx512m`) but no test is added. Without a test, this can silently regress — the condition that triggered the OOM is a specific graph topology that the existing 452 tests don't cover.
   
   A parameterised JUnit test that constructs a dense diamond graph (e.g., N hub nodes each reachable via M parent paths) and asserts both that it completes without error and that it produces the same resolution result as `ClassicConflictResolver` would lock in this fix.



-- 
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