View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.impl.model;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.nio.file.Files;
25  import java.nio.file.Path;
26  import java.nio.file.Paths;
27  import java.util.ArrayList;
28  import java.util.Arrays;
29  import java.util.Collection;
30  import java.util.HashMap;
31  import java.util.HashSet;
32  import java.util.Iterator;
33  import java.util.LinkedHashMap;
34  import java.util.LinkedHashSet;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.Objects;
38  import java.util.Set;
39  import java.util.concurrent.ConcurrentHashMap;
40  import java.util.concurrent.CopyOnWriteArrayList;
41  import java.util.concurrent.Executor;
42  import java.util.concurrent.Executors;
43  import java.util.concurrent.atomic.AtomicReference;
44  import java.util.function.BiFunction;
45  import java.util.function.Supplier;
46  import java.util.function.UnaryOperator;
47  import java.util.stream.Collectors;
48  import java.util.stream.Stream;
49  
50  import org.apache.maven.api.Constants;
51  import org.apache.maven.api.RemoteRepository;
52  import org.apache.maven.api.Session;
53  import org.apache.maven.api.Type;
54  import org.apache.maven.api.VersionRange;
55  import org.apache.maven.api.annotations.Nonnull;
56  import org.apache.maven.api.annotations.Nullable;
57  import org.apache.maven.api.cache.CacheMetadata;
58  import org.apache.maven.api.cache.CacheRetention;
59  import org.apache.maven.api.di.Inject;
60  import org.apache.maven.api.di.Named;
61  import org.apache.maven.api.di.Singleton;
62  import org.apache.maven.api.feature.Features;
63  import org.apache.maven.api.model.Activation;
64  import org.apache.maven.api.model.Dependency;
65  import org.apache.maven.api.model.DependencyManagement;
66  import org.apache.maven.api.model.DeploymentRepository;
67  import org.apache.maven.api.model.DistributionManagement;
68  import org.apache.maven.api.model.Exclusion;
69  import org.apache.maven.api.model.InputLocation;
70  import org.apache.maven.api.model.Model;
71  import org.apache.maven.api.model.Parent;
72  import org.apache.maven.api.model.Profile;
73  import org.apache.maven.api.model.Repository;
74  import org.apache.maven.api.services.BuilderProblem;
75  import org.apache.maven.api.services.BuilderProblem.Severity;
76  import org.apache.maven.api.services.Interpolator;
77  import org.apache.maven.api.services.MavenException;
78  import org.apache.maven.api.services.ModelBuilder;
79  import org.apache.maven.api.services.ModelBuilderException;
80  import org.apache.maven.api.services.ModelBuilderRequest;
81  import org.apache.maven.api.services.ModelBuilderResult;
82  import org.apache.maven.api.services.ModelProblem;
83  import org.apache.maven.api.services.ModelProblem.Version;
84  import org.apache.maven.api.services.ModelProblemCollector;
85  import org.apache.maven.api.services.ModelSource;
86  import org.apache.maven.api.services.ProblemCollector;
87  import org.apache.maven.api.services.RepositoryFactory;
88  import org.apache.maven.api.services.Request;
89  import org.apache.maven.api.services.RequestTrace;
90  import org.apache.maven.api.services.Result;
91  import org.apache.maven.api.services.Source;
92  import org.apache.maven.api.services.Sources;
93  import org.apache.maven.api.services.SuperPomProvider;
94  import org.apache.maven.api.services.VersionParserException;
95  import org.apache.maven.api.services.model.DependencyManagementImporter;
96  import org.apache.maven.api.services.model.DependencyManagementInjector;
97  import org.apache.maven.api.services.model.InheritanceAssembler;
98  import org.apache.maven.api.services.model.ModelInterpolator;
99  import org.apache.maven.api.services.model.ModelNormalizer;
100 import org.apache.maven.api.services.model.ModelPathTranslator;
101 import org.apache.maven.api.services.model.ModelProcessor;
102 import org.apache.maven.api.services.model.ModelResolver;
103 import org.apache.maven.api.services.model.ModelResolverException;
104 import org.apache.maven.api.services.model.ModelUrlNormalizer;
105 import org.apache.maven.api.services.model.ModelValidator;
106 import org.apache.maven.api.services.model.ModelVersionParser;
107 import org.apache.maven.api.services.model.PathTranslator;
108 import org.apache.maven.api.services.model.PluginConfigurationExpander;
109 import org.apache.maven.api.services.model.PluginManagementInjector;
110 import org.apache.maven.api.services.model.ProfileActivationContext;
111 import org.apache.maven.api.services.model.ProfileInjector;
112 import org.apache.maven.api.services.model.ProfileSelector;
113 import org.apache.maven.api.services.model.RootLocator;
114 import org.apache.maven.api.services.xml.XmlReaderException;
115 import org.apache.maven.api.services.xml.XmlReaderRequest;
116 import org.apache.maven.api.spi.ModelParserException;
117 import org.apache.maven.api.spi.ModelTransformer;
118 import org.apache.maven.impl.DefaultRemoteRepository;
119 import org.apache.maven.impl.InternalSession;
120 import org.apache.maven.impl.RequestTraceHelper;
121 import org.apache.maven.impl.util.PhasingExecutor;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
124 
125 /**
126  * The model builder is responsible for building the {@link Model} from the POM file.
127  * There are two ways to main use cases: the first one is to build the model from a POM file
128  * on the file system in order to actually build the project. The second one is to build the
129  * model for a dependency  or an external parent.
130  */
131 @Named
132 @Singleton
133 public class DefaultModelBuilder implements ModelBuilder {
134 
135     public static final String NAMESPACE_PREFIX = "http://maven.apache.org/POM/";
136     private static final String RAW = "raw";
137     private static final String FILE = "file";
138     private static final String IMPORT = "import";
139     private static final String PARENT = "parent";
140     private static final String PARENT_EXTERNAL = "parent-external";
141     private static final String MODEL = "model";
142 
143     private final Logger logger = LoggerFactory.getLogger(getClass());
144 
145     private final ModelProcessor modelProcessor;
146     private final ModelValidator modelValidator;
147     private final ModelNormalizer modelNormalizer;
148     private final ModelInterpolator modelInterpolator;
149     private final ModelPathTranslator modelPathTranslator;
150     private final ModelUrlNormalizer modelUrlNormalizer;
151     private final SuperPomProvider superPomProvider;
152     private final InheritanceAssembler inheritanceAssembler;
153     private final ProfileSelector profileSelector;
154     private final ProfileInjector profileInjector;
155     private final PluginManagementInjector pluginManagementInjector;
156     private final DependencyManagementInjector dependencyManagementInjector;
157     private final DependencyManagementImporter dependencyManagementImporter;
158     private final PluginConfigurationExpander pluginConfigurationExpander;
159     private final ModelVersionParser versionParser;
160     private final List<ModelTransformer> transformers;
161     private final ModelResolver modelResolver;
162     private final Interpolator interpolator;
163     private final PathTranslator pathTranslator;
164     private final RootLocator rootLocator;
165 
166     @SuppressWarnings("checkstyle:ParameterNumber")
167     @Inject
168     public DefaultModelBuilder(
169             ModelProcessor modelProcessor,
170             ModelValidator modelValidator,
171             ModelNormalizer modelNormalizer,
172             ModelInterpolator modelInterpolator,
173             ModelPathTranslator modelPathTranslator,
174             ModelUrlNormalizer modelUrlNormalizer,
175             SuperPomProvider superPomProvider,
176             InheritanceAssembler inheritanceAssembler,
177             ProfileSelector profileSelector,
178             ProfileInjector profileInjector,
179             PluginManagementInjector pluginManagementInjector,
180             DependencyManagementInjector dependencyManagementInjector,
181             DependencyManagementImporter dependencyManagementImporter,
182             PluginConfigurationExpander pluginConfigurationExpander,
183             ModelVersionParser versionParser,
184             @Nullable List<ModelTransformer> transformers,
185             ModelResolver modelResolver,
186             Interpolator interpolator,
187             PathTranslator pathTranslator,
188             RootLocator rootLocator) {
189         this.modelProcessor = modelProcessor;
190         this.modelValidator = modelValidator;
191         this.modelNormalizer = modelNormalizer;
192         this.modelInterpolator = modelInterpolator;
193         this.modelPathTranslator = modelPathTranslator;
194         this.modelUrlNormalizer = modelUrlNormalizer;
195         this.superPomProvider = superPomProvider;
196         this.inheritanceAssembler = inheritanceAssembler;
197         this.profileSelector = profileSelector;
198         this.profileInjector = profileInjector;
199         this.pluginManagementInjector = pluginManagementInjector;
200         this.dependencyManagementInjector = dependencyManagementInjector;
201         this.dependencyManagementImporter = dependencyManagementImporter;
202         this.pluginConfigurationExpander = pluginConfigurationExpander;
203         this.versionParser = versionParser;
204         this.transformers = transformers;
205         this.modelResolver = modelResolver;
206         this.interpolator = interpolator;
207         this.pathTranslator = pathTranslator;
208         this.rootLocator = rootLocator;
209     }
210 
211     @Override
212     public ModelBuilderSession newSession() {
213         return new ModelBuilderSessionImpl();
214     }
215 
216     protected class ModelBuilderSessionImpl implements ModelBuilderSession {
217         ModelBuilderSessionState mainSession;
218 
219         /**
220          * Builds a model based on the provided ModelBuilderRequest.
221          *
222          * @param request The request containing the parameters for building the model.
223          * @return The result of the model building process.
224          * @throws ModelBuilderException If an error occurs during model building.
225          */
226         @Override
227         public ModelBuilderResult build(ModelBuilderRequest request) throws ModelBuilderException {
228             RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(request.getSession(), request);
229             try {
230                 // Create or derive a session based on the request
231                 ModelBuilderSessionState session;
232                 if (mainSession == null) {
233                     mainSession = new ModelBuilderSessionState(request);
234                     session = mainSession;
235                 } else {
236                     session = mainSession.deriveTopLevel(
237                             request,
238                             new DefaultModelBuilderResult(request, ProblemCollector.create(mainSession.session)));
239                 }
240                 // Build the request
241                 if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
242                     // build the build poms
243                     session.buildBuildPom();
244                 } else {
245                     // simply build the effective model
246                     session.buildEffectiveModel(new LinkedHashSet<>());
247                 }
248                 return session.result;
249             } finally {
250                 RequestTraceHelper.exit(trace);
251             }
252         }
253     }
254 
255     protected class ModelBuilderSessionState implements ModelProblemCollector {
256         final Session session;
257         final ModelBuilderRequest request;
258         final DefaultModelBuilderResult result;
259         final Graph dag;
260         final Map<GAKey, Set<ModelSource>> mappedSources;
261         final Set<ImportWarningKey> reportedImportWarnings;
262         final Map<String, ProblemCollector<ModelProblem>> reactorProblemCollectors;
263 
264         String source;
265         Model sourceModel;
266         Model rootModel;
267 
268         List<RemoteRepository> pomRepositories;
269         List<RemoteRepository> externalRepositories;
270         List<RemoteRepository> repositories;
271 
272         List<RemoteRepository> getRepositories() {
273             return repositories;
274         }
275 
276         List<RemoteRepository> getExternalRepositories() {
277             return externalRepositories;
278         }
279 
280         // Cycle detection chain shared across all derived sessions
281         // Contains both GAV coordinates (groupId:artifactId:version) and file paths
282         final Set<String> parentChain;
283 
284         // Sticky across derive(): true for a session that is itself resolving a dependency
285         // (ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY), or that was derived, directly
286         // or transitively, from such a session -- for instance a dependency's own parent POM.
287         // Kept separate from request.getRequestType() because a parent lookup always derives a
288         // CONSUMER_PARENT request regardless of what kind of session triggered it, which would
289         // otherwise lose the distinction this flag preserves.
290         final boolean externalOrigin;
291 
292         ModelBuilderSessionState(ModelBuilderRequest request) {
293             this(
294                     request.getSession(),
295                     request,
296                     new DefaultModelBuilderResult(request, ProblemCollector.create(request.getSession())),
297                     new Graph(),
298                     new ConcurrentHashMap<>(64),
299                     ConcurrentHashMap.newKeySet(),
300                     new ConcurrentHashMap<>(),
301                     List.of(),
302                     repos(request),
303                     repos(request),
304                     new LinkedHashSet<>(),
305                     isExternalOrigin(request));
306         }
307 
308         static List<RemoteRepository> repos(ModelBuilderRequest request) {
309             List<RemoteRepository> repos = request.getRepositories() != null
310                     ? request.getRepositories()
311                     : request.getSession().getRemoteRepositories();
312             return mergeRepositoriesById(repos);
313         }
314 
315         /**
316          * Merges repositories that share the same ID by combining their policies.
317          * This handles the case where mirror injection produces multiple repository
318          * entries with the same mirror ID but different snapshot/release policies
319          * (e.g., when both "central" and a profile-defined repo are mirrored to the
320          * same mirror, producing two entries with the mirror's ID but different policies).
321          * Without this merge, policy deduplication in the resolver can drop the snapshot
322          * policy, causing SNAPSHOT parent resolution to fail (MNG-12769).
323          */
324         private static List<RemoteRepository> mergeRepositoriesById(List<RemoteRepository> repos) {
325             if (repos.size() <= 1) {
326                 return List.copyOf(repos);
327             }
328             LinkedHashMap<String, RemoteRepository> byId = new LinkedHashMap<>();
329             boolean hasDuplicates = false;
330             for (RemoteRepository repo : repos) {
331                 RemoteRepository existing = byId.putIfAbsent(repo.getId(), repo);
332                 if (existing != null) {
333                     hasDuplicates = true;
334                     byId.put(repo.getId(), mergeRepositoryPolicies(existing, repo));
335                 }
336             }
337             return hasDuplicates ? List.copyOf(byId.values()) : List.copyOf(repos);
338         }
339 
340         /**
341          * Merges two repositories with the same ID by combining their policies.
342          * For each policy type (release/snapshot), the result is enabled if either
343          * input has it enabled. URL, proxy, authentication, and other properties
344          * are preserved from the dominant (first) repository.
345          */
346         private static RemoteRepository mergeRepositoryPolicies(RemoteRepository dominant, RemoteRepository recessive) {
347             if (dominant instanceof DefaultRemoteRepository d && recessive instanceof DefaultRemoteRepository r) {
348                 org.eclipse.aether.repository.RemoteRepository dr = d.getRepository();
349                 org.eclipse.aether.repository.RemoteRepository rr = r.getRepository();
350 
351                 boolean mergeSnapshots =
352                         rr.getPolicy(true).isEnabled() && !dr.getPolicy(true).isEnabled();
353                 boolean mergeReleases =
354                         rr.getPolicy(false).isEnabled() && !dr.getPolicy(false).isEnabled();
355 
356                 if (mergeSnapshots || mergeReleases) {
357                     org.eclipse.aether.repository.RemoteRepository.Builder builder =
358                             new org.eclipse.aether.repository.RemoteRepository.Builder(dr);
359                     if (mergeSnapshots) {
360                         builder.setSnapshotPolicy(rr.getPolicy(true));
361                     }
362                     if (mergeReleases) {
363                         builder.setReleasePolicy(rr.getPolicy(false));
364                     }
365                     return new DefaultRemoteRepository(builder.build());
366                 }
367             }
368             return dominant;
369         }
370 
371         @SuppressWarnings("checkstyle:ParameterNumber")
372         private ModelBuilderSessionState(
373                 Session session,
374                 ModelBuilderRequest request,
375                 DefaultModelBuilderResult result,
376                 Graph dag,
377                 Map<GAKey, Set<ModelSource>> mappedSources,
378                 Set<ImportWarningKey> reportedImportWarnings,
379                 Map<String, ProblemCollector<ModelProblem>> reactorProblemCollectors,
380                 List<RemoteRepository> pomRepositories,
381                 List<RemoteRepository> externalRepositories,
382                 List<RemoteRepository> repositories,
383                 Set<String> parentChain,
384                 boolean externalOrigin) {
385             this.session = session;
386             this.request = request;
387             this.result = result;
388             this.dag = dag;
389             this.mappedSources = mappedSources;
390             this.reportedImportWarnings = reportedImportWarnings;
391             this.reactorProblemCollectors = reactorProblemCollectors;
392             this.pomRepositories = pomRepositories;
393             this.externalRepositories = externalRepositories;
394             this.repositories = repositories;
395             this.parentChain = parentChain;
396             this.externalOrigin = externalOrigin;
397             this.result.setSource(this.request.getSource());
398         }
399 
400         ModelBuilderSessionState derive(ModelSource source) {
401             return derive(source, new DefaultModelBuilderResult(request, ProblemCollector.create(session)));
402         }
403 
404         ModelBuilderSessionState derive(ModelSource source, DefaultModelBuilderResult result) {
405             return derive(ModelBuilderRequest.build(request, source), result);
406         }
407 
408         /**
409          * Creates a new session, sharing cached datas and propagating errors.
410          */
411         ModelBuilderSessionState derive(ModelBuilderRequest request) {
412             return derive(request, new DefaultModelBuilderResult(request, ProblemCollector.create(session)));
413         }
414 
415         ModelBuilderSessionState derive(ModelBuilderRequest request, DefaultModelBuilderResult result) {
416             return derive(request, result, reportedImportWarnings, reactorProblemCollectors);
417         }
418 
419         ModelBuilderSessionState deriveTopLevel(ModelBuilderRequest request, DefaultModelBuilderResult result) {
420             return derive(request, result, ConcurrentHashMap.newKeySet(), new ConcurrentHashMap<>());
421         }
422 
423         private ModelBuilderSessionState derive(
424                 ModelBuilderRequest request,
425                 DefaultModelBuilderResult result,
426                 Set<ImportWarningKey> reportedImportWarnings,
427                 Map<String, ProblemCollector<ModelProblem>> reactorProblemCollectors) {
428             if (session != request.getSession()) {
429                 throw new IllegalArgumentException("Session mismatch");
430             }
431             // Create a new parentChain for each derived session to prevent cycle detection issues
432             // The parentChain now contains both GAV coordinates and file paths
433             // For BUILD_CONSUMER requests, use the request's explicit repositories so that
434             // BOM imports can be resolved from non-central repos (e.g., settings.xml profiles).
435             // This is scoped to BUILD_CONSUMER to avoid unintended side effects on other
436             // derived sessions (e.g., parent POM resolution during project builds).
437             List<RemoteRepository> derivedExtRepos = externalRepositories;
438             List<RemoteRepository> derivedRepos = repositories;
439             if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_CONSUMER
440                     && request.getRepositories() != null
441                     && !request.getRepositories().isEmpty()) {
442                 derivedExtRepos = List.copyOf(request.getRepositories());
443                 if (pomRepositories.isEmpty()) {
444                     derivedRepos = derivedExtRepos;
445                 } else {
446                     RepositoryFactory repositoryFactory = session.getService(RepositoryFactory.class);
447                     derivedRepos = repositoryFactory.aggregate(session, pomRepositories, derivedExtRepos, false);
448                 }
449             }
450             boolean derivedExternalOrigin = externalOrigin || isExternalOrigin(request);
451             return new ModelBuilderSessionState(
452                     session,
453                     request,
454                     result,
455                     dag,
456                     mappedSources,
457                     reportedImportWarnings,
458                     reactorProblemCollectors,
459                     pomRepositories,
460                     derivedExtRepos,
461                     derivedRepos,
462                     new LinkedHashSet<>(),
463                     derivedExternalOrigin);
464         }
465 
466         @Override
467         public String toString() {
468             return "ModelBuilderSession[" + "session="
469                     + session + ", " + "request="
470                     + request + ", " + "result="
471                     + result + ']';
472         }
473 
474         PhasingExecutor createExecutor() {
475             return new PhasingExecutor(Executors.newFixedThreadPool(getParallelism()));
476         }
477 
478         private int getParallelism() {
479             int parallelism = Runtime.getRuntime().availableProcessors() / 2 + 1;
480             try {
481                 String str = request.getUserProperties().get(Constants.MAVEN_MODEL_BUILDER_PARALLELISM);
482                 if (str != null) {
483                     parallelism = Integer.parseInt(str);
484                 }
485             } catch (Exception e) {
486                 // ignore
487             }
488             return Math.max(1, Math.min(parallelism, Runtime.getRuntime().availableProcessors()));
489         }
490 
491         public Model getRawModel(Path from, String groupId, String artifactId) {
492             ModelSource source = getSource(groupId, artifactId);
493             if (source != null) {
494                 if (addEdge(from, source.getPath())) {
495                     return null;
496                 }
497                 try {
498                     return derive(source).readRawModel();
499                 } catch (ModelBuilderException e) {
500                     // gathered with problem collector
501                 }
502             }
503             return null;
504         }
505 
506         public Model getRawModel(Path from, Path path) {
507             if (!Files.isRegularFile(path)) {
508                 throw new IllegalArgumentException("Not a regular file: " + path);
509             }
510             if (addEdge(from, path)) {
511                 return null;
512             }
513             try {
514                 return derive(Sources.buildSource(path)).readRawModel();
515             } catch (ModelBuilderException e) {
516                 // gathered with problem collector
517             }
518             return null;
519         }
520 
521         /**
522          * Returns false if the edge was added, true if it caused a cycle.
523          */
524         private boolean addEdge(Path from, Path p) {
525             try {
526                 dag.addEdge(from.toString(), p.toString());
527                 return false;
528             } catch (Graph.CycleDetectedException e) {
529                 add(Severity.FATAL, Version.BASE, "Cycle detected between models at " + from + " and " + p, null, e);
530                 return true;
531             }
532         }
533 
534         public ModelSource getSource(String groupId, String artifactId) {
535             Set<ModelSource> sources = mappedSources.get(new GAKey(groupId, artifactId));
536             if (sources != null) {
537                 return sources.stream()
538                         .reduce((a, b) -> {
539                             throw new IllegalStateException(String.format(
540                                     "No unique Source for %s:%s: %s and %s",
541                                     groupId, artifactId, a.getLocation(), b.getLocation()));
542                         })
543                         .orElse(null);
544             }
545             return null;
546         }
547 
548         public void putSource(String groupId, String artifactId, ModelSource source) {
549             mappedSources
550                     .computeIfAbsent(new GAKey(groupId, artifactId), k -> new HashSet<>())
551                     .add(source);
552             // Also  register the source under the null groupId
553             if (groupId != null) {
554                 putSource(null, artifactId, source);
555             }
556         }
557 
558         @Override
559         public ProblemCollector<ModelProblem> getProblemCollector() {
560             return result.getProblemCollector();
561         }
562 
563         @Override
564         public void setSource(String source) {
565             this.source = source;
566             this.sourceModel = null;
567         }
568 
569         @Override
570         public void setSource(Model source) {
571             this.sourceModel = source;
572             this.source = null;
573 
574             if (rootModel == null) {
575                 rootModel = source;
576             }
577         }
578 
579         @Override
580         public String getSource() {
581             if (source == null && sourceModel != null) {
582                 source = ModelProblemUtils.toPath(sourceModel);
583             }
584             return source;
585         }
586 
587         private String getModelId() {
588             return ModelProblemUtils.toId(sourceModel);
589         }
590 
591         @Override
592         public void setRootModel(Model rootModel) {
593             this.rootModel = rootModel;
594         }
595 
596         @Override
597         public Model getRootModel() {
598             return rootModel;
599         }
600 
601         @Override
602         public void add(
603                 BuilderProblem.Severity severity,
604                 ModelProblem.Version version,
605                 String message,
606                 InputLocation location,
607                 Exception exception) {
608             int line = -1;
609             int column = -1;
610             String source = null;
611             String modelId = null;
612 
613             if (location != null) {
614                 line = location.getLineNumber();
615                 column = location.getColumnNumber();
616                 if (location.getSource() != null) {
617                     modelId = location.getSource().getModelId();
618                     source = location.getSource().getLocation();
619                 }
620             }
621 
622             if (modelId == null) {
623                 modelId = getModelId();
624                 source = getSource();
625             }
626 
627             if (line <= 0 && column <= 0 && exception instanceof ModelParserException e) {
628                 line = e.getLineNumber();
629                 column = e.getColumnNumber();
630             }
631 
632             ModelProblem problem =
633                     new DefaultModelProblem(message, severity, version, source, line, column, modelId, exception);
634 
635             add(problem);
636         }
637 
638         @Override
639         public ModelBuilderException newModelBuilderException() {
640             return new ModelBuilderException(result);
641         }
642 
643         public void mergeRepositories(Model model, boolean replace) {
644             if (model.getRepositories().isEmpty()
645                     || InternalSession.from(session).getSession().isIgnoreArtifactDescriptorRepositories()) {
646                 return;
647             }
648             // We need to interpolate the repositories before we can use them
649             Model interpolatedModel = interpolateModel(
650                     Model.newBuilder()
651                             .pomFile(model.getPomFile())
652                             .properties(model.getProperties())
653                             .repositories(model.getRepositories())
654                             .build(),
655                     request,
656                     this);
657             List<RemoteRepository> repos = interpolatedModel.getRepositories().stream()
658                     // filter out transitive invalid repositories
659                     // this should be safe because invalid repo coming from build POMs
660                     // have been rejected earlier during validation
661                     .filter(repo -> repo.getUrl() != null
662                             && !repo.getUrl().contains("${")
663                             && (repo.getId() == null || !repo.getId().contains("${")))
664                     .map(session::createRemoteRepository)
665                     .toList();
666             // Repositories contributed by a model resolved from a repository are merged
667             // recessively; repositories supplied by the request or session keep precedence.
668             // Note: the isBuildRequest() guard means any future non-build RequestType will
669             // also use recessive merging (the else branch). This is intentional — only a
670             // build request has a well-defined set of session/request repositories that
671             // should take precedence; dependency and parent resolution do not.
672             if (replace && isBuildRequest()) {
673                 Set<String> ids = repos.stream().map(RemoteRepository::getId).collect(Collectors.toSet());
674                 repositories = repositories.stream()
675                         .filter(r -> !ids.contains(r.getId()))
676                         .toList();
677                 pomRepositories = pomRepositories.stream()
678                         .filter(r -> !ids.contains(r.getId()))
679                         .toList();
680             } else {
681                 Set<String> ids =
682                         pomRepositories.stream().map(RemoteRepository::getId).collect(Collectors.toSet());
683                 repos = repos.stream().filter(r -> !ids.contains(r.getId())).toList();
684             }
685 
686             RepositoryFactory repositoryFactory = session.getService(RepositoryFactory.class);
687             if (request.getRepositoryMerging() == ModelBuilderRequest.RepositoryMerging.REQUEST_DOMINANT) {
688                 repositories = repositoryFactory.aggregate(session, repositories, repos, true);
689                 pomRepositories = repositories;
690             } else {
691                 pomRepositories = repositoryFactory.aggregate(session, pomRepositories, repos, true);
692                 repositories = repositoryFactory.aggregate(session, pomRepositories, externalRepositories, false);
693             }
694         }
695 
696         //
697         // Transform raw model to build pom.
698         // Infer missing coordinates from models in the reactor
699         //
700         Model transformFileToRaw(Model model) {
701             Parent newParent = inferParentVersion(model);
702 
703             List<Dependency> newDeps = null;
704             boolean depsChanged = false;
705             if (!model.getDependencies().isEmpty()) {
706                 newDeps = new ArrayList<>(model.getDependencies().size());
707                 depsChanged = inferDependencies(model, model.getDependencies(), newDeps);
708             }
709 
710             DependencyManagement depMgmt = model.getDependencyManagement();
711             List<Dependency> newManagedDeps = null;
712             boolean managedDepsChanged = false;
713             if (depMgmt != null && !depMgmt.getDependencies().isEmpty()) {
714                 newManagedDeps = new ArrayList<>(depMgmt.getDependencies().size());
715                 managedDepsChanged = inferDependencies(model, depMgmt.getDependencies(), newManagedDeps);
716             }
717 
718             if (newParent == null && !depsChanged && !managedDepsChanged) {
719                 return model;
720             }
721             Model.Builder builder = Model.newBuilder(model);
722             if (newParent != null) {
723                 builder.parent(newParent);
724             }
725             if (depsChanged) {
726                 builder.dependencies(newDeps);
727             }
728             if (managedDepsChanged) {
729                 builder.dependencyManagement(depMgmt.withDependencies(newManagedDeps));
730             }
731             return builder.build();
732         }
733 
734         private Parent inferParentVersion(Model model) {
735             Parent parent = model.getParent();
736             if (parent == null
737                     || parent.getVersion() != null
738                     || parent.getGroupId() == null
739                     || parent.getArtifactId() == null) {
740                 return null;
741             }
742 
743             Model parentModel = getRawModel(model.getPomFile(), parent.getGroupId(), parent.getArtifactId());
744             if (parentModel == null) {
745                 return null;
746             }
747 
748             String version = parentModel.getVersion();
749             InputLocation versionLocation = parentModel.getLocation("version");
750             if (version == null && parentModel.getParent() != null) {
751                 // Parent model inherits its version from its own parent (grandparent).
752                 // versionLocation may be null if the grandparent has no explicit <version>;
753                 // Builder.location() silently ignores null values, which is safe here.
754                 version = parentModel.getParent().getVersion();
755                 versionLocation = parentModel.getParent().getLocation("version");
756             }
757             return version != null
758                     ? parent.with()
759                             .version(version)
760                             .location("version", versionLocation)
761                             .build()
762                     : null;
763         }
764 
765         /**
766          * Infers the missing version or groupId of the given dependencies by looking them up in the reactor.
767          * Each dependency, either the original one or the inferred one, is added to {@code result}.
768          *
769          * @param model the model declaring the dependencies
770          * @param dependencies the dependencies to process
771          * @param result the list collecting the resulting dependencies
772          * @return whether at least one dependency has been inferred
773          */
774         private boolean inferDependencies(Model model, List<Dependency> dependencies, List<Dependency> result) {
775             boolean changed = false;
776             for (Dependency dep : dependencies) {
777                 Dependency newDep = null;
778                 if (dep.getVersion() == null) {
779                     newDep = inferDependencyVersion(model, dep);
780                 } else if (dep.getGroupId() == null) {
781                     // Handle missing groupId when version is present
782                     newDep = inferDependencyGroupId(model, dep);
783                 }
784                 if (newDep != null) {
785                     changed = true;
786                 }
787                 result.add(newDep == null ? dep : newDep);
788             }
789             return changed;
790         }
791 
792         private Dependency inferDependencyVersion(Model model, Dependency dep) {
793             Model depModel = getRawModel(model.getPomFile(), dep.getGroupId(), dep.getArtifactId());
794             if (depModel == null) {
795                 return null;
796             }
797             Dependency.Builder depBuilder = Dependency.newBuilder(dep);
798             String version = depModel.getVersion();
799             InputLocation versionLocation = depModel.getLocation("version");
800             if (version == null && depModel.getParent() != null) {
801                 version = depModel.getParent().getVersion();
802                 versionLocation = depModel.getParent().getLocation("version");
803             }
804             depBuilder.version(version).location("version", versionLocation);
805             if (dep.getGroupId() == null) {
806                 String depGroupId = depModel.getGroupId();
807                 InputLocation groupIdLocation = depModel.getLocation("groupId");
808                 if (depGroupId == null && depModel.getParent() != null) {
809                     depGroupId = depModel.getParent().getGroupId();
810                     groupIdLocation = depModel.getParent().getLocation("groupId");
811                 }
812                 depBuilder.groupId(depGroupId).location("groupId", groupIdLocation);
813             }
814             return depBuilder.build();
815         }
816 
817         private Dependency inferDependencyGroupId(Model model, Dependency dep) {
818             Model depModel = getRawModel(model.getPomFile(), dep.getGroupId(), dep.getArtifactId());
819             if (depModel == null) {
820                 return null;
821             }
822             Dependency.Builder depBuilder = Dependency.newBuilder(dep);
823             String depGroupId = depModel.getGroupId();
824             InputLocation groupIdLocation = depModel.getLocation("groupId");
825             if (depGroupId == null && depModel.getParent() != null) {
826                 depGroupId = depModel.getParent().getGroupId();
827                 groupIdLocation = depModel.getParent().getLocation("groupId");
828             }
829             depBuilder.groupId(depGroupId).location("groupId", groupIdLocation);
830             return depBuilder.build();
831         }
832 
833         String replaceCiFriendlyVersion(Map<String, String> properties, String version) {
834             return version != null ? interpolator.interpolate(version, properties::get) : null;
835         }
836 
837         /**
838          * Get enhanced properties that include profile-aware property resolution.
839          * This method activates profiles to ensure that properties defined in profiles
840          * are available for CI-friendly version processing and repository URL interpolation.
841          * It also includes directory-related properties that may be needed during profile activation.
842          */
843         private Map<String, String> getEnhancedProperties(Model model, Path rootDirectory, Set<Path> activeModelReads) {
844             Map<String, String> properties = new HashMap<>();
845 
846             // Add directory-specific properties first, as they may be needed for profile activation
847             if (model.getProjectDirectory() != null) {
848                 String basedir = model.getProjectDirectory().toString();
849                 String basedirUri = model.getProjectDirectory().toUri().toString();
850                 properties.put("basedir", basedir);
851                 properties.put("project.basedir", basedir);
852                 properties.put("project.basedir.uri", basedirUri);
853             }
854             if (rootDirectory != null) {
855                 try {
856                     String root = rootDirectory.toString();
857                     String rootUri = rootDirectory.toUri().toString();
858                     properties.put("project.rootDirectory", root);
859                     properties.put("project.rootDirectory.uri", rootUri);
860                 } catch (IllegalStateException e) {
861                     // Root directory not available, continue without it
862                 }
863             }
864 
865             // Handle root vs non-root project properties with profile activation.
866             // Use toAbsolutePath().normalize() for robust comparison — rootDirectory from
867             // session.getRootDirectory() may not be normalized, while model.getProjectDirectory()
868             // (derived from pomFile.getParent() in PathSource) is always normalized. Without
869             // consistent normalization, the root model can incorrectly enter this branch and
870             // trigger infinite recursion through readFileModel() (GH-12598).
871             Path normalizedRootDir =
872                     rootDirectory != null ? rootDirectory.toAbsolutePath().normalize() : null;
873             Path normalizedProjectDir = model.getProjectDirectory() != null
874                     ? model.getProjectDirectory().toAbsolutePath().normalize()
875                     : null;
876             if (!Objects.equals(normalizedRootDir, normalizedProjectDir)) {
877                 Path rootModelPath = modelProcessor.locateExistingPom(rootDirectory);
878                 if (rootModelPath != null) {
879                     // Check if the root model path is within the root directory to prevent infinite loops
880                     // This can happen when a .mvn directory exists in a subdirectory and parent inference
881                     // tries to read models above the discovered root directory.
882                     // Also skip if the root model is already being read in an outer call frame
883                     // to prevent StackOverflowError when a project has an internal parent in a
884                     // subdirectory with CI-friendly ${revision} and a .mvn/ root marker (GH-12301).
885                     // Use toAbsolutePath().normalize() for the guard check to handle paths
886                     // obtained via different representations (e.g., symlinks, relative segments).
887                     if (isParentWithinRootDirectory(rootModelPath, rootDirectory)
888                             && !activeModelReads.contains(
889                                     rootModelPath.toAbsolutePath().normalize())) {
890                         Model rootModel =
891                                 derive(Sources.buildSource(rootModelPath)).readFileModel(activeModelReads);
892                         properties.putAll(getPropertiesWithProfiles(rootModel, properties));
893                     }
894                 }
895             } else {
896                 properties.putAll(getPropertiesWithProfiles(model, properties));
897             }
898 
899             return properties;
900         }
901 
902         /**
903          * Get properties from a model including properties from activated profiles.
904          * This performs lightweight profile activation to merge profile properties.
905          *
906          * @param model the model to get properties from
907          * @param baseProperties base properties (including directory properties) to include in profile activation context
908          */
909         private Map<String, String> getPropertiesWithProfiles(Model model, Map<String, String> baseProperties) {
910             Map<String, String> properties = new HashMap<>();
911 
912             // Start with base properties (including directory properties)
913             properties.putAll(baseProperties);
914 
915             // Add model properties
916             properties.putAll(model.getProperties());
917 
918             try {
919                 // Create a profile activation context for this model with base properties available
920                 DefaultProfileActivationContext profileContext = getProfileActivationContext(request, model);
921 
922                 // Activate profiles and merge their properties
923                 List<Profile> activeProfiles = getActiveProfiles(model.getProfiles(), profileContext);
924 
925                 for (Profile profile : activeProfiles) {
926                     properties.putAll(profile.getProperties());
927                 }
928             } catch (Exception e) {
929                 // If profile activation fails, log a warning but continue with base properties
930                 // This ensures that CI-friendly versions still work even if profile activation has issues
931                 logger.warn("Failed to activate profiles for CI-friendly version processing: {}", e.getMessage());
932                 logger.debug("Profile activation failure details", e);
933             }
934 
935             // System and user properties override everything (use request properties
936             // to ensure consistency with model interpolation, which also uses request properties)
937             properties.putAll(request.getSystemProperties());
938             properties.putAll(request.getUserProperties());
939 
940             return properties;
941         }
942 
943         /**
944          * Convenience method for getting properties with profiles without additional base properties.
945          * This is a backward compatibility method that provides an empty base properties map.
946          */
947         private Map<String, String> getPropertiesWithProfiles(Model model) {
948             return getPropertiesWithProfiles(model, new HashMap<>());
949         }
950 
951         private void buildBuildPom() throws ModelBuilderException {
952             // Retrieve and normalize the source path, ensuring it's non-null and in absolute form
953             Path top = request.getSource().getPath();
954             if (top == null) {
955                 throw new IllegalStateException("Recursive build requested but source has no path");
956             }
957             top = top.toAbsolutePath().normalize();
958 
959             // Obtain the root directory, resolving it if necessary
960             Path rootDirectory;
961             try {
962                 rootDirectory = session.getRootDirectory();
963             } catch (IllegalStateException e) {
964                 rootDirectory = session.getService(RootLocator.class).findMandatoryRoot(top);
965             }
966 
967             // Locate and normalize the root POM if it exists, fallback to top otherwise
968             Path root = modelProcessor.locateExistingPom(rootDirectory);
969             if (root != null) {
970                 root = root.toAbsolutePath().normalize();
971             } else {
972                 root = top;
973             }
974 
975             // Load all models starting from the root
976             loadFromRoot(root, top);
977 
978             // Check for errors after loading models
979             if (hasErrors()) {
980                 throw newModelBuilderException();
981             }
982 
983             // For the top model and all its children, build the effective model.
984             // This is done through the phased executor
985             var allResults = results(result).toList();
986             List<RuntimeException> exceptions = new CopyOnWriteArrayList<>();
987             InternalSession session = InternalSession.from(this.session);
988             RequestTrace trace = session.getCurrentTrace();
989             try (PhasingExecutor executor = createExecutor()) {
990                 for (DefaultModelBuilderResult r : allResults) {
991                     executor.execute(() -> {
992                         ModelBuilderSessionState mbs = derive(r.getSource(), r);
993                         session.setCurrentTrace(trace);
994                         try {
995                             mbs.buildEffectiveModel(new LinkedHashSet<>());
996                         } catch (ModelBuilderException e) {
997                             // gathered with problem collector
998                             // Propagate problems from child session to parent session
999                             for (var problem : e.getResult()
1000                                     .getProblemCollector()
1001                                     .problems()
1002                                     .toList()) {
1003                                 getProblemCollector().reportProblem(problem);
1004                             }
1005                         } catch (RuntimeException t) {
1006                             exceptions.add(t);
1007                         } finally {
1008                             session.setCurrentTrace(null);
1009                         }
1010                     });
1011                 }
1012             }
1013 
1014             // Check for errors again after execution
1015             if (exceptions.size() == 1) {
1016                 throw exceptions.get(0);
1017             } else if (exceptions.size() > 1) {
1018                 MavenException fatalException = new MavenException("Multiple fatal exceptions occurred");
1019                 exceptions.forEach(fatalException::addSuppressed);
1020                 throw fatalException;
1021             } else if (hasErrors()) {
1022                 throw newModelBuilderException();
1023             }
1024         }
1025 
1026         /**
1027          * Generates a stream of DefaultModelBuilderResult objects, starting with the provided
1028          * result and recursively including all its child results.
1029          *
1030          * @param r The initial DefaultModelBuilderResult object from which to generate the stream.
1031          * @return A Stream of DefaultModelBuilderResult objects, starting with the provided result
1032          *         and including all its child results.
1033          */
1034         Stream<DefaultModelBuilderResult> results(DefaultModelBuilderResult r) {
1035             return Stream.concat(Stream.of(r), r.getChildren().stream().flatMap(this::results));
1036         }
1037 
1038         private void loadFromRoot(Path root, Path top) {
1039             try (PhasingExecutor executor = createExecutor()) {
1040                 DefaultModelBuilderResult r = Objects.equals(top, root)
1041                         ? result
1042                         : new DefaultModelBuilderResult(request, ProblemCollector.create(session));
1043                 loadFilePom(executor, top, root, Set.of(), r);
1044             }
1045             if (result.getFileModel() == null && !Objects.equals(top, root)) {
1046                 logger.warn(
1047                         "The top project ({}) cannot be found in the reactor from root project ({}). "
1048                                 + "Make sure the root directory is correct (a missing '.mvn' directory in the root "
1049                                 + "project is the most common cause) and the project is correctly included "
1050                                 + "in the reactor (missing activated profiles, command line options, etc.). For this "
1051                                 + "build, the top project will be used as the root project.",
1052                         top,
1053                         root);
1054                 mappedSources.clear();
1055                 reportedImportWarnings.clear();
1056                 reactorProblemCollectors.clear();
1057                 loadFromRoot(top, top);
1058             }
1059         }
1060 
1061         private void loadFilePom(
1062                 Executor executor, Path top, Path pom, Set<Path> parents, DefaultModelBuilderResult r) {
1063             try {
1064                 Path pomDirectory = Files.isDirectory(pom) ? pom : pom.getParent();
1065                 ModelSource src = Sources.buildSource(pom);
1066                 Model model = derive(src, r).readFileModel();
1067                 // keep all loaded file models in memory, those will be needed
1068                 // during the raw to build transformation
1069                 registerReactorProblemCollector(src, r.getProblemCollector());
1070                 putSource(getGroupId(model), model.getArtifactId(), src);
1071                 Model activated = activateFileModel(model);
1072                 for (String subproject : getSubprojects(activated)) {
1073                     if (subproject == null || subproject.isEmpty()) {
1074                         continue;
1075                     }
1076 
1077                     // #12729: interpolate properties in the subproject/module path (e.g.
1078                     // <module>./../module/pom${version-discriminator}.xml</module>) before
1079                     // resolving it against the filesystem. Model-wide interpolation happens
1080                     // later in the build, but module paths must be resolved here, so we
1081                     // interpolate just the path against the user, model and system properties.
1082                     subproject = interpolator.interpolate(
1083                             subproject,
1084                             Interpolator.chain(
1085                                     request.getUserProperties()::get,
1086                                     activated.getProperties()::get,
1087                                     request.getSystemProperties()::get));
1088 
1089                     subproject = subproject.replace('\\', File.separatorChar).replace('/', File.separatorChar);
1090 
1091                     Path rawSubprojectFile = modelProcessor.locateExistingPom(pomDirectory.resolve(subproject));
1092 
1093                     if (rawSubprojectFile == null) {
1094                         ModelProblem problem = new DefaultModelProblem(
1095                                 "Child subproject " + subproject + " of " + pomDirectory + " does not exist",
1096                                 Severity.ERROR,
1097                                 Version.BASE,
1098                                 model,
1099                                 -1,
1100                                 -1,
1101                                 null);
1102                         r.getProblemCollector().reportProblem(problem);
1103                         continue;
1104                     }
1105 
1106                     Path subprojectFile = rawSubprojectFile.toAbsolutePath().normalize();
1107 
1108                     if (parents.contains(subprojectFile)) {
1109                         StringBuilder buffer = new StringBuilder(256);
1110                         for (Path aggregatorFile : parents) {
1111                             buffer.append(aggregatorFile).append(" -> ");
1112                         }
1113                         buffer.append(subprojectFile);
1114 
1115                         ModelProblem problem = new DefaultModelProblem(
1116                                 "Child subproject " + subprojectFile + " of " + pom + " forms aggregation cycle "
1117                                         + buffer,
1118                                 Severity.ERROR,
1119                                 Version.BASE,
1120                                 model,
1121                                 -1,
1122                                 -1,
1123                                 null);
1124                         r.getProblemCollector().reportProblem(problem);
1125                         continue;
1126                     }
1127 
1128                     DefaultModelBuilderResult cr = Objects.equals(top, subprojectFile)
1129                             ? result
1130                             : new DefaultModelBuilderResult(request, ProblemCollector.create(session));
1131                     if (request.isRecursive()) {
1132                         r.getChildren().add(cr);
1133                     }
1134 
1135                     InternalSession session = InternalSession.from(this.session);
1136                     RequestTrace trace = session.getCurrentTrace();
1137                     executor.execute(() -> {
1138                         session.setCurrentTrace(trace);
1139                         try {
1140                             loadFilePom(executor, top, subprojectFile, concat(parents, pom), cr);
1141                         } finally {
1142                             session.setCurrentTrace(null);
1143                         }
1144                     });
1145                 }
1146             } catch (ModelBuilderException e) {
1147                 // gathered with problem collector
1148                 add(Severity.ERROR, Version.V40, "Failed to load project " + pom, e);
1149             }
1150         }
1151 
1152         static <T> Set<T> concat(Set<T> a, T b) {
1153             Set<T> result = new HashSet<>(a);
1154             result.add(b);
1155             return Set.copyOf(result);
1156         }
1157 
1158         void buildEffectiveModel(Collection<String> importIds) throws ModelBuilderException {
1159             Model resultModel = readEffectiveModel();
1160             setSource(resultModel);
1161             setRootModel(resultModel);
1162 
1163             // model path translation
1164             resultModel =
1165                     modelPathTranslator.alignToBaseDirectory(resultModel, resultModel.getProjectDirectory(), request);
1166 
1167             // plugin management injection
1168             resultModel = pluginManagementInjector.injectManagement(resultModel, request, this);
1169 
1170             // lifecycle bindings injection
1171             if (request.getRequestType() != ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY) {
1172                 org.apache.maven.api.services.ModelTransformer lifecycleBindingsInjector =
1173                         request.getLifecycleBindingsInjector();
1174                 if (lifecycleBindingsInjector != null) {
1175                     resultModel = lifecycleBindingsInjector.transform(resultModel, request, this);
1176                 }
1177             }
1178 
1179             // dependency management import
1180             resultModel = importDependencyManagement(resultModel, importIds);
1181 
1182             // dependency management injection
1183             resultModel = dependencyManagementInjector.injectManagement(resultModel, request, this);
1184 
1185             resultModel = modelNormalizer.injectDefaultValues(resultModel, request, this);
1186 
1187             if (request.getRequestType() != ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY) {
1188                 // plugins configuration
1189                 resultModel = pluginConfigurationExpander.expandPluginConfiguration(resultModel, request, this);
1190             }
1191 
1192             for (var transformer : transformers) {
1193                 resultModel = transformer.transformEffectiveModel(resultModel);
1194             }
1195 
1196             result.setEffectiveModel(resultModel);
1197             // Set the default relative path for the parent in the file model
1198             if (result.getFileModel().getParent() != null
1199                     && result.getFileModel().getParent().getRelativePath() == null) {
1200                 result.setFileModel(result.getFileModel()
1201                         .withParent(result.getFileModel()
1202                                 .getParent()
1203                                 .withRelativePath(resultModel.getParent().getRelativePath())));
1204             }
1205 
1206             // effective model validation
1207             modelValidator.validateEffectiveModel(
1208                     session,
1209                     resultModel,
1210                     isBuildRequest() ? ModelValidator.VALIDATION_LEVEL_STRICT : ModelValidator.VALIDATION_LEVEL_MINIMAL,
1211                     this);
1212 
1213             if (hasErrors()) {
1214                 throw newModelBuilderException();
1215             }
1216         }
1217 
1218         Model readParent(
1219                 Model childModel,
1220                 Parent parent,
1221                 DefaultProfileActivationContext profileActivationContext,
1222                 Set<String> parentChain) {
1223             Model parentModel;
1224 
1225             if (parent != null) {
1226                 // Check for circular parent resolution using model IDs
1227                 String parentId = parent.getGroupId() + ":" + parent.getArtifactId() + ":" + parent.getVersion();
1228                 if (!parentChain.add(parentId)) {
1229                     StringBuilder message = new StringBuilder("The parents form a cycle: ");
1230                     for (String id : parentChain) {
1231                         message.append(id).append(" -> ");
1232                     }
1233                     message.append(parentId);
1234 
1235                     add(Severity.FATAL, Version.BASE, message.toString());
1236                     throw newModelBuilderException();
1237                 }
1238 
1239                 try {
1240                     parentModel = resolveParent(childModel, parent, profileActivationContext, parentChain);
1241 
1242                     if (!"pom".equals(parentModel.getPackaging())) {
1243                         add(
1244                                 Severity.ERROR,
1245                                 Version.BASE,
1246                                 "Invalid packaging for parent POM " + ModelProblemUtils.toSourceHint(parentModel)
1247                                         + ", must be \"pom\" but is \"" + parentModel.getPackaging() + "\"",
1248                                 parentModel.getLocation("packaging"));
1249                     }
1250                     result.setParentModel(parentModel);
1251 
1252                     // Recursively read the parent's parent
1253                     if (parentModel.getParent() != null) {
1254                         readParent(parentModel, parentModel.getParent(), profileActivationContext, parentChain);
1255                     }
1256                 } finally {
1257                     // Remove from chain when done processing this parent
1258                     parentChain.remove(parentId);
1259                 }
1260             } else {
1261                 String superModelVersion = childModel.getModelVersion();
1262                 if (superModelVersion == null || !KNOWN_MODEL_VERSIONS.contains(superModelVersion)) {
1263                     // Maven 3.x is always using 4.0.0 version to load the supermodel, so
1264                     // do the same when loading a dependency.  The model validator will also
1265                     // check that field later.
1266                     superModelVersion = MODEL_VERSION_4_0_0;
1267                 }
1268                 parentModel = getSuperModel(superModelVersion);
1269             }
1270 
1271             return parentModel;
1272         }
1273 
1274         private Model resolveParent(
1275                 Model childModel,
1276                 Parent parent,
1277                 DefaultProfileActivationContext profileActivationContext,
1278                 Set<String> parentChain)
1279                 throws ModelBuilderException {
1280             Model parentModel = null;
1281             if (isBuildRequest()) {
1282                 parentModel = readParentLocally(childModel, parent, profileActivationContext, parentChain);
1283             }
1284             if (parentModel == null) {
1285                 parentModel = resolveAndReadParentExternally(childModel, parent, profileActivationContext, parentChain);
1286             }
1287             return parentModel;
1288         }
1289 
1290         private Model readParentLocally(
1291                 Model childModel,
1292                 Parent parent,
1293                 DefaultProfileActivationContext profileActivationContext,
1294                 Set<String> parentChain)
1295                 throws ModelBuilderException {
1296             ModelSource candidateSource;
1297             String parentPath = parent.getRelativePath();
1298             if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
1299                 if (parentPath != null && !parentPath.isEmpty()) {
1300                     candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, parentPath);
1301                     if (candidateSource == null) {
1302                         wrongParentRelativePath(childModel);
1303                         return null;
1304                     }
1305                 } else {
1306                     candidateSource =
1307                             resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1308                     if (candidateSource == null && parentPath == null) {
1309                         candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, "..");
1310                     }
1311                 }
1312             } else {
1313                 candidateSource = resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1314                 if (candidateSource == null) {
1315                     if (parentPath == null) {
1316                         parentPath = "..";
1317                     }
1318                     if (!parentPath.isEmpty()) {
1319                         candidateSource = request.getSource().resolve(modelProcessor::locateExistingPom, parentPath);
1320                     }
1321                 }
1322             }
1323 
1324             if (candidateSource == null) {
1325                 return null;
1326             }
1327 
1328             // Check for circular parent resolution using source locations (file paths)
1329             // This must be done BEFORE calling derive() to prevent StackOverflowError
1330             String sourceLocation = candidateSource.getLocation();
1331 
1332             if (!parentChain.add(sourceLocation)) {
1333                 StringBuilder message = new StringBuilder("The parents form a cycle: ");
1334                 for (String location : parentChain) {
1335                     message.append(location).append(" -> ");
1336                 }
1337                 message.append(sourceLocation);
1338 
1339                 add(Severity.FATAL, Version.BASE, message.toString());
1340                 throw newModelBuilderException();
1341             }
1342 
1343             try {
1344                 ModelBuilderSessionState derived = derive(
1345                         request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_CONSUMER
1346                                 ? ModelBuilderRequest.builder(request)
1347                                         .requestType(ModelBuilderRequest.RequestType.CONSUMER_PARENT)
1348                                         .source(candidateSource)
1349                                         .build()
1350                                 : ModelBuilderRequest.build(request, candidateSource));
1351 
1352                 // Check GA match BEFORE readAsParentModel() which recursively resolves
1353                 // the candidate's parent chain and can trigger false cycle detection (GH-12074).
1354                 Model fileModel = derived.readFileModel();
1355                 String fileGroupId = getGroupId(fileModel);
1356                 String fileArtifactId = fileModel.getArtifactId();
1357 
1358                 if (fileGroupId == null
1359                         || !fileGroupId.equals(parent.getGroupId())
1360                         || fileArtifactId == null
1361                         || !fileArtifactId.equals(parent.getArtifactId())) {
1362                     mismatchRelativePathAndGA(childModel, parent, fileGroupId, fileArtifactId);
1363                     return null;
1364                 }
1365                 Model candidateModel = derived.readAsParentModel(profileActivationContext, parentChain);
1366                 // Add profiles from parent, preserving model ID tracking
1367                 for (Map.Entry<String, List<Profile>> entry :
1368                         derived.result.getActivePomProfilesByModel().entrySet()) {
1369                     addActivePomProfiles(entry.getKey(), entry.getValue());
1370                 }
1371 
1372                 String version = getVersion(candidateModel);
1373 
1374                 if (version != null && parent.getVersion() != null && !version.equals(parent.getVersion())) {
1375                     try {
1376                         VersionRange parentRange = versionParser.parseVersionRange(parent.getVersion());
1377                         if (!parentRange.contains(versionParser.parseVersion(version))) {
1378                             // version skew drop back to resolution from the repository
1379                             return null;
1380                         }
1381 
1382                         // Validate versions aren't inherited when using parent ranges the same way as when read
1383                         // externally.
1384                         String rawChildModelVersion = childModel.getVersion();
1385 
1386                         if (rawChildModelVersion == null) {
1387                             // Message below is checked for in the MNG-2199 core IT.
1388                             add(Severity.FATAL, Version.V31, "Version must be a constant", childModel.getLocation(""));
1389 
1390                         } else {
1391                             if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1392                                 // Message below is checked for in the MNG-2199 core IT.
1393                                 add(
1394                                         Severity.FATAL,
1395                                         Version.V31,
1396                                         "Version must be a constant",
1397                                         childModel.getLocation("version"));
1398                             }
1399                         }
1400 
1401                         // MNG-2199: What else to check here ?
1402                     } catch (VersionParserException e) {
1403                         // invalid version range, so drop back to resolution from the repository
1404                         return null;
1405                     }
1406                 }
1407                 return candidateModel;
1408             } finally {
1409                 // Remove the source location from the chain when we're done processing this parent
1410                 parentChain.remove(sourceLocation);
1411             }
1412         }
1413 
1414         private void mismatchRelativePathAndGA(Model childModel, Parent parent, String groupId, String artifactId) {
1415             boolean defaultPath = parent.getRelativePath() == null;
1416             boolean maven3Mode = Features.mavenMaven3Personality(
1417                     InternalSession.from(session).getSession().getConfigProperties());
1418 
1419             String actual = groupId + ':' + artifactId;
1420             String declared = parent.getGroupId() + ':' + parent.getArtifactId();
1421             String sourceHint = (childModel != getRootModel()) ? ModelProblemUtils.toSourceHint(childModel) : null;
1422 
1423             String message;
1424             if (defaultPath) {
1425                 // <relativePath> was omitted — Maven probed ../pom.xml on its own
1426                 message = "Maven probed the default location '../pom.xml'"
1427                         + (sourceHint != null ? " for POM " + sourceHint : "")
1428                         + " and found " + actual
1429                         + " instead of the declared parent " + declared
1430                         + ". Maven will fall back to repository resolution."
1431                         + " To suppress this warning, add <relativePath/> to your <parent> declaration.";
1432             } else {
1433                 // <relativePath> was set explicitly — this is a configuration error
1434                 message = "'parent.relativePath'"
1435                         + (sourceHint != null ? " of POM " + sourceHint : "")
1436                         + " points at '" + parent.getRelativePath() + "'"
1437                         + " which resolves to " + actual
1438                         + " instead of the declared parent " + declared
1439                         + (maven3Mode
1440                                 ? ". Please verify your project structure."
1441                                 : ". Correct the <relativePath> value or remove it to let Maven resolve the parent"
1442                                         + " from the repository."
1443                                         + " If this POM was generated by a build tool (e.g. maven-shade-plugin),"
1444                                         + " upgrade that tool or use -Dmaven.maven3Personality as a temporary workaround.");
1445             }
1446 
1447             setSource(childModel);
1448             // WARNING when: Maven probed the default path (user didn't set anything),
1449             //               OR maven3Personality is active (preserve historical lenient behaviour).
1450             // FATAL otherwise: explicit <relativePath> pointing at the wrong artifact is a config error.
1451             boolean warn = defaultPath || maven3Mode;
1452             add(warn ? Severity.WARNING : Severity.FATAL, Version.BASE, message, parent.getLocation(""));
1453         }
1454 
1455         private void wrongParentRelativePath(Model childModel) {
1456             Parent parent = childModel.getParent();
1457             String parentPath = parent.getRelativePath();
1458             StringBuilder buffer = new StringBuilder(256);
1459             buffer.append("'parent.relativePath'");
1460             if (childModel != getRootModel()) {
1461                 buffer.append(" of POM ").append(ModelProblemUtils.toSourceHint(childModel));
1462             }
1463             buffer.append(" points at '").append(parentPath);
1464             buffer.append("' but no POM could be found, please verify your project structure");
1465 
1466             setSource(childModel);
1467             add(Severity.FATAL, Version.BASE, buffer.toString(), parent.getLocation(""));
1468         }
1469 
1470         Model resolveAndReadParentExternally(
1471                 Model childModel,
1472                 Parent parent,
1473                 DefaultProfileActivationContext profileActivationContext,
1474                 Set<String> parentChain)
1475                 throws ModelBuilderException {
1476             ModelBuilderRequest request = this.request;
1477             setSource(childModel);
1478 
1479             String groupId = parent.getGroupId();
1480             String artifactId = parent.getArtifactId();
1481             String version = parent.getVersion();
1482 
1483             // add repositories specified by the current model so that we can resolve the parent
1484             if (!childModel.getRepositories().isEmpty()) {
1485                 var previousRepositories = repositories;
1486                 mergeRepositories(childModel, false);
1487                 if (!Objects.equals(previousRepositories, repositories)) {
1488                     if (logger.isDebugEnabled()) {
1489                         logger.debug("Merging repositories from " + childModel.getId() + "\n"
1490                                 + repositories.stream()
1491                                         .map(Object::toString)
1492                                         .collect(Collectors.joining("\n", "    ", "")));
1493                     }
1494                 }
1495             }
1496 
1497             ModelSource modelSource;
1498             try {
1499                 modelSource = resolveReactorModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
1500                 if (modelSource == null) {
1501                     AtomicReference<Parent> modified = new AtomicReference<>();
1502                     modelSource = modelResolver.resolveModel(request.getSession(), repositories, parent, modified);
1503                     if (modified.get() != null) {
1504                         parent = modified.get();
1505                     }
1506                 }
1507             } catch (ModelResolverException e) {
1508                 // Message below is checked for in the MNG-2199 core IT.
1509                 StringBuilder buffer = new StringBuilder(256);
1510                 buffer.append("Non-resolvable parent POM");
1511                 if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
1512                     buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
1513                 }
1514                 if (childModel != getRootModel()) {
1515                     buffer.append(" for ").append(ModelProblemUtils.toId(childModel));
1516                 }
1517                 buffer.append(": ").append(e.getMessage());
1518                 if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT) {
1519                     buffer.append(" and parent could not be found in reactor");
1520                 }
1521 
1522                 add(Severity.FATAL, Version.BASE, buffer.toString(), parent.getLocation(""), e);
1523                 throw newModelBuilderException();
1524             }
1525 
1526             ModelBuilderRequest lenientRequest = ModelBuilderRequest.builder(request)
1527                     .requestType(ModelBuilderRequest.RequestType.CONSUMER_PARENT)
1528                     .source(modelSource)
1529                     .build();
1530 
1531             ModelBuilderSessionState derived = derive(lenientRequest);
1532             Model parentModel = derived.readAsParentModel(profileActivationContext, parentChain);
1533             // Add profiles from parent, preserving model ID tracking
1534             for (Map.Entry<String, List<Profile>> entry :
1535                     derived.result.getActivePomProfilesByModel().entrySet()) {
1536                 addActivePomProfiles(entry.getKey(), entry.getValue());
1537             }
1538 
1539             if (!parent.getVersion().equals(version)) {
1540                 String rawChildModelVersion = childModel.getVersion();
1541 
1542                 if (rawChildModelVersion == null) {
1543                     // Message below is checked for in the MNG-2199 core IT.
1544                     add(Severity.FATAL, Version.V31, "Version must be a constant", childModel.getLocation(""));
1545                 } else {
1546                     if (rawChildVersionReferencesParent(rawChildModelVersion)) {
1547                         // Message below is checked for in the MNG-2199 core IT.
1548                         add(
1549                                 Severity.FATAL,
1550                                 Version.V31,
1551                                 "Version must be a constant",
1552                                 childModel.getLocation("version"));
1553                     }
1554                 }
1555 
1556                 // MNG-2199: What else to check here ?
1557             }
1558 
1559             return parentModel;
1560         }
1561 
1562         Model activateFileModel(Model inputModel) throws ModelBuilderException {
1563             setRootModel(inputModel);
1564 
1565             // profile activation
1566             DefaultProfileActivationContext profileActivationContext = getProfileActivationContext(request, inputModel);
1567 
1568             setSource("(external profiles)");
1569             List<Profile> activeExternalProfiles = getActiveProfiles(request.getProfiles(), profileActivationContext);
1570 
1571             result.setActiveExternalProfiles(activeExternalProfiles);
1572 
1573             if (!activeExternalProfiles.isEmpty()) {
1574                 Map<String, String> profileProps = new HashMap<>();
1575                 for (Profile profile : activeExternalProfiles) {
1576                     profileProps.putAll(profile.getProperties());
1577                 }
1578                 profileProps.putAll(request.getUserProperties());
1579                 profileActivationContext.setUserProperties(profileProps);
1580             }
1581 
1582             profileActivationContext.setModel(inputModel);
1583             setSource(inputModel);
1584             List<Profile> activePomProfiles = getActiveProfiles(inputModel.getProfiles(), profileActivationContext);
1585 
1586             // model normalization
1587             setSource(inputModel);
1588             inputModel = modelNormalizer.mergeDuplicates(inputModel, request, this);
1589 
1590             List<Activation> interpolatedActivations = getProfileActivations(inputModel);
1591             inputModel = injectProfileActivations(inputModel, interpolatedActivations);
1592 
1593             // profile injection
1594             inputModel = profileInjector.injectProfiles(inputModel, activePomProfiles, request, this);
1595             inputModel = profileInjector.injectProfiles(inputModel, activeExternalProfiles, request, this);
1596 
1597             return inputModel;
1598         }
1599 
1600         @SuppressWarnings("checkstyle:methodlength")
1601         private Model readEffectiveModel() throws ModelBuilderException {
1602             Model inputModel = readRawModel();
1603             if (hasFatalErrors()) {
1604                 throw newModelBuilderException();
1605             }
1606 
1607             setRootModel(inputModel);
1608 
1609             Model activatedFileModel = activateFileModel(inputModel);
1610 
1611             // profile activation
1612             DefaultProfileActivationContext profileActivationContext =
1613                     getProfileActivationContext(request, activatedFileModel);
1614 
1615             List<Profile> activeExternalProfiles = result.getActiveExternalProfiles();
1616 
1617             if (!activeExternalProfiles.isEmpty()) {
1618                 Map<String, String> profileProps = new HashMap<>();
1619                 for (Profile profile : activeExternalProfiles) {
1620                     profileProps.putAll(profile.getProperties());
1621                 }
1622                 profileProps.putAll(request.getUserProperties());
1623                 profileActivationContext.setUserProperties(profileProps);
1624             }
1625 
1626             Model parentModel = readParent(
1627                     activatedFileModel, activatedFileModel.getParent(), profileActivationContext, parentChain);
1628 
1629             // Now that we have read the parent, we can set the relative
1630             // path correctly if it was not set in the input model
1631             if (inputModel.getParent() != null && inputModel.getParent().getRelativePath() == null) {
1632                 String relPath;
1633                 if (isBuildRequest() && parentModel.getPomFile() != null && inputModel.getPomFile() != null) {
1634                     relPath = inputModel
1635                             .getPomFile()
1636                             .getParent()
1637                             .toAbsolutePath()
1638                             .relativize(
1639                                     parentModel.getPomFile().toAbsolutePath().getParent())
1640                             .toString();
1641                 } else {
1642                     relPath = "..";
1643                 }
1644                 inputModel = inputModel.withParent(inputModel.getParent().withRelativePath(relPath));
1645             }
1646 
1647             Model model = inheritanceAssembler.assembleModelInheritance(inputModel, parentModel, request, this);
1648 
1649             // profile activation
1650             profileActivationContext.setModel(model);
1651 
1652             // Activate profiles from the input model (before inheritance) to get only local profiles
1653             // Parent profiles are already added when the parent model is read
1654             List<Profile> localActivePomProfiles =
1655                     getActiveProfiles(inputModel.getProfiles(), profileActivationContext);
1656 
1657             // profile injection - inject all profiles (local + inherited) into the model
1658             List<Profile> activePomProfiles = getActiveProfiles(model.getProfiles(), profileActivationContext);
1659             model = profileInjector.injectProfiles(model, activePomProfiles, request, this);
1660             model = profileInjector.injectProfiles(model, activeExternalProfiles, request, this);
1661 
1662             // Track only the local profiles for this model
1663             // Use ModelProblemUtils.toId() to get groupId:artifactId:version format (without packaging)
1664             addActivePomProfiles(ModelProblemUtils.toId(model), localActivePomProfiles);
1665 
1666             // model interpolation
1667             Model resultModel = model;
1668             resultModel = interpolateModel(resultModel, request, this);
1669 
1670             // model normalization
1671             resultModel = modelNormalizer.mergeDuplicates(resultModel, request, this);
1672 
1673             // url normalization
1674             resultModel = modelUrlNormalizer.normalize(resultModel, request);
1675 
1676             // Now the fully interpolated model is available: reconfigure the resolver
1677             if (!resultModel.getRepositories().isEmpty()) {
1678                 List<String> oldRepos =
1679                         repositories.stream().map(Object::toString).toList();
1680                 mergeRepositories(resultModel, true);
1681                 List<String> newRepos =
1682                         repositories.stream().map(Object::toString).toList();
1683                 if (!Objects.equals(oldRepos, newRepos)) {
1684                     logger.debug("Replacing repositories from " + resultModel.getId() + "\n"
1685                             + newRepos.stream().map(s -> "    " + s).collect(Collectors.joining("\n")));
1686                 }
1687             }
1688 
1689             return resultModel;
1690         }
1691 
1692         private void addActivePomProfiles(String modelId, List<Profile> activePomProfiles) {
1693             if (activePomProfiles != null && !activePomProfiles.isEmpty()) {
1694                 // Track profiles by model ID
1695                 result.setActivePomProfiles(modelId, activePomProfiles);
1696             }
1697         }
1698 
1699         private List<Profile> getActiveProfiles(
1700                 Collection<Profile> interpolatedProfiles, DefaultProfileActivationContext profileActivationContext) {
1701             if (isBuildRequestWithActivation()) {
1702                 if (externalOrigin) {
1703                     // A model resolved to satisfy dependency resolution -- a dependency POM
1704                     // itself, or one of its parents, reached transitively -- evaluates profiles
1705                     // against a sandboxed activation context.  The sandbox:
1706                     //  - merges model properties into system property lookups (so POM-declared
1707                     //    <properties> drive activation via the existing property lookup chain),
1708                     //  - suppresses user properties (consumer -D flags must not activate
1709                     //    dependency profiles — they were not set for that artifact),
1710                     //  - disables file existence checks (publisher paths don't exist here).
1711                     // Model properties are merged into system properties rather than adding
1712                     // a separate lookup step in PropertyProfileActivator, because changing the
1713                     // activator would affect ALL profile evaluations (including the build's own
1714                     // project) and cause unintended profile activation when a POM declares a
1715                     // property that matches a profile's activation condition.
1716                     // File-activated profiles are pre-filtered (not just sandboxed) because
1717                     // returning false from exists() would incorrectly activate <missing> profiles.
1718                     // Condition profiles using exists()/missing() are also pre-filtered for the
1719                     // same reason: inside the sandbox, context.exists() always returns false, so
1720                     // missing(path) evaluates to !false = true and fires unconditionally.
1721                     // Repository stripping is intentionally omitted here: only legitimately-active
1722                     // profiles reach injection, and stripping their repositories would break the
1723                     // established project → dep1 → dep2 pattern where dep1 declares dep2's
1724                     // repository inside an activeByDefault or JDK-activated profile.
1725                     // See #13100, #13141.
1726                     Collection<Profile> nonFileProfiles = interpolatedProfiles.stream()
1727                             .filter(p -> p.getActivation() == null
1728                                     || (p.getActivation().getFile() == null && !hasFileConditionExpression(p)))
1729                             .toList();
1730                     ProfileActivationContext externalContext =
1731                             profileActivationContext.withoutUserPropertiesAndFilesystem();
1732                     return profileSelector.getActiveProfiles(nonFileProfiles, externalContext, this);
1733                 }
1734                 // TODO(#13146): repositories contributed by external-model profiles can shadow
1735                 // central; a WARN/FAIL policy for URL mismatches should be added separately.
1736                 return profileSelector.getActiveProfiles(interpolatedProfiles, profileActivationContext, this);
1737             } else {
1738                 // BUILD_CONSUMER: activate only deterministic profiles whose activation is a
1739                 // function of the build platform (OS, JDK version, activeByDefault) rather than
1740                 // of environment-specific state (file existence, property values, condition
1741                 // expressions).  This ensures that platform-dependent properties (e.g.
1742                 // ${swt.artifactId} from an OS-activated profile) are resolved before the
1743                 // coordinate validator runs, while keeping the consumer POM reproducible across
1744                 // environments.  Repositories from these profiles are stripped — they must not
1745                 // leak into the published consumer POM.
1746                 // Packaging-activated profiles are also excluded: the consumer POM builder
1747                 // handles them separately via inlinePackagingActivatedProfiles().
1748                 // See GH-13004.
1749                 Collection<Profile> deterministicProfiles = interpolatedProfiles.stream()
1750                         .filter(profile ->
1751                                 !hasFileOrPropertyOrConditionActivation(profile) && !hasPackagingActivation(profile))
1752                         .map(profile -> profile.withRepositories(List.of()).withPluginRepositories(List.of()))
1753                         .toList();
1754                 return profileSelector.getActiveProfiles(deterministicProfiles, profileActivationContext, this);
1755             }
1756         }
1757 
1758         /**
1759          * Determines whether the given profile's activation depends on file existence, a
1760          * property, or a condition expression, as opposed to being a function of the build
1761          * platform (JDK version, operating system) or {@code activeByDefault}.
1762          * <p>
1763          * Used for BUILD_CONSUMER model building to keep the consumer POM deterministic.
1764          * For external (dependency/parent/BOM) models, the sandbox context approach is used
1765          * instead — see {@link DefaultProfileActivationContext#withoutUserPropertiesAndFilesystem()}.
1766          */
1767         private static boolean hasFileOrPropertyOrConditionActivation(Profile profile) {
1768             Activation activation = profile.getActivation();
1769             return activation != null
1770                     && (activation.getFile() != null
1771                             || activation.getProperty() != null
1772                             || (activation.getCondition() != null
1773                                     && !activation.getCondition().isBlank()));
1774         }
1775 
1776         /**
1777          * Returns {@code true} if the profile's condition expression calls {@code exists()} or
1778          * {@code missing()}.  Such profiles must be pre-filtered out when building external
1779          * (repository-resolved) models: inside the sandbox, {@code context.exists()} always
1780          * returns {@code false}, so {@code missing(path)} evaluates to {@code !false = true}
1781          * and fires unconditionally — the same footgun that file-activated profiles expose.
1782          */
1783         private static boolean hasFileConditionExpression(Profile profile) {
1784             Activation a = profile.getActivation();
1785             if (a == null || a.getCondition() == null) {
1786                 return false;
1787             }
1788             String c = a.getCondition();
1789             return c.contains("exists(") || c.contains("missing(");
1790         }
1791 
1792         /**
1793          * Determines whether the given profile's activation includes a packaging condition.
1794          * Packaging-activated profiles are handled separately by the consumer POM builder's
1795          * {@code inlinePackagingActivatedProfiles()} and must not be activated during
1796          * BUILD_CONSUMER model building to avoid double-merging their contributions.
1797          */
1798         private static boolean hasPackagingActivation(Profile profile) {
1799             Activation activation = profile.getActivation();
1800             return activation != null && activation.getPackaging() != null;
1801         }
1802 
1803         Model readFileModel() throws ModelBuilderException {
1804             return readFileModel(new HashSet<>());
1805         }
1806 
1807         Model readFileModel(Set<Path> activeModelReads) throws ModelBuilderException {
1808             Model model = cache(request.getSource(), FILE, () -> doReadFileModel(activeModelReads));
1809             // set the file model in the result outside the cache
1810             result.setFileModel(model);
1811             return model;
1812         }
1813 
1814         @SuppressWarnings("checkstyle:methodlength")
1815         Model doReadFileModel(Set<Path> activeModelReads) throws ModelBuilderException {
1816             ModelSource modelSource = request.getSource();
1817             Model model;
1818             Path rootDirectory;
1819             boolean rootDirectoryFromSession = false;
1820             setSource(modelSource.getLocation());
1821             logger.debug("Reading file model from " + modelSource.getLocation());
1822             Path sourcePath = modelSource.getPath();
1823             // Use toAbsolutePath().normalize() for consistent path identity in activeModelReads.
1824             // This must match the normalization used in getEnhancedProperties() guard check
1825             // to prevent StackOverflowError from path representation mismatches (GH-12598).
1826             Path normalizedPath =
1827                     sourcePath != null ? sourcePath.toAbsolutePath().normalize() : null;
1828             boolean trackRead = normalizedPath != null && activeModelReads.add(normalizedPath);
1829             try {
1830                 try {
1831                     boolean strict = isBuildRequest();
1832                     try {
1833                         rootDirectory = request.getSession().getRootDirectory();
1834                         rootDirectoryFromSession = true;
1835                     } catch (IllegalStateException ignore) {
1836                         rootDirectory = modelSource.getPath();
1837                         while (rootDirectory != null && !Files.isDirectory(rootDirectory)) {
1838                             rootDirectory = rootDirectory.getParent();
1839                         }
1840                     }
1841                     try (InputStream is = modelSource.openStream()) {
1842                         model = modelProcessor.read(XmlReaderRequest.builder()
1843                                 .strict(strict)
1844                                 .location(modelSource.getLocation())
1845                                 .path(modelSource.getPath())
1846                                 .rootDirectory(rootDirectory)
1847                                 .inputStream(is)
1848                                 .transformer(new InterningTransformer(session))
1849                                 .build());
1850                     } catch (XmlReaderException e) {
1851                         if (!strict) {
1852                             throw e;
1853                         }
1854                         try (InputStream is = modelSource.openStream()) {
1855                             model = modelProcessor.read(XmlReaderRequest.builder()
1856                                     .strict(false)
1857                                     .location(modelSource.getLocation())
1858                                     .path(modelSource.getPath())
1859                                     .rootDirectory(rootDirectory)
1860                                     .inputStream(is)
1861                                     .transformer(new InterningTransformer(session))
1862                                     .build());
1863                         } catch (XmlReaderException ne) {
1864                             // still unreadable even in non-strict mode, rethrow original error
1865                             throw e;
1866                         }
1867 
1868                         add(
1869                                 Severity.ERROR,
1870                                 Version.V20,
1871                                 "Malformed POM " + modelSource.getLocation() + ": " + e.getMessage(),
1872                                 e);
1873                     }
1874                 } catch (XmlReaderException e) {
1875                     add(
1876                             Severity.FATAL,
1877                             Version.BASE,
1878                             "Non-parseable POM " + modelSource.getLocation() + ": " + e.getMessage(),
1879                             e);
1880                     throw newModelBuilderException();
1881                 } catch (IOException e) {
1882                     String msg = e.getMessage();
1883                     if (msg == null || msg.isEmpty()) {
1884                         // NOTE: There's java.nio.charset.MalformedInputException and sun.io.MalformedInputException
1885                         if (e.getClass().getName().endsWith("MalformedInputException")) {
1886                             msg = "Some input bytes do not match the file encoding.";
1887                         } else {
1888                             msg = e.getClass().getSimpleName();
1889                         }
1890                     }
1891                     add(Severity.FATAL, Version.BASE, "Non-readable POM " + modelSource.getLocation() + ": " + msg, e);
1892                     throw newModelBuilderException();
1893                 }
1894 
1895                 if (model.getModelVersion() == null) {
1896                     String namespace = model.getNamespaceUri();
1897                     if (namespace != null && namespace.startsWith(NAMESPACE_PREFIX)) {
1898                         model = model.withModelVersion(namespace.substring(NAMESPACE_PREFIX.length()));
1899                     }
1900                 }
1901 
1902                 if (isBuildRequest()) {
1903                     model = model.withPomFile(modelSource.getPath());
1904 
1905                     Parent parent = model.getParent();
1906                     if (parent != null) {
1907                         String groupId = parent.getGroupId();
1908                         String artifactId = parent.getArtifactId();
1909                         String version = parent.getVersion();
1910                         String path = parent.getRelativePath();
1911                         boolean versionContainsExpression = version != null && version.contains("${");
1912                         if ((groupId == null || artifactId == null || version == null || versionContainsExpression)
1913                                 && (path == null || !path.isEmpty())) {
1914                             Path pomFile = model.getPomFile();
1915                             Path relativePath = Paths.get(path != null ? path : "..");
1916                             Path pomPath = pomFile.resolveSibling(relativePath).normalize();
1917                             if (Files.isDirectory(pomPath)) {
1918                                 pomPath = modelProcessor.locateExistingPom(pomPath);
1919                             }
1920                             if (pomPath != null && Files.isRegularFile(pomPath)) {
1921                                 if (rootDirectoryFromSession && !isParentWithinRootDirectory(pomPath, rootDirectory)) {
1922                                     add(
1923                                             Severity.FATAL,
1924                                             Version.BASE,
1925                                             "Parent POM " + pomPath + " is located above the root directory "
1926                                                     + rootDirectory
1927                                                     + ". This setup is invalid when a .mvn directory exists in a subdirectory.",
1928                                             parent.getLocation("relativePath"));
1929                                     throw newModelBuilderException();
1930                                 }
1931 
1932                                 Model parentModel =
1933                                         derive(Sources.buildSource(pomPath)).readFileModel(activeModelReads);
1934                                 String parentGroupId = getGroupId(parentModel);
1935                                 String parentArtifactId = parentModel.getArtifactId();
1936                                 String parentVersion = getVersion(parentModel);
1937                                 if ((groupId == null || groupId.equals(parentGroupId))
1938                                         && (artifactId == null || artifactId.equals(parentArtifactId))
1939                                         && (version == null
1940                                                 || version.equals(parentVersion)
1941                                                 || versionContainsExpression)) {
1942                                     model = model.withParent(parent.with()
1943                                             .groupId(parentGroupId)
1944                                             .artifactId(parentArtifactId)
1945                                             .version(parentVersion)
1946                                             .build());
1947                                 } else {
1948                                     mismatchRelativePathAndGA(model, parent, parentGroupId, parentArtifactId);
1949                                 }
1950                             } else {
1951                                 if (!MODEL_VERSION_4_0_0.equals(model.getModelVersion()) && path != null) {
1952                                     wrongParentRelativePath(model);
1953                                 }
1954                             }
1955                         }
1956                     }
1957 
1958                     // subprojects discovery
1959                     if (!hasSubprojectsDefined(model)
1960                             // only discover subprojects if POM > 4.0.0
1961                             && !MODEL_VERSION_4_0_0.equals(model.getModelVersion())
1962                             // and if packaging is POM (we check type, but the session is not yet available,
1963                             // we would require the project realm if we want to support extensions
1964                             && Type.POM.equals(model.getPackaging())
1965                             // and if discovery is not disabled via property
1966                             && Features.discoverSubprojects(request.getUserProperties())) {
1967                         List<String> subprojects = new ArrayList<>();
1968                         try (Stream<Path> files = Files.list(model.getProjectDirectory())) {
1969                             for (Path f : files.toList()) {
1970                                 if (Files.isDirectory(f)) {
1971                                     Path subproject = modelProcessor.locateExistingPom(f);
1972                                     if (subproject != null) {
1973                                         subprojects.add(f.getFileName().toString());
1974                                     }
1975                                 }
1976                             }
1977                             if (!subprojects.isEmpty()) {
1978                                 model = model.withSubprojects(subprojects);
1979                             }
1980                         } catch (IOException e) {
1981                             add(Severity.FATAL, Version.V41, "Error discovering subprojects", e);
1982                         }
1983                     }
1984 
1985                     // Enhanced property resolution with profile activation for CI-friendly versions and repository URLs
1986                     // This includes directory properties, profile properties, and user properties
1987                     Map<String, String> properties = getEnhancedProperties(model, rootDirectory, activeModelReads);
1988 
1989                     // CI friendly version processing with profile-aware properties
1990                     model = model.with()
1991                             .version(replaceCiFriendlyVersion(properties, model.getVersion()))
1992                             .parent(
1993                                     model.getParent() != null
1994                                             ? model.getParent()
1995                                                     .withVersion(replaceCiFriendlyVersion(
1996                                                             properties,
1997                                                             model.getParent().getVersion()))
1998                                             : null)
1999                             .build();
2000 
2001                     // Repository URL interpolation with the same profile-aware properties
2002                     UnaryOperator<String> callback = properties::get;
2003                     model = model.with()
2004                             .repositories(interpolateRepository(model.getRepositories(), callback))
2005                             .pluginRepositories(interpolateRepository(model.getPluginRepositories(), callback))
2006                             .profiles(map(model.getProfiles(), this::interpolateRepository, callback))
2007                             .distributionManagement(interpolateRepository(model.getDistributionManagement(), callback))
2008                             .build();
2009                     // Override model properties with user properties (use request properties
2010                     // to ensure consistency with model interpolation)
2011                     Map<String, String> userProps = request.getUserProperties();
2012                     Map<String, String> newProps = merge(model.getProperties(), userProps);
2013                     if (newProps != null) {
2014                         model = model.withProperties(newProps);
2015                     }
2016                     model = model.withProfiles(merge(model.getProfiles(), userProps));
2017                 } else {
2018                     if (modelSource.getPath() != null) {
2019                         model = model.withPomFile(modelSource.getPath());
2020                     }
2021                     if (rootDirectory != null) {
2022                         try {
2023                             Map<String, String> properties =
2024                                     getEnhancedProperties(model, rootDirectory, activeModelReads);
2025                             model = model.with()
2026                                     .version(replaceCiFriendlyVersion(properties, model.getVersion()))
2027                                     .parent(
2028                                             model.getParent() != null
2029                                                     ? model.getParent()
2030                                                             .withVersion(replaceCiFriendlyVersion(
2031                                                                     properties,
2032                                                                     model.getParent()
2033                                                                             .getVersion()))
2034                                                     : null)
2035                                     .build();
2036                         } catch (ModelBuilderException e) {
2037                             logger.debug(
2038                                     "Could not read root model properties for CI-friendly" + " version interpolation",
2039                                     e);
2040                         }
2041                     }
2042                 }
2043 
2044                 for (var transformer : transformers) {
2045                     model = transformer.transformFileModel(model);
2046                 }
2047 
2048                 setSource(model);
2049                 modelValidator.validateFileModel(
2050                         session,
2051                         model,
2052                         isBuildRequest()
2053                                 ? ModelValidator.VALIDATION_LEVEL_STRICT
2054                                 : ModelValidator.VALIDATION_LEVEL_MINIMAL,
2055                         this);
2056                 InternalSession internalSession = InternalSession.from(session);
2057                 if (Features.mavenMaven3Personality(internalSession.getSession().getConfigProperties())
2058                         && Objects.equals(ModelBuilder.MODEL_VERSION_4_1_0, model.getModelVersion())) {
2059                     add(Severity.FATAL, Version.BASE, "Maven3 mode: no higher model version than 4.0.0 allowed");
2060                 }
2061                 if (hasFatalErrors()) {
2062                     throw newModelBuilderException();
2063                 }
2064 
2065                 return model;
2066             } finally {
2067                 if (trackRead) {
2068                     activeModelReads.remove(normalizedPath);
2069                 }
2070             }
2071         }
2072 
2073         private DistributionManagement interpolateRepository(
2074                 DistributionManagement distributionManagement, UnaryOperator<String> callback) {
2075             return distributionManagement == null
2076                     ? null
2077                     : distributionManagement
2078                             .with()
2079                             .repository((DeploymentRepository)
2080                                     interpolateRepository(distributionManagement.getRepository(), callback))
2081                             .snapshotRepository((DeploymentRepository)
2082                                     interpolateRepository(distributionManagement.getSnapshotRepository(), callback))
2083                             .build();
2084         }
2085 
2086         private Profile interpolateRepository(Profile profile, UnaryOperator<String> callback) {
2087             return profile == null
2088                     ? null
2089                     : profile.with()
2090                             .repositories(interpolateRepository(profile.getRepositories(), callback))
2091                             .pluginRepositories(interpolateRepository(profile.getPluginRepositories(), callback))
2092                             .build();
2093         }
2094 
2095         private List<Repository> interpolateRepository(List<Repository> repositories, UnaryOperator<String> callback) {
2096             return map(repositories, this::interpolateRepository, callback);
2097         }
2098 
2099         private Repository interpolateRepository(Repository repository, UnaryOperator<String> callback) {
2100             return repository == null
2101                     ? null
2102                     : repository
2103                             .with()
2104                             .id(interpolator.interpolate(repository.getId(), callback))
2105                             .url(interpolator.interpolate(repository.getUrl(), callback))
2106                             .build();
2107         }
2108 
2109         /**
2110          * Merges a list of model profiles with user-defined properties.
2111          * For each property defined in both the model and user properties, the user property value
2112          * takes precedence and overrides the model value.
2113          *
2114          * @param profiles list of profiles from the model
2115          * @param userProperties map of user-defined properties that override model properties
2116          * @return a new list containing profiles with overridden properties if changes were made,
2117          *         or the original list if no overrides were needed
2118          */
2119         List<Profile> merge(List<Profile> profiles, Map<String, String> userProperties) {
2120             List<Profile> result = null;
2121             for (int i = 0; i < profiles.size(); i++) {
2122                 Profile profile = profiles.get(i);
2123                 Map<String, String> props = merge(profile.getProperties(), userProperties);
2124                 if (props != null) {
2125                     Profile merged = profile.withProperties(props);
2126                     if (result == null) {
2127                         result = new ArrayList<>(profiles);
2128                     }
2129                     result.set(i, merged);
2130                 }
2131             }
2132             return result != null ? result : profiles;
2133         }
2134 
2135         /**
2136          * Merges model properties with user properties, giving precedence to user properties.
2137          * For any property key present in both maps, the user property value will override
2138          * the model property value when they differ.
2139          *
2140          * @param properties properties defined in the model
2141          * @param userProperties user-defined properties that override model properties
2142          * @return a new map with model properties overridden by user properties if changes were needed,
2143          *         or null if no overrides were needed
2144          */
2145         Map<String, String> merge(Map<String, String> properties, Map<String, String> userProperties) {
2146             Map<String, String> result = null;
2147             for (Map.Entry<String, String> entry : properties.entrySet()) {
2148                 String key = entry.getKey();
2149                 String value = userProperties.get(key);
2150                 if (value != null && !Objects.equals(value, entry.getValue())) {
2151                     if (result == null) {
2152                         result = new LinkedHashMap<>(properties);
2153                     }
2154                     result.put(entry.getKey(), value);
2155                 }
2156             }
2157             return result;
2158         }
2159 
2160         Model readRawModel() throws ModelBuilderException {
2161             // ensure file model is available
2162             readFileModel();
2163             Model model = cache(request.getSource(), RAW, this::doReadRawModel);
2164             // set the raw model in the result outside the cache
2165             result.setRawModel(model);
2166             return model;
2167         }
2168 
2169         private Model doReadRawModel() throws ModelBuilderException {
2170             Model rawModel = readFileModel();
2171 
2172             if (!MODEL_VERSION_4_0_0.equals(rawModel.getModelVersion()) && isBuildRequest()) {
2173                 rawModel = transformFileToRaw(rawModel);
2174             }
2175 
2176             for (var transformer : transformers) {
2177                 rawModel = transformer.transformRawModel(rawModel);
2178             }
2179 
2180             modelValidator.validateRawModel(
2181                     session,
2182                     rawModel,
2183                     isBuildRequest() ? ModelValidator.VALIDATION_LEVEL_STRICT : ModelValidator.VALIDATION_LEVEL_MINIMAL,
2184                     this);
2185 
2186             if (hasFatalErrors()) {
2187                 throw newModelBuilderException();
2188             }
2189 
2190             return rawModel;
2191         }
2192 
2193         /**
2194          * Record to store both the parent model and its activated profiles for caching.
2195          */
2196         private record ParentModelWithProfiles(Model model, List<Profile> activatedProfiles) {}
2197 
2198         /**
2199          * Reads the request source's parent with cycle detection.
2200          */
2201         Model readAsParentModel(DefaultProfileActivationContext profileActivationContext, Set<String> parentChain)
2202                 throws ModelBuilderException {
2203             // Partition the cache by externalOrigin so a parent model resolved while building
2204             // the operator's own project never shares an entry with the same source resolved
2205             // while resolving a dependency: the two contexts activate profiles differently (see
2206             // getActiveProfiles below), and the model built for one must not be reused for the
2207             // other, even though both are keyed off the same underlying source.
2208             //
2209             // This partition is a defensive backstop, not the primary guard: cache(source, tag,
2210             // supplier) additionally scopes each entry to the top-level request (see
2211             // getOuterRequest()), which falls back to the request object's own identity once its
2212             // RequestTrace has no further request-typed ancestor. Two independently-built request
2213             // objects therefore land in different buckets regardless of this tag, and never reach
2214             // this collision in practice; the tag matters only when two reads end up sharing a
2215             // request object (as derive() calls from a common ancestor can), which is why it is
2216             // kept even though the getActiveProfiles gate above already decides the correct
2217             // activation for each read on its own.
2218             Map<DefaultProfileActivationContext.Record, ParentModelWithProfiles> parentsPerContext =
2219                     cache(request.getSource(), externalOrigin ? PARENT_EXTERNAL : PARENT, ConcurrentHashMap::new);
2220 
2221             for (Map.Entry<DefaultProfileActivationContext.Record, ParentModelWithProfiles> e :
2222                     parentsPerContext.entrySet()) {
2223                 if (e.getKey().matches(profileActivationContext)) {
2224                     ParentModelWithProfiles cached = e.getValue();
2225                     // CRITICAL: On cache hit, we need to replay the cached record's keys into the
2226                     // current recording context. The matches() method already re-evaluated the
2227                     // conditions and recorded some keys in ctx, but we also need to ensure all
2228                     // the keys from the cached record are recorded in the current context.
2229                     if (profileActivationContext.record != null) {
2230                         replayRecordIntoContext(e.getKey(), profileActivationContext);
2231                     }
2232                     // Add the activated profiles from cache to the result
2233                     // Use ModelProblemUtils.toId() to get groupId:artifactId:version format (without packaging)
2234                     addActivePomProfiles(ModelProblemUtils.toId(cached.model()), cached.activatedProfiles());
2235                     return cached.model();
2236                 }
2237             }
2238 
2239             // Cache miss: process the parent model
2240             // CRITICAL: Use a separate recording context to avoid recording intermediate keys
2241             // that aren't essential to the final result. Only replay the final essential keys
2242             // into the parent recording context to maintain clean cache keys and avoid
2243             // over-recording during parent model processing.
2244             DefaultProfileActivationContext ctx = profileActivationContext.start();
2245             ParentModelWithProfiles modelWithProfiles = doReadAsParentModel(ctx, parentChain);
2246             DefaultProfileActivationContext.Record record = ctx.stop();
2247             replayRecordIntoContext(record, profileActivationContext);
2248 
2249             parentsPerContext.put(record, modelWithProfiles);
2250             // Use ModelProblemUtils.toId() to get groupId:artifactId:version format (without packaging)
2251             addActivePomProfiles(
2252                     ModelProblemUtils.toId(modelWithProfiles.model()), modelWithProfiles.activatedProfiles());
2253             return modelWithProfiles.model();
2254         }
2255 
2256         private ParentModelWithProfiles doReadAsParentModel(
2257                 DefaultProfileActivationContext childProfileActivationContext, Set<String> parentChain)
2258                 throws ModelBuilderException {
2259             Model raw = readRawModel();
2260             Model parentData = readParent(raw, raw.getParent(), childProfileActivationContext, parentChain);
2261             Model parent = new DefaultInheritanceAssembler(new DefaultInheritanceAssembler.InheritanceModelMerger() {
2262                         @Override
2263                         protected void mergeModel_Modules(
2264                                 Model.Builder builder,
2265                                 Model target,
2266                                 Model source,
2267                                 boolean sourceDominant,
2268                                 Map<Object, Object> context) {}
2269 
2270                         @Override
2271                         protected void mergeModel_Subprojects(
2272                                 Model.Builder builder,
2273                                 Model target,
2274                                 Model source,
2275                                 boolean sourceDominant,
2276                                 Map<Object, Object> context) {}
2277                     })
2278                     .assembleModelInheritance(raw, parentData, request, this);
2279 
2280             // Profile injection SHOULD be performed on parent models to ensure
2281             // that profile content becomes part of the parent model before inheritance.
2282             // This ensures proper precedence: child elements override parent elements,
2283             // including elements that came from parent profiles.
2284             //
2285             // Use the child's activation context (passed as parameter) to determine
2286             // which parent profiles should be active, ensuring consistency.
2287             List<Profile> parentActivePomProfiles =
2288                     getActiveProfiles(parent.getProfiles(), childProfileActivationContext);
2289 
2290             // Inject profiles into parent model
2291             Model injectedParentModel = profileInjector
2292                     .injectProfiles(parent, parentActivePomProfiles, request, this)
2293                     .withProfiles(List.of()); // Remove profiles after injection to avoid double-processing
2294 
2295             // Note: addActivePomProfiles() will be called by the caller for cache miss case
2296             return new ParentModelWithProfiles(injectedParentModel.withParent(null), parentActivePomProfiles);
2297         }
2298 
2299         private Model importDependencyManagement(Model model, Collection<String> importIds) {
2300             DependencyManagement depMgmt = model.getDependencyManagement();
2301 
2302             if (depMgmt == null) {
2303                 return model;
2304             }
2305 
2306             String importing = model.getGroupId() + ':' + model.getArtifactId() + ':' + model.getVersion();
2307 
2308             importIds.add(importing);
2309 
2310             List<DependencyManagement> importMgmts = null;
2311 
2312             List<Dependency> deps = new ArrayList<>(depMgmt.getDependencies());
2313             for (Iterator<Dependency> it = deps.iterator(); it.hasNext(); ) {
2314                 Dependency dependency = it.next();
2315 
2316                 if (!(("pom".equals(dependency.getType()) && "import".equals(dependency.getScope()))
2317                         || "bom".equals(dependency.getType()))) {
2318                     continue;
2319                 }
2320 
2321                 it.remove();
2322 
2323                 DependencyManagement importMgmt = loadDependencyManagement(dependency, importIds);
2324 
2325                 if (importMgmt != null) {
2326                     if (importMgmts == null) {
2327                         importMgmts = new ArrayList<>();
2328                     }
2329 
2330                     importMgmts.add(importMgmt);
2331                 }
2332             }
2333 
2334             importIds.remove(importing);
2335 
2336             model = model.withDependencyManagement(
2337                     model.getDependencyManagement().withDependencies(deps));
2338 
2339             return dependencyManagementImporter.importManagement(
2340                     model, importMgmts, request, deduplicatingImportProblemCollector());
2341         }
2342 
2343         private ModelProblemCollector deduplicatingImportProblemCollector() {
2344             return new DeduplicatingImportProblemCollector();
2345         }
2346 
2347         /**
2348          * A {@link ModelProblemCollector} wrapper that deduplicates BOM import conflict warnings
2349          * within a single top-level build.  When a warning originates from a reactor module,
2350          * it is routed to that module's own problem collector so the warning appears next to the
2351          * declaration rather than being repeated for every inheriting child.  Non-warning problems
2352          * and warnings without a resolvable source are forwarded to the enclosing
2353          * {@link ModelBuilderSessionState} unchanged.
2354          */
2355         private class DeduplicatingImportProblemCollector implements ModelProblemCollector {
2356             @Override
2357             public ProblemCollector<ModelProblem> getProblemCollector() {
2358                 return ModelBuilderSessionState.this.getProblemCollector();
2359             }
2360 
2361             @Override
2362             public void add(
2363                     BuilderProblem.Severity severity,
2364                     ModelProblem.Version version,
2365                     String message,
2366                     InputLocation location,
2367                     Exception exception) {
2368                 if (severity == Severity.WARNING && location != null && location.getSource() != null) {
2369                     var source = location.getSource();
2370                     String sourceLocation = source.getLocation();
2371                     ImportWarningKey key = new ImportWarningKey(
2372                             message,
2373                             sourceLocation,
2374                             source.getModelId(),
2375                             location.getLineNumber(),
2376                             location.getColumnNumber());
2377                     if (!reportedImportWarnings.add(key)) {
2378                         return;
2379                     }
2380                     ProblemCollector<ModelProblem> collector =
2381                             sourceLocation != null ? reactorProblemCollectors.get(sourceLocation) : null;
2382                     if (collector != null) {
2383                         collector.reportProblem(new DefaultModelProblem(
2384                                 message,
2385                                 severity,
2386                                 version,
2387                                 sourceLocation,
2388                                 location.getLineNumber(),
2389                                 location.getColumnNumber(),
2390                                 source.getModelId(),
2391                                 exception));
2392                         return;
2393                     }
2394                 }
2395                 ModelBuilderSessionState.this.add(severity, version, message, location, exception);
2396             }
2397 
2398             @Override
2399             public ModelBuilderException newModelBuilderException() {
2400                 return ModelBuilderSessionState.this.newModelBuilderException();
2401             }
2402 
2403             @Override
2404             public void setSource(String location) {
2405                 ModelBuilderSessionState.this.setSource(location);
2406             }
2407 
2408             @Override
2409             public void setSource(Model model) {
2410                 ModelBuilderSessionState.this.setSource(model);
2411             }
2412 
2413             @Override
2414             public String getSource() {
2415                 return ModelBuilderSessionState.this.getSource();
2416             }
2417 
2418             @Override
2419             public void setRootModel(Model model) {
2420                 ModelBuilderSessionState.this.setRootModel(model);
2421             }
2422 
2423             @Override
2424             public Model getRootModel() {
2425                 return ModelBuilderSessionState.this.getRootModel();
2426             }
2427         }
2428 
2429         /**
2430          * Registers the problem collector under both the location string (path form) and
2431          * the URI form of the source.  Import warnings produced by
2432          * {@link DefaultDependencyManagementImporter} carry whichever form the resolver
2433          * happened to record, so both keys are registered as a safety net to ensure a
2434          * lookup in {@link DeduplicatingImportProblemCollector#add} always finds the
2435          * declaring model's collector.
2436          */
2437         private void registerReactorProblemCollector(
2438                 ModelSource source, ProblemCollector<ModelProblem> problemCollector) {
2439             if (source.getLocation() != null) {
2440                 reactorProblemCollectors.put(source.getLocation(), problemCollector);
2441             }
2442             if (source.getPath() != null) {
2443                 reactorProblemCollectors.put(source.getPath().toUri().toString(), problemCollector);
2444             }
2445         }
2446 
2447         private DependencyManagement loadDependencyManagement(Dependency dependency, Collection<String> importIds) {
2448             String groupId = dependency.getGroupId();
2449             String artifactId = dependency.getArtifactId();
2450             String version = dependency.getVersion();
2451 
2452             if (groupId == null || groupId.isEmpty()) {
2453                 add(
2454                         Severity.ERROR,
2455                         Version.BASE,
2456                         "'dependencyManagement.dependencies.dependency.groupId' for " + dependency.getManagementKey()
2457                                 + " is missing.",
2458                         dependency.getLocation(""));
2459                 return null;
2460             }
2461             if (artifactId == null || artifactId.isEmpty()) {
2462                 add(
2463                         Severity.ERROR,
2464                         Version.BASE,
2465                         "'dependencyManagement.dependencies.dependency.artifactId' for " + dependency.getManagementKey()
2466                                 + " is missing.",
2467                         dependency.getLocation(""));
2468                 return null;
2469             }
2470             if (version == null || version.isEmpty()) {
2471                 add(
2472                         Severity.ERROR,
2473                         Version.BASE,
2474                         "'dependencyManagement.dependencies.dependency.version' for " + dependency.getManagementKey()
2475                                 + " is missing.",
2476                         dependency.getLocation(""));
2477                 return null;
2478             }
2479 
2480             String imported = groupId + ':' + artifactId + ':' + version;
2481 
2482             if (importIds.contains(imported)) {
2483                 StringBuilder message =
2484                         new StringBuilder("The dependencies of type=pom and with scope=import form a cycle: ");
2485                 for (String modelId : importIds) {
2486                     message.append(modelId).append(" -> ");
2487                 }
2488                 message.append(imported);
2489                 add(Severity.ERROR, Version.BASE, message.toString());
2490                 return null;
2491             }
2492 
2493             Model importModel = cache(
2494                     repositories,
2495                     groupId,
2496                     artifactId,
2497                     version,
2498                     null,
2499                     IMPORT,
2500                     () -> doLoadDependencyManagement(dependency, groupId, artifactId, version, importIds));
2501             DependencyManagement importMgmt = importModel != null ? importModel.getDependencyManagement() : null;
2502             if (importMgmt == null) {
2503                 importMgmt = DependencyManagement.newInstance();
2504             }
2505 
2506             // [MNG-5600] Dependency management import should support exclusions.
2507             List<Exclusion> exclusions = dependency.getExclusions();
2508             if (importMgmt != null && !exclusions.isEmpty()) {
2509                 // Dependency excluded from import.
2510                 List<Dependency> dependencies = importMgmt.getDependencies().stream()
2511                         .filter(candidate -> exclusions.stream().noneMatch(exclusion -> match(exclusion, candidate)))
2512                         .map(candidate -> addExclusions(candidate, exclusions))
2513                         .collect(Collectors.toList());
2514                 importMgmt = importMgmt.withDependencies(dependencies);
2515             }
2516 
2517             return DependencyManagement.newBuilder(importMgmt, true)
2518                     .importedFrom(dependency.getLocation(""))
2519                     .build();
2520         }
2521 
2522         @SuppressWarnings("checkstyle:parameternumber")
2523         private Model doLoadDependencyManagement(
2524                 Dependency dependency,
2525                 String groupId,
2526                 String artifactId,
2527                 String version,
2528                 Collection<String> importIds) {
2529             Model importModel;
2530             ModelSource importSource;
2531             boolean repositoryResolved = false;
2532             try {
2533                 importSource = resolveReactorModel(groupId, artifactId, version);
2534                 if (importSource == null) {
2535                     importSource = modelResolver.resolveModel(
2536                             request.getSession(), repositories, dependency, new AtomicReference<>());
2537                     repositoryResolved = true;
2538                 }
2539             } catch (ModelBuilderException | ModelResolverException e) {
2540                 StringBuilder buffer = new StringBuilder(256);
2541                 buffer.append("Non-resolvable import POM");
2542                 if (!containsCoordinates(e.getMessage(), groupId, artifactId, version)) {
2543                     buffer.append(' ').append(ModelProblemUtils.toId(groupId, artifactId, version));
2544                 }
2545                 buffer.append(": ").append(e.getMessage());
2546 
2547                 add(Severity.ERROR, Version.BASE, buffer.toString(), dependency.getLocation(""), e);
2548                 return null;
2549             }
2550 
2551             Path rootDirectory;
2552             try {
2553                 rootDirectory = request.getSession().getRootDirectory();
2554             } catch (IllegalStateException e) {
2555                 rootDirectory = null;
2556             }
2557             if (request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT && rootDirectory != null) {
2558                 Path sourcePath = importSource.getPath();
2559                 if (sourcePath != null && sourcePath.startsWith(rootDirectory)) {
2560                     add(
2561                             Severity.WARNING,
2562                             Version.BASE,
2563                             "BOM imports from within reactor should be avoided",
2564                             dependency.getLocation(""));
2565                 }
2566             }
2567 
2568             final ModelBuilderResult importResult;
2569             try {
2570                 ModelBuilderRequest importRequest = ModelBuilderRequest.builder()
2571                         .session(request.getSession())
2572                         .requestType(ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY)
2573                         .systemProperties(request.getSystemProperties())
2574                         .userProperties(request.getUserProperties())
2575                         .source(importSource)
2576                         .repositories(repositories)
2577                         .build();
2578                 ModelBuilderSessionState modelBuilderSession = derive(importRequest);
2579                 // build the effective model
2580                 modelBuilderSession.buildEffectiveModel(importIds);
2581                 importResult = modelBuilderSession.result;
2582             } catch (ModelBuilderException e) {
2583                 return null;
2584             }
2585 
2586             importModel = importResult.getEffectiveModel();
2587 
2588             if (repositoryResolved) {
2589                 importModel = rejectSystemScopeFromRepositoryImport(importModel, dependency);
2590             }
2591 
2592             return importModel;
2593         }
2594 
2595         /**
2596          * Dependency management imported (as a BOM) from a POM resolved from a repository, rather
2597          * than from the local reactor, may not declare {@code system} scope or a
2598          * {@code systemPath} for a managed dependency: by default, offending entries are dropped
2599          * from the imported management (so a cached import cannot re-introduce them) and a
2600          * warning is emitted, unless the
2601          * {@code maven.repository.dependencyManagement.allowSystemScope} user property is set to
2602          * {@code true}, in which case they are imported as before, with a warning. Dependency
2603          * management imported from the local reactor is not affected.
2604          */
2605         private Model rejectSystemScopeFromRepositoryImport(Model importModel, Dependency dependency) {
2606             DependencyManagement importMgmt = importModel != null ? importModel.getDependencyManagement() : null;
2607             if (importMgmt == null) {
2608                 return importModel;
2609             }
2610             String offending = importMgmt.getDependencies().stream()
2611                     .filter(DefaultModelBuilder::usesSystemScope)
2612                     .map(Dependency::getManagementKey)
2613                     .collect(Collectors.joining(", "));
2614             if (offending.isEmpty()) {
2615                 return importModel;
2616             }
2617             String allow = request.getUserProperties()
2618                     .getOrDefault(
2619                             Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE,
2620                             request.getSystemProperties()
2621                                     .get(Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE));
2622             if (Boolean.parseBoolean(allow)) {
2623                 add(
2624                         Severity.WARNING,
2625                         Version.V41,
2626                         "The import POM " + ModelProblemUtils.toId(importModel)
2627                                 + " declares 'system' scope or 'systemPath' for " + offending
2628                                 + "; importing it because the '"
2629                                 + Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE
2630                                 + "' user property is set to 'true'.",
2631                         dependency.getLocation(""));
2632                 return importModel;
2633             }
2634             add(
2635                     Severity.WARNING,
2636                     Version.V41,
2637                     "The import POM " + ModelProblemUtils.toId(importModel)
2638                             + " was resolved from a repository and declares 'system' scope or 'systemPath' for "
2639                             + offending + "; these entries are not imported. Remove the 'system' scope from the"
2640                             + " imported POM, or set the '"
2641                             + Constants.MAVEN_REPOSITORY_DEPENDENCY_MANAGEMENT_ALLOW_SYSTEM_SCOPE
2642                             + "' user property to 'true' to import them as before.",
2643                     dependency.getLocation(""));
2644             List<Dependency> retained = importMgmt.getDependencies().stream()
2645                     .filter(d -> !usesSystemScope(d))
2646                     .collect(Collectors.toList());
2647             return importModel.withDependencyManagement(importMgmt.withDependencies(retained));
2648         }
2649 
2650         ModelSource resolveReactorModel(String groupId, String artifactId, String version)
2651                 throws ModelBuilderException {
2652             Set<ModelSource> sources = mappedSources.get(new GAKey(groupId, artifactId));
2653             if (sources != null) {
2654                 for (ModelSource source : sources) {
2655                     Model model = derive(source).readRawModel();
2656                     if (Objects.equals(getVersion(model), version)) {
2657                         return source;
2658                     }
2659                 }
2660                 // TODO: log a warning ?
2661             }
2662             return null;
2663         }
2664 
2665         private <T> T cache(
2666                 List<RemoteRepository> repositories,
2667                 String groupId,
2668                 String artifactId,
2669                 String version,
2670                 String classifier,
2671                 String tag,
2672                 Supplier<T> supplier) {
2673             RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(session, request);
2674             try {
2675                 RgavCacheKey r = new RgavCacheKey(
2676                         session, trace.mvnTrace(), repositories, groupId, artifactId, version, classifier, tag);
2677                 SourceResponse<RgavCacheKey, T> response =
2678                         InternalSession.from(session).request(r, tr -> new SourceResponse<>(tr, supplier.get()));
2679                 return response.response;
2680             } finally {
2681                 RequestTraceHelper.exit(trace);
2682             }
2683         }
2684 
2685         private <T> T cache(Source source, String tag, Supplier<T> supplier) throws ModelBuilderException {
2686             RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(session, request);
2687             try {
2688                 SourceCacheKey r = new SourceCacheKey(session, trace.mvnTrace(), source, tag);
2689                 SourceResponse<SourceCacheKey, T> response =
2690                         InternalSession.from(session).request(r, tr -> new SourceResponse<>(tr, supplier.get()));
2691                 return response.response;
2692             } finally {
2693                 RequestTraceHelper.exit(trace);
2694             }
2695         }
2696 
2697         boolean isBuildRequest() {
2698             return request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_PROJECT
2699                     || request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_EFFECTIVE
2700                     || request.getRequestType() == ModelBuilderRequest.RequestType.BUILD_CONSUMER;
2701         }
2702 
2703         boolean isBuildRequestWithActivation() {
2704             return request.getRequestType() != ModelBuilderRequest.RequestType.BUILD_CONSUMER;
2705         }
2706 
2707         /**
2708          * Replays the keys from a cached record into the current recording context.
2709          * This ensures that when there's a cache hit, all the keys that were originally
2710          * accessed during the cached computation are recorded in the current context.
2711          */
2712         private void replayRecordIntoContext(
2713                 DefaultProfileActivationContext.Record cachedRecord, DefaultProfileActivationContext targetContext) {
2714             if (targetContext.record == null) {
2715                 return; // Target context is not recording
2716             }
2717 
2718             // Replay all the recorded keys from the cached record into the target context's record
2719             // We need to access the mutable maps in the target context's record
2720             DefaultProfileActivationContext.Record targetRecord = targetContext.record;
2721 
2722             // Replay active profiles
2723             cachedRecord.usedActiveProfiles.forEach(targetRecord.usedActiveProfiles::putIfAbsent);
2724 
2725             // Replay inactive profiles
2726             cachedRecord.usedInactiveProfiles.forEach(targetRecord.usedInactiveProfiles::putIfAbsent);
2727 
2728             // Replay system properties
2729             cachedRecord.usedSystemProperties.forEach(targetRecord.usedSystemProperties::putIfAbsent);
2730 
2731             // Replay user properties
2732             cachedRecord.usedUserProperties.forEach(targetRecord.usedUserProperties::putIfAbsent);
2733 
2734             // Replay model properties
2735             cachedRecord.usedModelProperties.forEach(targetRecord.usedModelProperties::putIfAbsent);
2736 
2737             // Replay model infos
2738             cachedRecord.usedModelInfos.forEach(targetRecord.usedModelInfos::putIfAbsent);
2739 
2740             // Replay exists checks
2741             cachedRecord.usedExists.forEach(targetRecord.usedExists::putIfAbsent);
2742         }
2743     }
2744 
2745     @SuppressWarnings("deprecation")
2746     private static List<String> getSubprojects(Model activated) {
2747         List<String> subprojects = activated.getSubprojects();
2748         if (subprojects.isEmpty()) {
2749             subprojects = activated.getModules();
2750         }
2751         return subprojects;
2752     }
2753 
2754     /**
2755      * Checks whether the model has a non-empty {@code <subprojects>} or {@code <modules>} element.
2756      * <p>
2757      * When this returns {@code false} and auto-discovery is enabled (via
2758      * {@link Features#discoverSubprojects(Map)}), Maven will scan subdirectories
2759      * for POM files. Users who want to suppress discovery without listing subprojects
2760      * can set {@code -Dmaven.project.discoverSubprojects=false}.
2761      */
2762     @SuppressWarnings("deprecation")
2763     private static boolean hasSubprojectsDefined(Model model) {
2764         return !model.getSubprojects().isEmpty() || !model.getModules().isEmpty();
2765     }
2766 
2767     @Override
2768     public Model buildRawModel(ModelBuilderRequest request) throws ModelBuilderException {
2769         RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(request.getSession(), request);
2770         try {
2771             ModelBuilderSessionState build = new ModelBuilderSessionState(request);
2772             Model model = build.readRawModel();
2773             if (build.hasErrors()) {
2774                 throw build.newModelBuilderException();
2775             }
2776             return model;
2777         } finally {
2778             RequestTraceHelper.exit(trace);
2779         }
2780     }
2781 
2782     static String getGroupId(Model model) {
2783         String groupId = model.getGroupId();
2784         if (groupId == null && model.getParent() != null) {
2785             groupId = model.getParent().getGroupId();
2786         }
2787         return groupId;
2788     }
2789 
2790     static String getVersion(Model model) {
2791         String version = model.getVersion();
2792         if (version == null && model.getParent() != null) {
2793             version = model.getParent().getVersion();
2794         }
2795         return version;
2796     }
2797 
2798     /**
2799      * Whether the model this request builds was resolved from a repository rather than supplied to
2800      * Maven. {@link org.apache.maven.api.services.Sources#resolvedSource} carries the resolved
2801      * model's coordinates and is the only source kind that does; a POM built from a file the caller
2802      * pointed at reports none.
2803      */
2804     static boolean isExternalOrigin(ModelBuilderRequest request) {
2805         return request.getRequestType() == ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY
2806                 && request.getSource() != null
2807                 && request.getSource().getModelId() != null;
2808     }
2809 
2810     static boolean usesSystemScope(Dependency dependency) {
2811         return "system".equals(dependency.getScope())
2812                 || (dependency.getSystemPath() != null
2813                         && !dependency.getSystemPath().isEmpty());
2814     }
2815 
2816     private DefaultProfileActivationContext getProfileActivationContext(ModelBuilderRequest request, Model model) {
2817         return new DefaultProfileActivationContext(
2818                 pathTranslator,
2819                 rootLocator,
2820                 interpolator,
2821                 request.getActiveProfileIds(),
2822                 request.getInactiveProfileIds(),
2823                 request.getSystemProperties(),
2824                 request.getUserProperties(),
2825                 model);
2826     }
2827 
2828     private List<Activation> getProfileActivations(Model model) {
2829         return model.getProfiles().stream().map(Profile::getActivation).collect(Collectors.toList());
2830     }
2831 
2832     private Model injectProfileActivations(Model model, List<Activation> activations) {
2833         List<Profile> profiles = new ArrayList<>();
2834         boolean modified = false;
2835         for (int i = 0; i < model.getProfiles().size(); i++) {
2836             Profile profile = model.getProfiles().get(i);
2837             Activation activation = profile.getActivation();
2838             if (activation != null) {
2839                 // restore activation
2840                 profile = profile.withActivation(activations.get(i));
2841                 modified = true;
2842             }
2843             profiles.add(profile);
2844         }
2845         return modified ? model.withProfiles(profiles) : model;
2846     }
2847 
2848     private Model interpolateModel(Model model, ModelBuilderRequest request, ModelProblemCollector problems) {
2849         Model interpolatedModel =
2850                 modelInterpolator.interpolateModel(model, model.getProjectDirectory(), request, problems);
2851         if (interpolatedModel.getParent() != null) {
2852             Map<String, String> map1 = request.getSession().getUserProperties();
2853             Map<String, String> map2 = model.getProperties();
2854             Map<String, String> map3 = request.getSession().getSystemProperties();
2855             UnaryOperator<String> cb = Interpolator.chain(map1::get, map2::get, map3::get);
2856             try {
2857                 String interpolated =
2858                         interpolator.interpolate(interpolatedModel.getParent().getVersion(), cb);
2859                 interpolatedModel = interpolatedModel.withParent(
2860                         interpolatedModel.getParent().withVersion(interpolated));
2861             } catch (Exception e) {
2862                 problems.add(
2863                         Severity.ERROR,
2864                         Version.BASE,
2865                         "Failed to interpolate field: "
2866                                 + interpolatedModel.getParent().getVersion()
2867                                 + " on class: ",
2868                         e);
2869             }
2870         }
2871         interpolatedModel = interpolatedModel.withPomFile(model.getPomFile());
2872         return interpolatedModel;
2873     }
2874 
2875     private boolean rawChildVersionReferencesParent(String rawChildModelVersion) {
2876         return rawChildModelVersion.equals("${pom.version}")
2877                 || rawChildModelVersion.equals("${project.version}")
2878                 || rawChildModelVersion.equals("${pom.parent.version}")
2879                 || rawChildModelVersion.equals("${project.parent.version}");
2880     }
2881 
2882     private Model getSuperModel(String modelVersion) {
2883         return superPomProvider.getSuperPom(modelVersion);
2884     }
2885 
2886     private static org.apache.maven.api.model.Dependency addExclusions(
2887             org.apache.maven.api.model.Dependency candidate, List<Exclusion> exclusions) {
2888         return candidate.withExclusions(Stream.concat(candidate.getExclusions().stream(), exclusions.stream())
2889                 .toList());
2890     }
2891 
2892     private boolean match(Exclusion exclusion, Dependency candidate) {
2893         return match(exclusion.getGroupId(), candidate.getGroupId())
2894                 && match(exclusion.getArtifactId(), candidate.getArtifactId());
2895     }
2896 
2897     private boolean match(String match, String text) {
2898         return match.equals("*") || match.equals(text);
2899     }
2900 
2901     private boolean containsCoordinates(String message, String groupId, String artifactId, String version) {
2902         return message != null
2903                 && (groupId == null || message.contains(groupId))
2904                 && (artifactId == null || message.contains(artifactId))
2905                 && (version == null || message.contains(version));
2906     }
2907 
2908     record GAKey(String groupId, String artifactId) {}
2909 
2910     /**
2911      * Composite key used to deduplicate BOM import conflict warnings within a single top-level build.
2912      * Two warnings are considered duplicates when they share the same message text and originate
2913      * from the same source location (file, model ID, line, and column).
2914      */
2915     private record ImportWarningKey(
2916             String message, String sourceLocation, String sourceModelId, int lineNumber, int columnNumber) {}
2917 
2918     public record RgavCacheKey(
2919             Session session,
2920             RequestTrace trace,
2921             List<RemoteRepository> repositories,
2922             String groupId,
2923             String artifactId,
2924             String version,
2925             String classifier,
2926             String tag)
2927             implements Request<Session> {
2928         @Nonnull
2929         @Override
2930         public Session getSession() {
2931             return session;
2932         }
2933 
2934         @Nullable
2935         @Override
2936         public RequestTrace getTrace() {
2937             return trace;
2938         }
2939 
2940         @Override
2941         public boolean equals(Object o) {
2942             return o instanceof RgavCacheKey that
2943                     && Objects.equals(tag, that.tag)
2944                     && Objects.equals(groupId, that.groupId)
2945                     && Objects.equals(version, that.version)
2946                     && Objects.equals(artifactId, that.artifactId)
2947                     && Objects.equals(classifier, that.classifier)
2948                     && Objects.equals(repositories, that.repositories);
2949         }
2950 
2951         @Override
2952         public int hashCode() {
2953             return Objects.hash(repositories, groupId, artifactId, version, classifier, tag);
2954         }
2955 
2956         @Override
2957         public String toString() {
2958             StringBuilder sb = new StringBuilder();
2959             sb.append(getClass().getSimpleName()).append("[").append("gav='");
2960             if (groupId != null) {
2961                 sb.append(groupId);
2962             }
2963             sb.append(":");
2964             if (artifactId != null) {
2965                 sb.append(artifactId);
2966             }
2967             sb.append(":");
2968             if (version != null) {
2969                 sb.append(version);
2970             }
2971             sb.append(":");
2972             if (classifier != null) {
2973                 sb.append(classifier);
2974             }
2975             sb.append("', tag='");
2976             sb.append(tag);
2977             sb.append("']");
2978             return sb.toString();
2979         }
2980     }
2981 
2982     public record SourceCacheKey(Session session, RequestTrace trace, Source source, String tag)
2983             implements Request<Session>, CacheMetadata {
2984         @Nonnull
2985         @Override
2986         public Session getSession() {
2987             return session;
2988         }
2989 
2990         @Nullable
2991         @Override
2992         public RequestTrace getTrace() {
2993             return trace;
2994         }
2995 
2996         @Override
2997         public CacheRetention getCacheRetention() {
2998             return source instanceof CacheMetadata cacheMetadata ? cacheMetadata.getCacheRetention() : null;
2999         }
3000 
3001         @Override
3002         public boolean equals(Object o) {
3003             return o instanceof SourceCacheKey that
3004                     && Objects.equals(tag, that.tag)
3005                     && Objects.equals(source, that.source);
3006         }
3007 
3008         @Override
3009         public int hashCode() {
3010             return Objects.hash(source, tag);
3011         }
3012 
3013         @Override
3014         public String toString() {
3015             return getClass().getSimpleName() + "[" + "location=" + source.getLocation() + ", tag=" + tag + ", path="
3016                     + source.getPath() + ']';
3017         }
3018     }
3019 
3020     public static class SourceResponse<R extends Request<?>, T> implements Result<R> {
3021         private final R request;
3022         private final T response;
3023 
3024         SourceResponse(R request, T response) {
3025             this.request = request;
3026             this.response = response;
3027         }
3028 
3029         @Nonnull
3030         @Override
3031         public R getRequest() {
3032             return request;
3033         }
3034     }
3035 
3036     static class InterningTransformer implements XmlReaderRequest.Transformer {
3037         static final Set<String> DEFAULT_CONTEXTS = Set.of(
3038                 // Core Maven coordinates
3039                 "groupId",
3040                 "artifactId",
3041                 "version",
3042                 "namespaceUri",
3043                 "packaging",
3044 
3045                 // Dependency-related fields
3046                 "scope",
3047                 "type",
3048                 "classifier",
3049 
3050                 // Build and plugin-related fields
3051                 "phase",
3052                 "goal",
3053                 "execution",
3054 
3055                 // Repository-related fields
3056                 "layout",
3057                 "policy",
3058                 "checksumPolicy",
3059                 "updatePolicy",
3060 
3061                 // Common metadata fields
3062                 "modelVersion",
3063                 "name",
3064                 "url",
3065                 "system",
3066                 "distribution",
3067                 "status",
3068 
3069                 // SCM fields
3070                 "connection",
3071                 "developerConnection",
3072                 "tag",
3073 
3074                 // Common enum-like values that appear frequently
3075                 "id",
3076                 "inherited",
3077                 "optional");
3078 
3079         private final Set<String> contexts;
3080 
3081         /**
3082          * Creates an InterningTransformer with default contexts.
3083          */
3084         InterningTransformer() {
3085             this.contexts = DEFAULT_CONTEXTS;
3086         }
3087 
3088         /**
3089          * Creates an InterningTransformer with contexts from session properties.
3090          *
3091          * @param session the Maven session to read properties from
3092          */
3093         InterningTransformer(Session session) {
3094             this.contexts = parseContextsFromSession(session);
3095         }
3096 
3097         private Set<String> parseContextsFromSession(Session session) {
3098             String contextsProperty = session.getUserProperties().get(Constants.MAVEN_MODEL_BUILDER_INTERNS);
3099             if (contextsProperty == null) {
3100                 contextsProperty = session.getSystemProperties().get(Constants.MAVEN_MODEL_BUILDER_INTERNS);
3101             }
3102 
3103             if (contextsProperty == null || contextsProperty.trim().isEmpty()) {
3104                 return DEFAULT_CONTEXTS;
3105             }
3106 
3107             return Arrays.stream(contextsProperty.split(","))
3108                     .map(String::trim)
3109                     .filter(s -> !s.isEmpty())
3110                     .collect(Collectors.toSet());
3111         }
3112 
3113         @Override
3114         public String transform(String input, String context) {
3115             return input != null && contexts.contains(context) ? input.intern() : input;
3116         }
3117 
3118         /**
3119          * Get the contexts that will be interned by this transformer.
3120          * Used for testing purposes.
3121          */
3122         Set<String> getContexts() {
3123             return contexts;
3124         }
3125     }
3126 
3127     private static <T, A> List<T> map(List<T> resources, BiFunction<T, A, T> mapper, A argument) {
3128         List<T> newResources = null;
3129         if (resources != null) {
3130             for (int i = 0; i < resources.size(); i++) {
3131                 T resource = resources.get(i);
3132                 T newResource = mapper.apply(resource, argument);
3133                 if (newResource != resource) {
3134                     if (newResources == null) {
3135                         newResources = new ArrayList<>(resources);
3136                     }
3137                     newResources.set(i, newResource);
3138                 }
3139             }
3140         }
3141         return newResources;
3142     }
3143 
3144     /**
3145      * Checks if the parent POM path is within the root directory.
3146      * This prevents invalid setups where a parent POM is located above the root directory.
3147      *
3148      * @param parentPath the path to the parent POM
3149      * @param rootDirectory the root directory
3150      * @return true if the parent is within the root directory, false otherwise
3151      */
3152     private static boolean isParentWithinRootDirectory(Path parentPath, Path rootDirectory) {
3153         if (parentPath == null || rootDirectory == null) {
3154             return true; // Allow if either is null (fallback behavior)
3155         }
3156 
3157         try {
3158             Path normalizedParent = parentPath.toAbsolutePath().normalize();
3159             Path normalizedRoot = rootDirectory.toAbsolutePath().normalize();
3160 
3161             // Check if the parent path starts with the root directory path
3162             return normalizedParent.startsWith(normalizedRoot);
3163         } catch (Exception e) {
3164             // If there's any issue with path resolution, allow it (fallback behavior)
3165             return true;
3166         }
3167     }
3168 }