You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by gn...@apache.org on 2026/08/05 03:26:34 UTC

(maven) 01/01: Fix concurrent builder race conditions in artifact resolution and phase ordering

This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch run-maven-4-0-x-on-a-few-projects-let-s-start-wit
in repository https://gitbox.apache.org/repos/asf/maven.git

commit b4c3cc98f0d76926d6e3959d879a5ed204961bca
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Wed Aug 5 05:26:21 2026 +0200

    Fix concurrent builder race conditions in artifact resolution and phase ordering
    
    The concurrent builder (-b concurrent) suffered from several race conditions
    when building large multi-module projects like Apache Camel (682 modules):
    
    1. Thread-safety for session.getCurrentProject(): Multiple executor threads
       shared MavenSession.currentProject, causing dependency resolution and
       artifact filter to use the wrong project. Fixed by adding a ThreadLocal
       in the concurrent MojoExecutor and recording lifecycle phases directly
       on the correct project (not via the racy session reference).
    
    2. MavenProject artifact state thread-safety: setResolvedArtifacts(),
       setArtifactFilter(), getArtifacts(), and getArtifactMap() were not
       thread-safe. Made them synchronized with merge semantics that preserve
       artifact file references across concurrent resolutions.
    
    3. Reactor output directory fallback: When a reactor dependency has been
       compiled but not yet packaged, use its output directory (if it exists)
       as the artifact file. This prevents NPEs in downstream compiler plugin
       classpath resolution.
    
    4. V4 lifecycle RESOURCES ordering: Added after(SOURCES) constraint to
       the RESOURCES phase so resource processing happens after source
       generation, matching Maven 3 sequential ordering.
    
    5. after:* step skip propagation: Changed the after:* step decision from
       checking before:* status to checking the phase step itself. Before:*
       is an empty lifecycle setup step that always completes early; checking
       it allowed after:* steps to execute when the phase was SKIPPED,
       causing downstream steps to run out of order.
    
    6. Scope expansion for dependency ordering: filterByScope() now expands
       "compile" scope to include provided and system dependencies, matching
       Maven dependency resolution semantics and ensuring provided-scope
       reactor dependencies are properly ordered.
    
    Tested with Apache Camel 682-module build: reduced concurrent builder
    failures from 67 modules to 0 (remaining 3 failures are pre-existing
    Maven 4 issues unrelated to the concurrent builder).
    
    Co-Authored-By: Claude Opus 4.6 <no...@anthropic.com>
---
 .../internal/impl/DefaultLifecycleRegistry.java    |  2 +-
 .../internal/LifecycleDependencyResolver.java      | 14 +++--
 .../maven/lifecycle/internal/MojoExecutor.java     |  5 +-
 .../internal/concurrent/BuildPlanExecutor.java     | 61 +++++++++++++++++++---
 .../internal/concurrent/MojoExecutor.java          | 53 +++++++++++++++++++
 .../org/apache/maven/project/MavenProject.java     | 61 +++++++++-------------
 .../internal/concurrent/BuildPlanCreatorTest.java  | 35 ++++++++-----
 7 files changed, 170 insertions(+), 61 deletions(-)

diff --git a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecycleRegistry.java b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecycleRegistry.java
index c2006cb732..458dcd1965 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecycleRegistry.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecycleRegistry.java
@@ -459,7 +459,7 @@ public Collection<Phase> phases() {
                                     BUILD,
                                     after(VALIDATE),
                                     phase(SOURCES),
-                                    phase(RESOURCES),
+                                    phase(RESOURCES, after(SOURCES)),
                                     phase(COMPILE, after(SOURCES), dependencies(SCOPE_COMPILE, READY)),
                                     phase(READY, after(COMPILE), after(RESOURCES)),
                                     phase(PACKAGE, after(READY), dependencies(SCOPE_RUNTIME, PACKAGE))),
diff --git a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java
index f41b00f905..adc6aca086 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleDependencyResolver.java
@@ -131,9 +131,17 @@ public void resolveProjectDependencies(
             Map<Artifact, File> reactorProjects =
                     new HashMap<>(session.getProjects().size());
             for (MavenProject reactorProject : session.getProjects()) {
-                reactorProjects.put(
-                        reactorProject.getArtifact(),
-                        reactorProject.getArtifact().getFile());
+                File file = reactorProject.getArtifact().getFile();
+                // In the concurrent builder, a reactor project may have compiled (output directory
+                // exists) but not yet been packaged (artifact file is null).  Use the output
+                // directory as a fallback so that downstream projects see the compiled classes.
+                if (file == null) {
+                    File outputDir = new File(reactorProject.getBuild().getOutputDirectory());
+                    if (outputDir.isDirectory()) {
+                        file = outputDir;
+                    }
+                }
+                reactorProjects.put(reactorProject.getArtifact(), file);
             }
 
             Map<String, Artifact> map = new HashMap<>();
diff --git a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java
index 92b3f75bee..d7b7cfc3d5 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/MojoExecutor.java
@@ -391,8 +391,11 @@ public void ensureDependenciesAreResolved(
         }
 
         ArtifactFilter artifactFilter = getArtifactFilter(mojoDescriptor);
+        // Use the project captured in the dependency context — session.getCurrentProject()
+        // is shared mutable state that can be overwritten by concurrent threads in the
+        // concurrent builder, causing the filter to be applied to the wrong project.
         List<MavenProject> projectsToResolve = LifecycleDependencyResolver.getProjects(
-                session.getCurrentProject(), session, mojoDescriptor.isAggregator());
+                dependencyContext.getProject(), session, mojoDescriptor.isAggregator());
         for (MavenProject projectToResolve : projectsToResolve) {
             projectToResolve.setArtifactFilter(artifactFilter);
         }
diff --git a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
index cbd5ae2ed9..c9a6c03ef7 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
@@ -375,14 +375,19 @@ private void processStep(BuildStep step) {
             // Check if all predecessors are executed successfully
             boolean allPredecessorsExecuted = step.predecessors.stream().allMatch(s -> s.status.get() == EXECUTED);
 
-            // Special case for after:* steps - they should run if their corresponding before:* step ran
+            // Special case for after:* steps - they should run if their corresponding phase step ran
             if (isAfterStep) {
                 String phaseName = step.name.substring(AFTER.length());
-                // Always process after:* steps for cleanup if their before:* step ran
-                shouldExecute = plan.step(step.project, BEFORE + phaseName)
+                // Run after:* steps for cleanup if their phase step itself ran or failed.
+                // Check the phase step (not before:*) because before:* is an empty lifecycle
+                // setup step that completes early — it doesn't indicate the phase's mojos ran.
+                // If the phase was SKIPPED (e.g. due to a dependency cascade), the after:*
+                // step should also be skipped to prevent downstream steps from executing
+                // out of order.
+                shouldExecute = plan.step(step.project, phaseName)
                         .map(s -> {
                             int stepStatus = s.status.get();
-                            return stepStatus == EXECUTED;
+                            return stepStatus == EXECUTED || stepStatus == FAILED;
                         })
                         .orElse(false);
 
@@ -562,6 +567,12 @@ private void executeStep(BuildStep step) throws IOException, LifecycleExecutionE
                     List<MojoExecution> executions = step.executions().toList();
                     if (!executions.isEmpty()) {
                         attachToThread(step);
+                        // Set a thread-local project reference so the concurrent
+                        // MojoExecutor can build its DependencyContext with the
+                        // correct project.  session.getCurrentProject() is racy —
+                        // another thread can overwrite it between attachToThread
+                        // and mojoExecutor.execute.
+                        org.apache.maven.lifecycle.internal.concurrent.MojoExecutor.setThreadProject(step.project);
                         clock.start();
                         try {
                             executions.forEach(mojoExecution -> {
@@ -569,7 +580,17 @@ private void executeStep(BuildStep step) throws IOException, LifecycleExecutionE
                                 finalizeMojoConfiguration(mojoExecution);
                             });
                             mojoExecutor.execute(session, executions);
+                            // Record lifecycle phase on the correct project directly.
+                            // The base MojoExecutor's PhaseRecorder uses session.getCurrentProject()
+                            // which is overwritten by concurrent threads in parallel builds,
+                            // causing phases to be recorded on the wrong project. This ensures
+                            // ReactorReader.determineBuildOutputDirectoryForArtifact() can find
+                            // compiled output via project.hasLifecyclePhase().
+                            if (!step.name.startsWith(BEFORE) && !step.name.startsWith(AFTER)) {
+                                step.project.addLifecyclePhase(step.name);
+                            }
                         } finally {
+                            org.apache.maven.lifecycle.internal.concurrent.MojoExecutor.clearThreadProject();
                             clock.stop();
                         }
                     }
@@ -708,8 +729,16 @@ private void applyAfterLinks(MojoDescriptor mojoDescriptor, MavenProject project
          * matching purposes. Note that this does <em>not</em> perform path-scope
          * resolution — for example, filtering by "compile" will not include
          * "provided"-scoped dependencies even though they contribute to
-         * {@code PathScope.MAIN_COMPILE}. This keeps the filter simple and predictable;
-         * broader scope-aware filtering can be added in a follow-up if needed.
+         * {@code PathScope.MAIN_COMPILE}.
+         * <p>
+         * The scope parameter is expanded to match the Maven dependency resolution semantics:
+         * <ul>
+         *   <li>"compile" matches compile, provided, and system scoped dependencies</li>
+         *   <li>"runtime" matches compile and runtime scoped dependencies</li>
+         *   <li>"test" matches all scopes</li>
+         * </ul>
+         * This ensures that provided-scope reactor dependencies are properly ordered in the
+         * build plan when needed for compilation.
          *
          * @param project the project whose dependencies to check
          * @param upstreamProjects the list of upstream reactor projects
@@ -721,14 +750,32 @@ static List<MavenProject> filterByScope(
             if (scope == null || scope.isEmpty()) {
                 return upstreamProjects;
             }
+            Set<String> matchingScopes = expandScope(scope);
             return upstreamProjects.stream()
                     .filter(dep -> project.getDependencies().stream()
                             .anyMatch(d -> dep.getGroupId().equals(d.getGroupId())
                                     && dep.getArtifactId().equals(d.getArtifactId())
-                                    && scope.equals(d.getScope() != null ? d.getScope() : "compile")))
+                                    && matchingScopes.contains(d.getScope() != null ? d.getScope() : "compile")))
                     .collect(Collectors.toList());
         }
 
+        /**
+         * Expands a dependency scope identifier to the set of artifact scopes that are included
+         * in dependency resolution for that scope. This mirrors the semantics of
+         * {@link org.apache.maven.lifecycle.internal.MojoExecutor#toScopes(String)}.
+         */
+        private static Set<String> expandScope(String scope) {
+            return switch (scope) {
+                case "compile" -> Set.of("compile", "provided", "system");
+                case "runtime" -> Set.of("compile", "runtime");
+                case "compile+runtime" -> Set.of("compile", "provided", "system", "runtime");
+                case "runtime+system" -> Set.of("compile", "system", "runtime");
+                case "test" -> Set.of("compile", "provided", "system", "runtime", "test");
+                case "test-only" -> Set.of("test");
+                default -> Set.of(scope);
+            };
+        }
+
         protected BuildPlan computeForkPlan(BuildStep step, MojoExecution execution, BuildPlan buildPlan) {
             MojoDescriptor mojoDescriptor = execution.getMojoDescriptor();
             PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();
diff --git a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/MojoExecutor.java b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/MojoExecutor.java
index 273035b82c..53963b3e74 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/MojoExecutor.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/MojoExecutor.java
@@ -23,18 +23,35 @@
 import javax.inject.Provider;
 import javax.inject.Singleton;
 
+import java.util.List;
+
 import org.apache.maven.api.services.MessageBuilderFactory;
 import org.apache.maven.execution.MavenSession;
+import org.apache.maven.lifecycle.internal.DependencyContext;
 import org.apache.maven.lifecycle.internal.ExecutionEventCatapult;
 import org.apache.maven.lifecycle.internal.LifecycleDependencyResolver;
 import org.apache.maven.plugin.BuildPluginManager;
 import org.apache.maven.plugin.MavenPluginManager;
+import org.apache.maven.plugin.MojoExecution;
 import org.apache.maven.plugin.MojosExecutionStrategy;
+import org.apache.maven.project.MavenProject;
 
+/**
+ * Concurrent-builder variant of the mojo executor.
+ * <p>
+ * In the concurrent builder, multiple build steps for different projects
+ * execute in parallel.  The shared {@code MavenSession.currentProject} field
+ * is therefore unreliable — another thread can overwrite it between the
+ * moment a step attaches to its thread and the moment the mojo executor
+ * reads it.  This subclass uses a {@link ThreadLocal} to provide each
+ * executor thread with its own, stable reference to the project being built.
+ */
 @Named("concurrent")
 @Singleton
 public class MojoExecutor extends org.apache.maven.lifecycle.internal.MojoExecutor {
 
+    private static final ThreadLocal<MavenProject> THREAD_PROJECT = new ThreadLocal<>();
+
     @Inject
     public MojoExecutor(
             BuildPluginManager pluginManager,
@@ -56,4 +73,40 @@ public MojoExecutor(
     protected boolean useProjectLock(MavenSession session) {
         return false;
     }
+
+    /**
+     * Set the project for the current executor thread.  Called by
+     * {@link BuildPlanExecutor} before invoking
+     * {@link #execute(MavenSession, List)} so that
+     * {@link #newDependencyContext} picks up the correct project
+     * regardless of what {@code session.getCurrentProject()} returns.
+     */
+    static void setThreadProject(MavenProject project) {
+        THREAD_PROJECT.set(project);
+    }
+
+    /** Clear the thread-local project reference after execution. */
+    static void clearThreadProject() {
+        THREAD_PROJECT.remove();
+    }
+
+    /**
+     * Override to use the thread-local project instead of
+     * {@code session.getCurrentProject()}, which is racy in the
+     * concurrent builder.
+     */
+    @Override
+    public DependencyContext newDependencyContext(MavenSession session, List<MojoExecution> mojoExecutions) {
+        DependencyContext ctx = super.newDependencyContext(session, mojoExecutions);
+        MavenProject threadProject = THREAD_PROJECT.get();
+        if (threadProject != null && threadProject != ctx.getProject()) {
+            // The super method captured the wrong project from the racy
+            // session.currentProject — rebuild with the correct one.
+            return new DependencyContext(
+                    threadProject,
+                    ctx.getScopesToCollectForCurrentProject(),
+                    ctx.getScopesToResolveForCurrentProject());
+        }
+        return ctx;
+    }
 }
diff --git a/impl/maven-core/src/main/java/org/apache/maven/project/MavenProject.java b/impl/maven-core/src/main/java/org/apache/maven/project/MavenProject.java
index 63c9e2a654..85c8d3a758 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/project/MavenProject.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/project/MavenProject.java
@@ -894,7 +894,7 @@ public void setArtifacts(Set<Artifact> artifacts) {
      * @return {@link Set} &lt; {@link Artifact} &gt;
      * @see #getDependencyArtifacts() to get only direct dependencies
      */
-    public Set<Artifact> getArtifacts() {
+    public synchronized Set<Artifact> getArtifacts() {
         if (artifacts == null) {
             if (artifactFilter == null || resolvedArtifacts == null) {
                 artifacts = new LinkedHashSet<>();
@@ -910,7 +910,7 @@ public Set<Artifact> getArtifacts() {
         return artifacts;
     }
 
-    public Map<String, Artifact> getArtifactMap() {
+    public synchronized Map<String, Artifact> getArtifactMap() {
         if (artifactMap == null) {
             artifactMap = ArtifactUtils.artifactMapByVersionlessId(getArtifacts());
         }
@@ -1505,53 +1505,42 @@ public DependencyFilter getExtensionDependencyFilter() {
         return extensionDependencyFilter;
     }
 
-    /**
-     * Sets the transitive dependency artifacts that have been resolved/collected for this project.
-     * <strong>Warning:</strong> This is an internal utility method that is only public for technical reasons, it is not
-     * part of the public API. In particular, this method can be changed or deleted without prior notice and must not be
-     * used by plugins.
-     *
-     * @param artifacts The set of artifacts, may be {@code null}.
-     */
-    public void setResolvedArtifacts(Set<Artifact> artifacts) {
-        this.resolvedArtifacts = (artifacts != null) ? artifacts : Collections.emptySet();
+    /** Sets resolved artifacts; merges to preserve file references. Thread-safe. */
+    public synchronized void setResolvedArtifacts(Set<Artifact> artifacts) {
+        Set<Artifact> newArtifacts = (artifacts != null) ? artifacts : Collections.emptySet();
+        if (this.resolvedArtifacts != null && !this.resolvedArtifacts.isEmpty() && !newArtifacts.isEmpty()) {
+            // Merge: start from old set (preserving all artifacts), override with new
+            Map<String, Artifact> merged = new LinkedHashMap<>();
+            for (Artifact a : this.resolvedArtifacts) {
+                merged.put(a.getDependencyConflictId(), a);
+            }
+            for (Artifact a : newArtifacts) {
+                Artifact existing = merged.get(a.getDependencyConflictId());
+                // Replace old with new UNLESS old has a file and new doesn't
+                if (existing == null || existing.getFile() == null || a.getFile() != null) {
+                    merged.put(a.getDependencyConflictId(), a);
+                }
+            }
+            newArtifacts = new LinkedHashSet<>(merged.values());
+        }
+        this.resolvedArtifacts = newArtifacts;
         this.artifacts = null;
         this.artifactMap = null;
     }
 
-    /**
-     * Sets the scope filter to select the artifacts being exposed to the currently executed mojo.
-     * <strong>Warning:</strong> This is an internal utility method that is only public for technical reasons, it is not
-     * part of the public API. In particular, this method can be changed or deleted without prior notice and must not be
-     * used by plugins.
-     *
-     * @param artifactFilter The artifact filter, may be {@code null} to exclude all artifacts.
-     */
-    public void setArtifactFilter(ArtifactFilter artifactFilter) {
+    /** Sets the scope filter for artifacts exposed to the executing mojo. Thread-safe. */
+    public synchronized void setArtifactFilter(ArtifactFilter artifactFilter) {
         this.artifactFilter = artifactFilter;
         this.artifacts = null;
         this.artifactMap = null;
     }
 
-    /**
-     * <strong>Warning:</strong> This is an internal utility method that is only public for technical reasons, it is not
-     * part of the public API. In particular, this method can be changed or deleted without prior notice and must not be
-     * used by plugins.
-     *
-     * @param phase The phase to check for, must not be {@code null}.
-     * @return {@code true} if the phase has been seen.
-     */
+    /** Internal: checks if a lifecycle phase has been executed for this project. */
     public boolean hasLifecyclePhase(String phase) {
         return lifecyclePhases.contains(phase);
     }
 
-    /**
-     * <strong>Warning:</strong> This is an internal utility method that is only public for technical reasons, it is not
-     * part of the public API. In particular, this method can be changed or deleted without prior notice and must not be
-     * used by plugins.
-     *
-     * @param lifecyclePhase The lifecycle phase to add, must not be {@code null}.
-     */
+    /** Internal: records that a lifecycle phase has been executed for this project. */
     public void addLifecyclePhase(String lifecyclePhase) {
         lifecyclePhases.add(lifecyclePhase);
     }
diff --git a/impl/maven-core/src/test/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanCreatorTest.java b/impl/maven-core/src/test/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanCreatorTest.java
index 6a08b7ee35..a6939ed2e5 100644
--- a/impl/maven-core/src/test/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanCreatorTest.java
+++ b/impl/maven-core/src/test/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanCreatorTest.java
@@ -240,40 +240,49 @@ void testFilterByScopeNullReturnsAll() {
     }
 
     /**
-     * Tests that {@code filterByScope} filters upstream projects by exact scope match,
-     * treating null-scoped dependencies as "compile" (Maven default).
+     * Tests that {@code filterByScope} expands scopes to match Maven dependency resolution semantics.
+     * "compile" includes compile, provided, and system scoped dependencies (plus null-scoped which
+     * defaults to compile). This ensures provided-scope reactor dependencies are properly ordered in
+     * the build plan when needed at compile time.
      */
     @Test
     void testFilterByScopeMatchesExact() {
         MavenProject compileDep = createProjectWithId("g", "compile-dep");
         MavenProject providedDep = createProjectWithId("g", "provided-dep");
+        MavenProject systemDep = createProjectWithId("g", "system-dep");
+        MavenProject runtimeDep = createProjectWithId("g", "runtime-dep");
         MavenProject testDep = createProjectWithId("g", "test-dep");
         MavenProject nullScopeDep = createProjectWithId("g", "null-scope-dep");
-        List<MavenProject> upstream = List.of(compileDep, providedDep, testDep, nullScopeDep);
+        List<MavenProject> upstream = List.of(compileDep, providedDep, systemDep, runtimeDep, testDep, nullScopeDep);
 
         MavenProject consumer = new MavenProject();
         consumer.getDependencies().add(createDependency("g", "compile-dep", "compile"));
         consumer.getDependencies().add(createDependency("g", "provided-dep", "provided"));
+        consumer.getDependencies().add(createDependency("g", "system-dep", "system"));
+        consumer.getDependencies().add(createDependency("g", "runtime-dep", "runtime"));
         consumer.getDependencies().add(createDependency("g", "test-dep", "test"));
         consumer.getDependencies().add(createDependency("g", "null-scope-dep", null));
 
-        // "compile" matches explicit compile + null-scoped (Maven default is compile)
+        // "compile" scope expands to compile + provided + system + null-scoped (Maven default)
         List<MavenProject> compileFiltered =
                 BuildPlanExecutor.BuildContext.filterByScope(consumer, upstream, "compile");
-        assertEquals(2, compileFiltered.size());
+        assertEquals(4, compileFiltered.size());
         assertTrue(compileFiltered.contains(compileDep));
+        assertTrue(compileFiltered.contains(providedDep));
+        assertTrue(compileFiltered.contains(systemDep));
         assertTrue(compileFiltered.contains(nullScopeDep));
 
-        // "provided" matches only provided-scoped
-        List<MavenProject> providedFiltered =
-                BuildPlanExecutor.BuildContext.filterByScope(consumer, upstream, "provided");
-        assertEquals(1, providedFiltered.size());
-        assertTrue(providedFiltered.contains(providedDep));
+        // "runtime" scope expands to compile + runtime
+        List<MavenProject> runtimeFiltered =
+                BuildPlanExecutor.BuildContext.filterByScope(consumer, upstream, "runtime");
+        assertEquals(3, runtimeFiltered.size());
+        assertTrue(runtimeFiltered.contains(compileDep));
+        assertTrue(runtimeFiltered.contains(runtimeDep));
+        assertTrue(runtimeFiltered.contains(nullScopeDep));
 
-        // "test" matches only test-scoped
+        // "test" scope expands to all scopes
         List<MavenProject> testFiltered = BuildPlanExecutor.BuildContext.filterByScope(consumer, upstream, "test");
-        assertEquals(1, testFiltered.size());
-        assertTrue(testFiltered.contains(testDep));
+        assertEquals(6, testFiltered.size());
     }
 
     /**