Skip to content

[MNG-8650] mvnval, a tool to validate POMs without building them - #13276

Merged
gnodet merged 1 commit into
apache:masterfrom
ikxeno:MNG-8650-pom-validator
Oct 13, 2026
Merged

gnodet merged 1 commit into
apache:masterfrom
ikxeno:MNG-8650-pom-validator

Conversation

@ikxeno

@ikxeno ikxeno commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #10442

This was gnodet's own request in MNG-8650, March 2025, and it moved to the 4.1.0
milestone rather than getting dropped:

I think we should provide a simple command line that can be used to validate a
POM and report warnings and errors in a simple way. We could then ask Sonatype
to make sure that POMs uploaded to Maven Central do not contain any error and
raise the warnings back to maintainers.

My own reason sits downstream of that. I maintain Java packaging for ALT Linux,
where builds run offline and our Maven and Gradle plugins read the POMs we ship.
A POM that parses but isn't valid breaks them during a rebuild, nowhere near the
actual mistake.

$ mvnval pom.xml
pom.xml:
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique:
        junit:junit:jar -> version 4.13.2 vs 4.12 @ line 12, column 5

Takes any number of POMs, defaults to ./pom.xml, writes text or --format json.
Exit 0 when nothing was reported, 1 when anything was rejected, 2 on bad usage,
3 on Ctrl+C, 4 when only warnings were. Reachable as mvnval, as mvn --val,
and inside mvnsh.

Two modes, and one contains the other

--mode raw reads the file and raw models. It reaches no repository, so it works
offline and on a POM whose parent is not published yet, which is the Central case:
a POM turning up there is on its own. What it cannot see is anything inheritance
introduces, such as a dependency whose version lives in the parent's
dependencyManagement.

--mode effective is the default. It runs the raw pass and then builds the
effective model, so parents and imported boms are resolved and the checks needing
them run too. It keeps the raw pass because the effective build reports nothing
about the reactor around a POM: on its own it passes a project whose declared
subproject is not on disk, which mvn refuses to read.

The default reaches the network and caches what it fetches, like any Maven
command. --local-repository aims that somewhere else, --temp-local-repository
at a directory made for the run and deleted when it ends, and maven.repo.local
works as it does elsewhere. -o, -s, -ps and -is are refused outside raw
mode rather than ignored: resolution runs on a session built from the default
settings files and cannot be redirected, and a gate that passed -o and got a
network call would be worse off than one told no.

Why not mvn -f pom.xml validate

Because that needs a project you can build, and it stops at the first thing it
cannot resolve. This reads POMs and reports on all of them, one exit code for the
batch, and --mode raw needs no repository at all.

Why a new API method

buildRawModel(request) already exists and is not enough: it returns the Model
and drops the problem collector, so warnings never reach the caller. build()
keeps the problems but throws as soon as validation reports an error, so a POM
with one error and four warnings tells you about the error only.

Named validate rather than buildRaw so the name says what the caller gets and
not how far the pipeline runs. default, not abstract, so anything implementing
ModelBuilderSession keeps compiling untouched. The interface promises only what
every implementation must keep; how far this one runs is documented on the
override.

Decisions worth arguing about

A session per POM, not one for the run. I wrote the shared session first, as
asked. It makes the verdict depend on argument order: derived sessions share
mappedSources, so a groupId:artifactId registered while reading an earlier POM
answers a later POM's parent lookup. Two files given one way came back clean and
the other way came back with an error about the wrong parent. Sharing bought no
reading either, since every pass walks the reactor from the root again.

The repositories come from the settings, derived here. ApiRunner.createSession
asks its injector for an unqualified Session, and InjectorImpl registers a
qualified @Provides under the unqualified key as well, so a provider belonging to
another tool can answer and bring its own hardcoded repositories. Deriving the list
gives the same answer whichever session came back, and keeps the repositories an
operator declared. Worth an issue of its own; I did not want to fix the injector
from here.

The reactor is mapped before the POM is read. A 4.1.0 subproject may leave out
its parent version, and it is taken from the parent's file model. Without the walk
a perfectly valid subproject fails with 'parent.version' is missing.

A reactor module that fails to load is logged, not reported. loadFilePom
reports that failure against the caller's result, so before this change
mvnval a/pom.xml said a/pom.xml was broken when the culprit was b/pom.xml.
The flag is scoped to validate; build() is untouched and still fails on a
broken module, because a build that silently skipped one would be worse.

Warnings exit 4. Codes 0 to 3 mean the same thing across the Maven 4 tools,
and 3 is already CANCELED in mvnenc and mvnup. A gate has to tell "this POM
has warnings" from "mvnval broke" and from "somebody hit Ctrl+C", so warnings got
the next free code.

One problem reported twice is collapsed in the tool. The parent version check
sits in both validateFileModel and validateRawModel, so the model builder hands
the same finding over twice. I collapsed it in Report rather than touching the
validator, since changing that changes mvn.

JSON assembled by hand. No JSON library is on the CLI classpath and I would
rather not put one there for one output format. Non-ASCII is escaped as \uXXXX
because the writer's charset is the console's, which on Windows is routinely not
UTF-8, and a path can carry an unpaired surrogate that no charset encodes.
--format json also quietens the log, since the document and the log share
standard output and a CI runner in debug mode was enough to stop the output being
JSON.

No container is stood up. LookupInvoker only ever builds a ProtoSession
and ModelBuilderRequest needs a full Session, so the session is built in
createSession, with the transports resolution needs, as mvnup does. Nothing
beside the POM can make this process load code: .mvn/extensions.xml,
maven.ext.class.path and .mvn/settings.xml next to the file are not read.
.mvn/jvm.config still reaches the launcher, as it does for every Maven tool.

THREAT_MODEL.md gets a row. It reads operator POMs and emits their content
into a machine-readable document, and in the default mode it fetches from URLs the
POM itself chose. The row says that rather than claiming a containment that does
not hold.

Checked

mvn verify on maven-api-cli, maven-api-core, maven-impl and maven-cli.
Checkstyle clean, javadoc clean under doclint. Distribution built and driven from
the unpacked archive.

Over the 40 POMs this repository builds from, both modes are clean. Over all 94
including test projects, six are flagged, and all six are fixtures that are broken
on purpose. Against five published POMs pulled from Central, both modes agree:
io.netty:netty-all:4.1.115.Final has ten duplicate dependency declarations, and
guava, spring-core, commons-lang3 and jackson-databind are clean. Aimed at an
empty local repository the default mode fetched nine parent and bom POMs and
reached the same verdict, so resolution is exercised end to end.

Order independence is asserted in a test: two roots sharing groupId:artifactId,
validated in both orders, same problems. --temp-local-repository is deleted on
every exit and on a signal, checked by killing the process at eight points through
a run. --format json parses as one document, including under RUNNER_DEBUG=1.
The shell command was driven through a pseudo terminal.

Two ITs fail on my machine for reasons this branch does not touch, and I have not
checked them against master: MavenITmng4428FollowHttpRedirectTest.testitHttpsToHttps,
which is HTTPS transport, and MavenITmng7045DropUselessAndOutdatedCdiApiTest, where
Groovy 4.0.28 dies with "BUG! exception in phase 'semantic analysis'" on JDK 25 after
the model has already built.

License

@elharo elharo changed the title Fix #10442: mvnval, a tool to validate POMs without building them mvnval, a tool to validate POMs without building them Sep 27, 2026
@elharo
elharo requested a lite review from Copilot September 27, 2026 11:36
@elharo elharo changed the title mvnval, a tool to validate POMs without building them [MNG-8650] mvnval, a tool to validate POMs without building them Sep 27, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Core-extension loading and incorrect invalid-format exit handling leave documented behavior and safety requirements unresolved.

Review effort: Lite
Findings: 1 High severity · 2 Medium severity

Open (3)
What changed in this PR

Adds mvnval, a raw POM validation CLI with text/JSON reporting, API support, launchers, documentation, and tests.

Changes:

  • Adds raw model building and validation problem collection.
  • Adds CLI parsing, reporting, exit codes, and distribution integration.
  • Adds unit/integration tests and threat-model documentation.

Review notes: core extensions may still load during bootstrap, invalid --format returns exit code 1 instead of 2, and the public path API documentation does not match returned values.

File Reviewed changes
THREAT_MODEL.md Documents mvnval input handling.
its/​core-it-suite/​src/​test/​resources/​mvnval-validate-pom/​duplicate-dependency/​pom.xml Invalid duplicate-dependency fixture.
its/​core-it-suite/​src/​test/​resources/​mvnval-validate-pom/​clean/​pom.xml Clean validation fixture.
its/​core-it-suite/​src/​test/​java/​org/​apache/​maven/​it/​MavenITgh10442MvnvalValidatePomTest.java Adds CLI integration tests.
its/​core-it-suite/​pom.xml Enables executable permissions for tests.
impl/​maven-impl/​src/​test/​java/​org/​apache/​maven/​impl/​model/​RawModelReadingTest.java Tests raw model behavior.
impl/​maven-impl/​src/​main/​java/​org/​apache/​maven/​impl/​model/​DefaultModelBuilder.java Implements raw model building.
impl/​maven-cli/​src/​test/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​ValidateInvokerTest.java Tests validation invocation.
impl/​maven-cli/​src/​test/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​TestUtils.java Provides CLI test utilities.
impl/​maven-cli/​src/​test/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​ReportTest.java Tests report behavior.
impl/​maven-cli/​src/​test/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​ReporterTest.java Tests report rendering.
impl/​maven-cli/​src/​test/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​OutputFormatTest.java Tests output format selection.
impl/​maven-cli/​src/​test/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​CommonsCliValidateOptionsTest.java Tests option parsing.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​MavenValCling.java Adds the CLI entry point.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​ValidateParser.java Parses validation arguments.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​ValidateInvoker.java Executes validation and determines exit codes.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​ValidateContext.java Provides validation context.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​TextReporter.java Implements text reporting.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​Reporter.java Defines reporting abstraction.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​Report.java Models validation results.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​package-info.java Documents the implementation package.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​OutputFormat.java Defines output formats.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​JsonReporter.java Implements JSON reporting.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​mvnval/​CommonsCliValidateOptions.java Defines validation options.
impl/​maven-cli/​src/​main/​java/​org/​apache/​maven/​cling/​invoker/​CommonsCliOptions.java Registers --val.
api/​maven-api-core/​src/​main/​java/​org/​apache/​maven/​api/​services/​ModelBuilder.java Adds the raw-build API.
api/​maven-api-cli/​src/​site/​markdown/​index.md Documents the new tool.
api/​maven-api-cli/​src/​main/​java/​org/​apache/​maven/​api/​cli/​Tools.java Registers tool metadata.
api/​maven-api-cli/​src/​main/​java/​org/​apache/​maven/​api/​cli/​ParserRequest.java Adds parser requests.
api/​maven-api-cli/​src/​main/​java/​org/​apache/​maven/​api/​cli/​mvnval/​ValidateOptions.java Defines public validation options.
api/​maven-api-cli/​src/​main/​java/​org/​apache/​maven/​api/​cli/​mvnval/​package-info.java Documents the validation API package.
apache-maven/​src/​assembly/​maven/​bin/​mvnval.cmd Adds the Windows mvnval launcher.
apache-maven/​src/​assembly/​maven/​bin/​mvnval Adds the Unix mvnval launcher.
apache-maven/​src/​assembly/​maven/​bin/​mvn.cmd Adds Windows dispatch support.
apache-maven/​src/​assembly/​maven/​bin/​mvn Adds Unix dispatch support.
apache-maven/​src/​assembly/​component.xml Includes the new scripts in distributions.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

elharo
elharo previously requested changes Sep 27, 2026

@elharo elharo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where will this be documented? In which files/URLs specifically? If they're in this repo, they must be part of this PR. If they're in maven-site there should be a concurrent PR with those changes too.

Comment thread THREAT_MODEL.md Resolved

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New feature — mvnval POM validation tool

Well-structured addition. The core extension isolation, exit code contract, and reactor-aware validation are all carefully designed and well-tested. A few observations:

Regarding existing reviews:

  • Copilot's core extension concern — already addressed: ValidateInvoker.createCoreExtensionSelector() returns an empty list, the THREAT_MODEL entry documents this, and ExtensionTests.shouldLoadNoCoreExtension tests it.
  • Copilot's exit code 2 concern — already addressed: CommonsCliValidateOptions.parse() deliberately does not check --format (see its Javadoc), and ValidateInvoker.execute() catches IllegalArgumentException from OutputFormat.parse() and returns BAD_OPERATION (exit 2). ValidateInvokerTest.shouldRejectUnknownFormatWithBadOperation() confirms this.
  • elharo's http vs https license URLs — all license headers in the project use http://www.apache.org/licenses/LICENSE-2.0. This is a project-wide convention, not a PR issue.
  • elharo's mvnval.cmd line 24 comment — MAVEN_BATCH_ECHO accepting 'on' matches mvnenc.cmd, mvnup.cmd, and the main mvn.cmd. Not a regression.

Refactoring quality: The loadReactor extraction from buildBuildPom is clean — buildBuildPom() now calls loadReactor(true, true) preserving original behavior, while buildRaw() calls loadReactor(false, false) for the relaxed validation context. The reportReactorLoadFailures flag correctly scopes error suppression to reactor scanning only; the actual POM validation path remains unaffected.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@ikxeno

ikxeno commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

Where will this be documented? In which files/URLs specifically? If they're in this repo, they must be part of this PR. If they're in maven-site there should be a concurrent PR with those changes too.

In this repo the only file documenting the tool set is api/maven-api-cli/src/site/markdown/index.md, which this PR updates with an mvnval entry next to mvnup. --help carries the usage, the exit codes and what the check can't see.

Past that I couldn't find a page for mvnup or mvnenc on maven.apache.org, so I don't have a sibling to copy. If it belongs in maven-site, say where and I'll open a PR there alongside this one. If you'd rather it lived here, point me at the file.

@ikxeno
ikxeno requested a review from gnodet-bot September 27, 2026 18:23
@ikxeno
ikxeno marked this pull request as ready for review September 27, 2026 21:03
@ikxeno
ikxeno requested a review from elharo September 27, 2026 21:04

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits 9ba8305..6781eef — all previous findings addressed

Previous findings status:

  1. ✅ reportReactorLoadFailures propagation (gnodet-bot) — Addressed. derive() now copies the flag to child sessions. Correct fix.

  2. ✅ determineWriter comment (gnodet-bot) — Addressed. Comment reworded to accurately describe why determineWriter is used instead of context.writer.

  3. ✅ Core extension loading (Copilot, gnodet-bot) — Addressed and improved. The previous approach (override createCoreExtensionSelector() to return empty list) only blocked extensions. The new approach (no-op overrides of container(), postContainer(), lookup(), init(), settings()) is strictly more thorough — it prevents the entire DI container from bootstrapping, which also blocks .mvn/extensions.xml, maven.ext.class.path, and .mvn/settings.xml. The THREAT_MODEL entry was updated accordingly.

  4. ✅ Exit code 2 for invalid format (Copilot) — Addressed. The validate() override now remaps the base class's exit code 1 (parse failure) to BAD_OPERATION (2), so a bad --format value or any other parse error exits 2 instead of colliding with the "POM rejected" exit code.

  5. ✅ Exit code contract — Now clean: 0=OK, 1=ERROR, 2=BAD_OPERATION, 3=CANCELED, 4=WARNINGS. The WARNINGS shift from 3→4 to accommodate CANCELED is correct and consistent with mvnenc/mvnup.

New changes assessment:

  • The Ctrl+C handling (Terminal.Signal.INT → thread interrupt → check between POMs → CANCELED exit) is correct. Thread.interrupted() clears the flag where it's acted on.
  • The broad catch (Exception e) in execute() prevents unexpected failures from becoming exit code 2 (which the handleException base would produce). Both mvnenc and mvnup do the same.
  • The UserInterruptException catch handles JLine-level interrupts separately from signal-level ones. Correct.
  • Test coverage for the new behavior is adequate: shouldStandUpNoContainer, shouldTurnParseFailureIntoBadOperation, mock terminal setup in TestUtils.

Solid follow-up commits. No new issues.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet gnodet left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this — the use case is clearly stated and the implementation is clean. I have a few concerns about the API addition before this goes in.

buildRaw encodes a limitation that belongs to the caller, not the API

The new ModelBuilderSession.buildRaw() is essentially "run the model builder pipeline but collect problems instead of throwing on the first validation error". That's a useful and legitimate contract. But the name encodes how far the pipeline runs (raw = file + raw model phase only) as if that were fixed by the method, when it's already controlled by RequestType on the ModelBuilderRequest.

I'd suggest renaming it to validate:

/**
 * Validates the model described by the request, collecting all problems
 * without throwing on validation errors. The request's {@link ModelBuilderRequest.RequestType}
 * controls how far the pipeline runs. Only throws when the model cannot be read at all.
 *
 * @since 4.1.0
 */
default ModelBuilderResult validate(ModelBuilderRequest request) throws ModelBuilderException {
    ...
}

Same implementation for now — the raw case stays as-is. But the name doesn't bake in the limitation, and we don't need a second API addition later when someone wants effective-model validation.

Effective-model validation is already achievable — without any new API

The PR description notes that validation stops at the raw model, and that a dependency whose version comes from the parent's dependencyManagement is only caught in validateEffectiveModel. That's true today, but it doesn't require any new API to fix. ApiRunner.createSession(injectorConsumer, localRepo) already accepts a local repository path, so mvnval could expose:

  • --depth raw|effective (defaulting to effective) to control how far the pipeline runs
  • -Dmaven.repo.local / --local-repository <path> for an explicit local repository (defaulting to ~/.m2/repository as usual)
  • --temp-local-repository to use a throwaway directory deleted on exit — useful for CI gates that want full isolation

With --depth effective, the full validateEffectiveModel runs — catching things like missing dependency versions inherited from a parent's dependencyManagement. No custom ModelResolver needed, no new API, just wiring what's already there.

The clearRequestScopedCache in buildRaw is a code smell

The finally block in buildRaw explicitly clears the request-scoped cache because the method knows it shouldn't share session state with a concurrent build() call on the same ModelBuilderSession. But the right answer isn't special-casing the cleanup: it's using a fresh ModelBuilderSession per validation job, which is what createSession() is for. A validate() method that documents "use a dedicated session" doesn't need this workaround — the cache lifecycle is just the session lifetime.

Reuse a single ModelBuilderSession across all validated POMs

The current implementation creates a fresh session per POM (modelBuilder.newSession() inside the loop). A shared parent is therefore re-resolved once per child — for a multi-module project with mvnval **/*.pom, that's N resolutions of the same parent. With a single ModelBuilderSession for the whole batch (the reactor pattern), parent POMs are resolved once and cached. The shell handles glob expansion; the tool already accepts multiple path arguments; sharing the session is the only missing piece for efficient multi-POM validation.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits 6781eef..addbec6 — all maintainer feedback addressed

Previous findings status:

  1. ✅ Rename buildRaw → validate (gnodet) — Addressed in adf8539. The API method now names the contract, not the pipeline stage. Javadoc rewritten accordingly, adding session isolation guidance ("give a validation run a session of its own").

  2. ✅ clearRequestScopedCache code smell (gnodet) — Addressed in 6f09770. The workaround is gone — validate() now uses sessionFor() (the same factory build() uses), so session lifetime governs the cache. No special cleanup needed.

  3. ✅ Reuse single ModelBuilderSession across all validated POMs (gnodet) — Addressed in 6f09770. ValidateInvoker.validateAll() creates one ModelBuilderSession via builder.newSession() and passes it to every validateOne() call. New test shouldValidateSeveralProjectsOnOneSession exercises two independent reactors on the same session.

  4. ✅ Lazy StringBuilder in quote() (rmannibucau) — Addressed in addbec6. The escaped(char) method is extracted, and quote() now returns '"' + value + '"' without allocating a StringBuilder when nothing needs escaping.

Solid follow-up. No new issues.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@elharo elharo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see https://www.apache.org/foundation/license-faq#httpsVhttp

Is it OK to use https instead of http in LICENSE and source headers?

Yes. When the LICENSE text was last updated in 2004, https did not have the widespread adoption it does now. It is acceptable, in fact encouraged, to use https wherever http is currently used in LICENSE files as well as in individual source headers.

@ikxeno

ikxeno commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

@elharo

I agree https would be better, and I can't use it here. Spotless checks every Java
file against config/maven-header-plain.txt from maven-shared-resources,
and line 10 of it is http. maven-parent:50 hands that artifact to spotless
as a plugin dependency.

Under CI that's spotless:check and an https header fails the build; locally the
same config runs spotless:apply and rewrites it back to http before you notice.
Either way it takes a change to maven-shared-resources first, then one sweep over
all 3237 files. Glad to do both, just not inside this PR.

@ikxeno

ikxeno commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

@gnodet

Two things I'd like you to decide.

Should validate() read RequestType? BUILD_PROJECT raw as now,
BUILD_EFFECTIVE running validateEffectiveModel and collecting the problems
rather than throwing. Then --depth is just the request, and there is never a
second method. I didn't do it on my own because nothing in the enum means "stop at
the raw model" today, and both branches of build() run to the end.

And can --depth default to raw? With effective as the default the offline
cases die: no repository, and no settings.xml either, so no mirrors or proxies.
There is also this. Once anything resolves, the <repositories> of the POM being
validated are part of where it resolves from, DefaultModelBuilder near 699 and
731. A gate in front of Central would be letting untrusted input pick the URLs it
fetches. As an opt-in flag I'll add it today.

The rest is in, adf8539 and 6f09770. Renamed, cache clear gone, one session for
the run.

Two things I got wrong. Sharing a session doesn't trip No unique Source when two
roots share coordinates; I claimed it did in the description, and there is a test
now. And the parent still isn't read once:

$ mvnval -X a/pom.xml b/pom.xml c/pom.xml | grep 'Reading file model' | sort | uniq -c
   3 a/pom.xml   3 b/pom.xml   3 c/pom.xml   3 pom.xml

Same numbers with a session per POM, because every validate() walks the reactor
from the root again. If you want the batch case cheaper, that's the walk, not the
session.

@ikxeno
ikxeno requested review from elharo and gnodet September 28, 2026 12:25
@gnodet

gnodet commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Thanks for addressing the rename, the cache cleanup, and the shared session — those are all improvements.

On the network question: I think the default should be --mode effective (full effective model validation, downloading parents into the local repository as needed), with --mode raw as an explicit opt-out for the offline / pre-commit case. The raw mode is useful, but it's the more limited option — defaulting to it means users get incomplete validation silently.

For the local repository, the default should be ~/.m2/repository as usual, with two options:

  • --local-repository <path> / -Dmaven.repo.local for an explicit path
  • --temp-local-repository for a throwaway directory deleted on exit (the CI isolation case)

ApiRunner.createSession(injectorConsumer, localRepo) already accepts the path — this is purely wiring on the mvnval side, no new API needed.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits addbec6..5b080ab — substantial new functionality, all previous findings addressed, solid implementation

Previous findings status:

  1. ✅ buildRaw → validate (gnodet) — Addressed in earlier commits. The API method is named for its contract.
  2. ✅ clearRequestScopedCache code smell (gnodet) — Gone.
  3. ✅ Reuse single ModelBuilderSession (gnodet) — Addressed in 6f09770, then intentionally reverted to a session per POM in the new commits. The revert is justified: derived sessions share mappedSources, so when two POMs from different reactors declare the same groupId:artifactId (e.g. as a parent), the first POM's mapping answers the second POM's parent lookup, making the verdict depend on argument order. Test shouldNotDependOnArgumentOrder exercises this regression. Creating a fresh session per POM costs nothing — each pass walks the reactor from the root anyway.
  4. ✅ Effective model validation (gnodet) — Addressed in f75cdab. Default is --mode effective, with --mode raw as opt-out. The naming differs from gnodet's original suggestion (--depth raw|effective) but the semantics match exactly.
  5. ✅ Lazy StringBuilder in quote() (rmannibucau) — Addressed in earlier commit.
  6. ✅ elharo's documentation question — Answered in PR comments.

New changes assessment (addbec6..5b080ab):

  • ValidationMode two-pass design is correct. EFFECTIVE runs validate() (raw) first, then build(BUILD_EFFECTIVE) on the same ModelBuilderSession. This works because sessionFor() derives a new ModelBuilderSessionState for the second request, and the builder caches file/raw models per source — so raw-phase problems aren't duplicated. The early-exit on raw errors avoids pointless network access.

  • validate() API contract relaxation is intentional and well-designed. The interface now says "must not resolve from a remote repository" while the implementation Javadoc (on DefaultModelBuilder) documents the specific guarantee: "stops after the raw model". This leaves room for future implementations to run further without violating the interface contract, while callers rely on the problems, not on model accessors whose @Nonnull contracts don't hold here.

  • Refused options (-o, -s, -ps, -is) in effective mode are correct. Resolution runs on the session ApiRunner builds, which reads the user's settings.xml and cannot be redirected. Silently ignoring --offline while going to the network would be a trap. Raw mode accepts them all since it resolves nothing.

  • --temp-local-repository cleanup is race-safe: deleteRecursively uses Files.deleteIfExists (idempotent), and the shutdown hook + finally block can overlap harmlessly. The "delete first, deregister second" ordering is correct — the alternative window where a signal arrives after the hook is removed but before deletion runs would leak the directory.

  • System.setProperty(MAVEN_LOGGER_DEFAULT_LOG_LEVEL, "error") in configureLogging is a JVM-global side effect that leaks after mvnval --format json in mvnsh. The next command's configureLogging overwrites it, so it's cosmetic noise (an INFO log line from MavenSimpleConfiguration noting the override), not a correctness bug.

  • Shell integration (BuiltinShellCommandRegistryFactory adding mvnval) follows the same pattern as mvnenc and mvnup.

  • Reporter interface dropped in favour of static methods on TextReporter/JsonReporter delegated through OutputFormat enum abstract method — simpler, no indirection for a two-element hierarchy.

  • resolvePoms normalises paths before distinct() — fixes "pom.xml" "./pom.xml" being treated as two files. Test shouldReadAPomNamedTwiceOnce covers it.

  • Test coverage is thorough: WiringTests.shouldRegisterTransports exercises the real ValidateInvoker (not the test seam) over file:// transport; EffectiveTests covers inherited problems, parent resolution, refused options, aimed/temp repositories, and argument-order independence.

Solid follow-up. No issues found.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@ikxeno

ikxeno commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@gnodet

Default is --mode effective now, --mode raw the opt-out.

Effective runs the raw pass first. build() with BUILD_EFFECTIVE says nothing about the reactor, so on its own it passed a project whose <modules> points at a directory that isn't there. No second read, the file and raw models are cached per source (DefaultModelBuilder:1812, :2168).

--local-repository, --temp-local-repository and maven.repo.local all work. I set the path with Session.withLocalRepository on the session that comes back rather than passing it to ApiRunner.createSession, because two things can drop that argument: settings.getLocalRepository() wins over it at ApiRunner:594, and the injector can hand back another tool's session, since InjectorImpl:333 binds a qualified @Provides under the unqualified key as well, so mvnup's can answer getInstance(Session.class). Neither fires on every setup, which is what made it worth pinning. Same reason I re-derive the remote repositories from the settings. File that injector one separately?

The shared session I undid. It makes the verdict depend on argument order: derived sessions share mappedSources, so a GA read from an earlier POM answers a later one's parent lookup. Same two files, one order clean, the other an error about the wrong parent. There's a test now. Every pass walks the reactor from the root again, so sharing saved no reading either.

Your javadoc sketch has RequestType controlling depth, and validate never reads it. I wrote what's true instead. Want it to actually dispatch?

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit 5b080ab..9c07cfd — clean fix, no issues

New commit assessment (9c07cfd): resolvePoms path deduplication fix.

Path::normalize only collapsed ./pom.xml vs pom.xml. The new sameFileSamePath uses toRealPath() which also resolves symlinks and case-insensitive filesystem equivalence (Windows/macOS: pom.xml vs POM.XML). Fallback to normalize() on IOException is correct — non-existent files reach unusable() downstream.

Test correctly handles platforms without symlink support (Windows without developer mode).

All previous findings remain addressed. No new issues.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@ikxeno

ikxeno commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

@gnodet, the CLI is ready for review. Here is the output from the unpacked distribution at eaabc887b0.

I ran all nine fixture files in both modes, then checked batch output, JSON, invalid arguments, the mvn --val entry point and the repository options. The repository probe has org.apache:apache:35 as a parent and an empty <relativePath/>, so effective mode has to resolve that parent. Each block includes the process exit code. Commands run from the sandbox unless a different directory is shown.

Machine-specific paths are shown as <sandbox>.

mvnval ok/pom.xml (exit 0)
$ mvnval ok/pom.xml
ok/pom.xml: no problems
exit 0
mvnval --mode raw ok/pom.xml (exit 0)
$ mvnval --mode raw ok/pom.xml
ok/pom.xml: no problems
exit 0
mvnval dup/pom.xml (exit 1)
$ mvnval dup/pom.xml
dup/pom.xml:
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version 4.13.2 vs 4.12 @ line 5, column 1
exit 1
mvnval --mode raw dup/pom.xml (exit 1)
$ mvnval --mode raw dup/pom.xml
dup/pom.xml:
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version 4.13.2 vs 4.12 @ line 5, column 1
exit 1
mvnval ghost/pom.xml (exit 1)
$ mvnval ghost/pom.xml
ghost/pom.xml:
  ERROR Child subproject no-such-dir of <sandbox>/ghost does not exist
exit 1
mvnval --mode raw ghost/pom.xml (exit 1)
$ mvnval --mode raw ghost/pom.xml
ghost/pom.xml:
  ERROR Child subproject no-such-dir of <sandbox>/ghost does not exist
exit 1
mvnval ghost/mod/pom.xml (exit 0)
$ mvnval ghost/mod/pom.xml
ghost/mod/pom.xml: no problems
exit 0
mvnval --mode raw ghost/mod/pom.xml (exit 0)
$ mvnval --mode raw ghost/mod/pom.xml
ghost/mod/pom.xml: no problems
exit 0
mvnval broken.xml (exit 1)
$ mvnval broken.xml
broken.xml:
  FATAL Non-parseable POM <sandbox>/broken.xml: Unable to read model: Unexpected character 'n' (code 110) in prolog; expected '<'
     at [row,col {unknown-source}]: [1,1]
exit 1
mvnval --mode raw broken.xml (exit 1)
$ mvnval --mode raw broken.xml
broken.xml:
  FATAL Non-parseable POM <sandbox>/broken.xml: Unable to read model: Unexpected character 'n' (code 110) in prolog; expected '<'
     at [row,col {unknown-source}]: [1,1]
exit 1
mvnval inherit/pom.xml (exit 0)
$ mvnval inherit/pom.xml
inherit/pom.xml: no problems
exit 0
mvnval --mode raw inherit/pom.xml (exit 0)
$ mvnval --mode raw inherit/pom.xml
inherit/pom.xml: no problems
exit 0
mvnval inherit/child/pom.xml (exit 1)
$ mvnval inherit/child/pom.xml
inherit/child/pom.xml:
  ERROR 'dependencies.dependency.version' for groupId='org.x', artifactId='unmanaged', type='jar' is missing. @ line 4, column 15
exit 1
mvnval --mode raw inherit/child/pom.xml (exit 0)
$ mvnval --mode raw inherit/child/pom.xml
inherit/child/pom.xml: no problems
exit 0
mvnval warn/pom.xml (exit 4)
$ mvnval warn/pom.xml
warn/pom.xml:
  WARNING 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-clean-plugin  is missing. @ line 3, column 17
exit 4
mvnval --mode raw warn/pom.xml (exit 0)
$ mvnval --mode raw warn/pom.xml
warn/pom.xml: no problems
exit 0
mvnval netty-all-4.1.115.Final.pom (exit 1)
$ mvnval netty-all-4.1.115.Final.pom
netty-all-4.1.115.Final.pom:
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1060, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1067, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-riscv64 -> duplicate declaration of version 4.1.115.Final @ line 1074, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-kqueue:jar:osx-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1081, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-kqueue:jar:osx-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1088, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-resolver-dns-native-macos:jar:osx-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1095, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-resolver-dns-native-macos:jar:osx-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1102, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1109, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1116, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-riscv64 -> duplicate declaration of version 4.1.115.Final @ line 1123, column 5
exit 1
mvnval --mode raw netty-all-4.1.115.Final.pom (exit 1)
$ mvnval --mode raw netty-all-4.1.115.Final.pom
netty-all-4.1.115.Final.pom:
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1060, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1067, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-riscv64 -> duplicate declaration of version 4.1.115.Final @ line 1074, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-kqueue:jar:osx-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1081, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-kqueue:jar:osx-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1088, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-resolver-dns-native-macos:jar:osx-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1095, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-resolver-dns-native-macos:jar:osx-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1102, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-x86_64 -> duplicate declaration of version 4.1.115.Final @ line 1109, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-aarch_64 -> duplicate declaration of version 4.1.115.Final @ line 1116, column 5
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: io.netty:netty-transport-native-epoll:jar:linux-riscv64 -> duplicate declaration of version 4.1.115.Final @ line 1123, column 5
exit 1
mvnval ok/pom.xml dup/pom.xml ghost/pom.xml warn/pom.xml (exit 1)
$ mvnval ok/pom.xml dup/pom.xml ghost/pom.xml warn/pom.xml
ok/pom.xml: no problems
dup/pom.xml:
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version 4.13.2 vs 4.12 @ line 5, column 1
ghost/pom.xml:
  ERROR Child subproject no-such-dir of <sandbox>/ghost does not exist
warn/pom.xml:
  WARNING 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-clean-plugin  is missing. @ line 3, column 17
exit 1
mvnval --mode raw --format json dup/pom.xml (exit 1)
$ mvnval --mode raw --format json dup/pom.xml
[{"pom":"<sandbox>/dup/pom.xml","problems":[{"severity":"ERROR","message":"'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version 4.13.2 vs 4.12","line":5,"column":1}]}]
exit 1
RUNNER_DEBUG=1 mvnval --mode raw --format json dup/pom.xml (exit 1)
$ RUNNER_DEBUG=1 mvnval --mode raw --format json dup/pom.xml
[{"pom":"<sandbox>/dup/pom.xml","problems":[{"severity":"ERROR","message":"'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version 4.13.2 vs 4.12","line":5,"column":1}]}]
exit 1
mvnval -o inherit/child/pom.xml (exit 2)
$ mvnval -o inherit/child/pom.xml
[ERROR] --offline (-o) needs --mode raw, which reaches no repository.
exit 2
mvnval --mode raw -o inherit/child/pom.xml (exit 0)
$ mvnval --mode raw -o inherit/child/pom.xml
inherit/child/pom.xml: no problems
exit 0
mvnval --mode bogus ok/pom.xml (exit 2)
$ mvnval --mode bogus ok/pom.xml
[ERROR] Unknown mode 'bogus', expected one of: raw, effective
exit 2
mvnval --format yaml ok/pom.xml (exit 2)
$ mvnval --format yaml ok/pom.xml
[ERROR] Unknown format 'yaml', expected one of: text, json
exit 2
mvnval missing-pom.xml (exit 1)
$ mvnval missing-pom.xml
missing-pom.xml: does not exist
exit 1
mvnval ok (exit 1)
$ mvnval ok
ok: is a directory, not a POM file
exit 1
cd ok && mvnval (exit 0)
$ cd ok && mvnval
pom.xml: no problems
exit 0
mvnval ok/pom.xml ./ok/pom.xml (exit 0)
$ mvnval ok/pom.xml ./ok/pom.xml
ok/pom.xml: no problems
exit 0
mvnval --mode raw --temp-local-repository ok/pom.xml (exit 0)
$ mvnval --mode raw --temp-local-repository ok/pom.xml
ok/pom.xml: no problems
exit 0
mvn --val --mode raw dup/pom.xml (exit 1)
$ mvn --val --mode raw dup/pom.xml
dup/pom.xml:
  ERROR 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> version 4.13.2 vs 4.12 @ line 5, column 1
exit 1

Repository options: the three explicit-path runs each fetched org/apache/apache/35/apache-35.pom into the requested directory. For each temporary run, I observed one mvnval-repo-* directory while the process was running and none after it exited.

mvnval --local-repository repo-probe/cli-repo repo-probe/pom.xml (exit 0)
$ mvnval --local-repository repo-probe/cli-repo repo-probe/pom.xml
[INFO] Loaded 23932 auto-discovered prefixes for remote repository central (prefixes-central.txt)
repo-probe/pom.xml: no problems
exit 0

Checked: the parent POM was present in the requested repository.

mvnval -Dmaven.repo.local=repo-probe/property-repo repo-probe/pom.xml (exit 0)
$ mvnval -Dmaven.repo.local=repo-probe/property-repo repo-probe/pom.xml
[INFO] Loaded 23932 auto-discovered prefixes for remote repository central (prefixes-central.txt)
repo-probe/pom.xml: no problems
exit 0

Checked: the parent POM was present in the requested repository.

mvnval -Dmaven.repo.local=repo-probe/unused-property-repo --local-repository repo-probe/priority-repo repo-probe/pom.xml (exit 0)
$ mvnval -Dmaven.repo.local=repo-probe/unused-property-repo --local-repository repo-probe/priority-repo repo-probe/pom.xml
[INFO] Loaded 23932 auto-discovered prefixes for remote repository central (prefixes-central.txt)
repo-probe/pom.xml: no problems
exit 0

Checked: the parent POM was present in the requested repository.

Checked: the unused repository path was not created.

mvnval --temp-local-repository repo-probe/pom.xml (exit 0)
$ mvnval --temp-local-repository repo-probe/pom.xml
[INFO] Loaded 23932 auto-discovered prefixes for remote repository central (prefixes-central.txt)
repo-probe/pom.xml: no problems
exit 0

Checked: the temporary directory existed during the run and was gone afterward.

mvnval -Dmaven.repo.local=repo-probe/unused-temp-property-repo --temp-local-repository repo-probe/pom.xml (exit 0)
$ mvnval -Dmaven.repo.local=repo-probe/unused-temp-property-repo --temp-local-repository repo-probe/pom.xml
[INFO] Loaded 23932 auto-discovered prefixes for remote repository central (prefixes-central.txt)
repo-probe/pom.xml: no problems
exit 0

Checked: the temporary directory existed during the run and was gone afterward.

Checked: the unused repository path was not created.

mvnval --local-repository repo-probe/cli-repo --temp-local-repository repo-probe/pom.xml (exit 2)
$ mvnval --local-repository repo-probe/cli-repo --temp-local-repository repo-probe/pom.xml
[ERROR] --local-repository and --temp-local-repository name different directories; give one.
exit 2
mvnval --mode raw --local-repository repo-probe/raw-ignored-repo repo-probe/pom.xml (exit 0)
$ mvnval --mode raw --local-repository repo-probe/raw-ignored-repo repo-probe/pom.xml
repo-probe/pom.xml: no problems
exit 0

Checked: the unused repository path was not created.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit 9c07cfd..eaabc88 — clean improvement, one minor leak in the test

Previous findings status: All previously raised findings (rename buildRaw → validate, clearRequestScopedCache removal, session-per-POM revert, effective mode, lazy StringBuilder, path deduplication via toRealPath()) remain addressed. No regressions.

New commit assessment (eaabc887 — "Name a POM in the report the way the caller named it"):

  • TextReporter.display() relative-path logic is correct. realPath() canonicalizes both cwd and pom before startsWith, so symlink-traversed working directories (macOS /var → /private/var) don't produce ../../private/var/... paths. Fallback to normalize() on IOException handles the non-existent path case.

  • JSON keeps absolute paths — correct decision, well-documented in the OutputFormat.JSON override comment. A machine-readable document consumed elsewhere must not depend on the producer's cwd.

  • OutputFormat.report() signature change (added Path cwd) is package-private, so no backward compatibility concern.

  • TestUtils.render uses Paths.get("/elsewhere") — ensures existing ReporterTest assertions exercise the absolute-path branch (POM paths never start with /elsewhere). Clean.

  • shouldPrintPathsRelativeToTheWorkingDirectory test — exercises both branches correctly (relative for in-cwd, absolute for outside-cwd). One issue noted below.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit eaabc88..135daf4 — previous finding addressed, no new issues

Previous finding status:

  1. ✅ Files.createTempDirectory("mvnval-outside-") leak (gnodet-bot) — Addressed. The temp directory is now wrapped in try/finally with leaf-first deleteIfExists cleanup: file → far/ → root. Ordering is correct, deleteIfExists is safe if creation failed partway through, and the test still exercises the absolute-path branch (the temp dir is genuinely outside @TempDir).

Clean fix.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit 135daf4..8d8f8b8 — two bugs fixed, no new issues

Previous findings status: All previously raised findings remain addressed. No regressions.

New commit assessment (8d8f8b88 — "Honor mvnval property overrides and Ctrl+C"):

Two independent bugs fixed in one commit:

  1. User properties not reaching the model builder — validateAll built ModelBuilderRequest without userProperties, so -Dproperty=value from the CLI was shadowed by POM <properties>. The fix passes context.protoSession.getUserProperties() into the request builder. The ModelBuilderRequest is now built once per POM in validateAll and threaded through validateOne → ValidationMode.problemsFor, which also simplifies ValidationMode — the request() factory and the Session/Path parameters are gone, replaced by a single ModelBuilderRequest. In EFFECTIVE mode, ModelBuilderRequest.builder(request).requestType(BUILD_EFFECTIVE).build() correctly copies userProperties via the copy constructor (line 202 of ModelBuilderRequest.java). shouldLetUserPropertiesOverridePomProperties covers both modes.

  2. Ctrl+C interrupted the wrong thread — the old signal -> Thread.currentThread().interrupt() ran on the signal dispatch thread, not the validation thread. The fix captures Thread.currentThread() before the try block and the handler calls validationThread.interrupt(). An AtomicBoolean cancellationRequested survives Thread.interrupted() calls inside the model builder. Previous handler restored in finally; interrupt flag cleared on all cancellation paths (canceled() and the outer finally). shouldCancelFromAnotherThreadAfterTheModelBuilderClearsTheInterrupt fires INT from CompletableFuture.runAsync, verifies the interrupt reached the right thread, confirms handler restoration, and checks that only one POM was attempted.

Static analysis: ast-grep flagged the two catch (Exception e) blocks — both are pre-existing, intentional, and documented (same pattern as mvnenc/mvnup).

Solid fixes with thorough test coverage.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@github-actions

This comment has been minimized.

@gnodet

gnodet commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

I pushed three improvements on top of this PR:

1. Suppress resolver noise in text mode

configureLogging now forces resolver logging to ERROR level in both text and JSON modes (unless -X/-e is passed). Previously only JSON mode silenced it; text output was cluttered with lines like [INFO] Loaded 24013 auto-discovered prefixes from ... that have nothing to do with POM validation.

2. Extract line/column from XmlReaderException

DefaultModelBuilder.add() now falls back to XmlReaderException.getLocation() when no InputLocation is present on the problem. Parser failures like Duplicated tag: 'relativePath' carry the location in the exception but it was never consulted, so the FATAL problem was reported without any line or column number.

3. XML source context display (-C / --context)

TextReporter now shows N lines of surrounding XML source around each problem location (default 2, configurable via -C N / --context N, disabled with -C 0). The problem line is marked with > and rendered in bold. Severity labels are colored (red for ERROR/FATAL, yellow for WARNING) when the terminal supports ANSI color.

Example output:

/path/to/pom.xml:
  FATAL Non-parseable POM: Duplicated tag: 'relativePath' @ line 6, column 5
    5 |     <relativePath/>
  > 6 |     <relativePath/>
    7 |   </parent>

@gnodet

gnodet commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

⚠️ License declaration missing

The pull request description must contain at least one of the following lines with a checked box ([x]):

- [ ] I hereby declare this contribution to be licensed under the [Apache License Version 2.0, January 2004](https://www.apache.org/licenses/LICENSE-2.0)
- [ ] I hereby declare that I have filed an [Apache Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).

This comment will be hidden automatically once the description is fixed.

@ikxeno you need to add the first line with a checked box

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits 8d8f8b8..3700924 — one real bug in the new session-mutation helpers

New commits assessed:

  • 2c1a714 bundle workspace reader for effective mode, honour -o
  • 61fa4bc IT for bundle workspace reader and --offline
  • be15945 quiet resolver noise, add line location and XML context display
  • 37009240 fix color detection — use MessageUtils.isColorEnabled() directly

Previous findings status: All previously raised findings remain addressed.

New findings:

  1. ⚠️ withOffline/withWorkspaceReader — clone attempt silently falls back to in-place mutation — the Javadoc describes a clone mechanism that does not work. session.withLocalRepository(session.getLocalRepository()) triggers the Objects.equals(basePath, localRepository.path()) short-circuit in AbstractSession.withLocalRepository(), so it returns this — no clone. rsession.setOffline(true) and rsession.setWorkspaceReader(reader) then mutate the original session in-place. The code happens to work today because the original session is not reused after validateAll mutates it, but the invariant stated in the Javadoc is false, and any future code that passes the same session to two independent callers will find the second caller has offline/workspace-reader state it did not set. See inline comments.

  2. ℹ️ TextReporter.contextLines re-reads the file once per problem — low severity: POMs are small. See inline comment.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits 8d8f8b8..3700924 — one real bug in the new session-mutation helpers

New commits assessed:

  • 2c1a714 bundle workspace reader for effective mode, honour -o
  • 61fa4bc IT for bundle workspace reader and --offline
  • be15945 quiet resolver noise, add line location and XML context display
  • 37009240 fix color detection — use MessageUtils.isColorEnabled() directly

Previous findings status: All previously raised findings remain addressed.

New findings:

  1. ⚠️ withOffline/withWorkspaceReader — clone attempt silently falls back to in-place mutation — the Javadoc describes a clone mechanism that does not work. session.withLocalRepository(session.getLocalRepository()) triggers the Objects.equals(basePath, localRepository.path()) short-circuit in AbstractSession.withLocalRepository(), so it returns this — no clone. rsession.setOffline(true) and rsession.setWorkspaceReader(reader) then mutate the original session in-place. The code happens to work today because the original session is not reused after validateAll mutates it, but the invariant stated in the Javadoc is false, and any future code that passes the same session to two independent callers will find the second caller has offline/workspace-reader state it did not set. See inline comments.

  2. ℹ️ TextReporter.contextLines re-reads the file once per problem — Files.readAllLines is called for every problem in a report, even when multiple problems share the same source file. Low severity for a CLI validation tool (POMs are small), but a single Map<Path, List<String>> cache would eliminate the redundancy.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet

gnodet commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

The pr-check / license-declaration CI step is failing because the PR description does not contain a checked license declaration.

Please add one of the following lines (with the box checked [x]) to the PR description:

or

Once the description is updated, the check will re-run and clear automatically.

@gnodet gnodet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit e6239a3 — previous findings addressed, merge conflict resolved

Previous findings status:

  1. ✅ withOffline/withWorkspaceReader — clone attempt silently falls back to in-place mutation (gnodet-bot) — Addressed. The broken-clone pretense is gone. Both helpers now directly cast to DefaultRepositorySystemSession and mutate in-place, with accurate Javadoc stating the safety contract (validateAll reassigns session immediately and does not retain the pre-mutation reference). Clean fix.

  2. ℹ️ TextReporter.contextLines re-reads the file once per problem — low severity, not blocking. Can be addressed in a follow-up if desired.

Additional changes in this commit:

  • module-info.java — exports org.apache.maven.api.cli.mvnval added to the maven-api-cli module descriptor. Correct.
  • IT settings fix — test isolation improvement.

Merge conflict with master: Resolved. Both branches added module-info.java for maven-api-cli; the merge kept the exports org.apache.maven.api.cli.mvnval line from this branch.

Remaining blocker: The license-declaration CI check fails because the PR description does not contain a checked [x] license declaration. @ikxeno, please edit the PR description to add a checked checkbox — for example: - [x] I hereby grant Apache Software Foundation (ASF) a license to reproduce, modify, and distribute my contribution. The CI bot will auto-resolve the failure once the description is updated.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet gnodet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits 3700924..61ac635 — clone bug fixed, clean

Previous findings status:

  1. ✅ withOffline — clone never happens; Javadoc claimed false invariant (gnodet-bot) — Addressed in e6239a3. The broken withLocalRepository(same-repo) clone attempt is removed. The method now directly casts to DefaultRepositorySystemSession and mutates in-place, with a comment that explicitly documents the safety assumption: "Safe only because validateAll reassigns session immediately and does not retain the pre-mutation reference." The false Javadoc is gone. Honest and correct.

  2. ✅ withWorkspaceReader — same broken-clone pattern (gnodet-bot) — Addressed in e6239a3. Same fix applied consistently. The misleading "it does not mutate the original session, which the tests may reuse across runs" Javadoc is removed entirely.

New changes assessment (e6239a3 — "fix withOffline/withWorkspaceReader clone, module-info export, IT settings"):

  • module-info.java export — adds api/maven-api-cli module exports needed by the new mvnval packages. Correct; without this the module system would block cross-module access at runtime.
  • IT settings fix — adjusts the BundleWorkspaceReader IT to account for real settings-derived repository configuration. No new logic, test correction only.

All previous findings remain addressed. No new issues.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit e6239a3 — previous findings addressed, clean fix

Previous findings status:

  1. ✅ withOffline clone never happens (gnodet-bot) — Addressed. Correctly drops the broken withLocalRepository(same-path) clone attempt and embraces honest in-place mutation with a clear safety comment. The session is fresh from createSession() and local to validateAll() — no external reference can observe the mutation.

  2. ✅ withWorkspaceReader same broken-clone pattern (gnodet-bot) — Addressed. Same fix applied. setWorkspaceReader() now runs on the right resolver session.

New commit assessment (e6239a3):

  • ValidateInvoker.java — in-place mutation is correct and the inline safety comment explains the invariant clearly.
  • module-info.java — conflict resolved cleanly; mvnval export is present and all 9 leaf packages are exported.
  • MavenITmng8650MvnvalBundleWorkspaceReaderTest.java — newVerifier(testDir, null) correctly uses the Path overload and skips the remote-settings fixture that is irrelevant for mvnval (which derives its own repositories).

One minor nit on the Javadoc (inline).

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet gnodet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit e6239a3 / 61ac635 — previous findings addressed, no new issues

Previous findings status:

  1. ✅ withOffline — clone never happens; Javadoc claimed false invariant — Addressed in e6239a3. The broken withLocalRepository(same-repo) clone attempt is removed. The method now directly casts to DefaultRepositorySystemSession and mutates in-place, with an accurate comment documenting the safety assumption. Correct fix.

  2. ✅ withWorkspaceReader — same broken-clone pattern — Addressed in e6239a3. Same direct-cast-and-mutate approach, misleading Javadoc removed.

ℹ️ TextReporter.contextLines file re-read per problem — low severity, not blocking for a CLI tool operating on small POMs. Acceptable to defer.

CI: license-declaration now passes. All inline threads resolved. No remaining blockers.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits 3700924..069f377 — previous findings addressed, one Javadoc nit self-corrected

Previous findings status:

  1. ✅ withOffline/withWorkspaceReader — clone attempt silently falls back to in-place mutation (gnodet-bot) — Addressed in e6239a32. The broken-clone pretense is gone. Both helpers now directly cast to DefaultRepositorySystemSession and mutate in-place, with accurate inline comments stating the safety contract (validateAll creates a fresh session via createSession() at line 204 and does not retain a reference after the call returns). Clean and honest.

New commit assessment (069f377d — "fix: update withOffline Javadoc to reflect in-place mutation"):

  • The Javadoc at line 376 previously said "by cloning the underlying resolver session with offline set to true" — inconsistent with the inline comment introduced in e6239a32 (which correctly said "Mutate in-place"). 069f377d updates the Javadoc to "by setting offline to true on the underlying resolver session." Accurate and consistent with the implementation.

All previous findings remain addressed. No new issues.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit 61ac635..069f377 — previous finding addressed, no new issues

Previous finding status:

  1. ✅ Stale Javadoc in withOffline (gnodet-bot) — Addressed. The phrase "by cloning the underlying resolver session with offline set to true" is replaced with "by setting offline to true on the underlying resolver session," which accurately reflects the in-place mutation semantics.

No new issues introduced. The single-line Javadoc correction is correct and complete.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@Bukama

Bukama commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Hi,
I leave the technical parts of this to @gnodet. But if this gets merged, I encourage you to also create a PR on maven-site and add a small page + menu entry in the tool section. Thank you.

@gnodet gnodet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commit fd9b90e — test-only fixes, no new issues

Previous findings status: All previously raised findings remain addressed.

New commit assessment (fd9b90e — "Use native paths and raw mode in mvnval tests"):

  • ValidateInvokerTest — Path.of("near", "pom.xml") replaces the hardcoded "near/pom.xml" string. Correct Windows-portability fix: path separator must match the platform's separator in the assertion.

  • MavenITgh10442MvnvalValidatePomTest — Adds --mode raw to the three existing ITs. The commit message explains why: the Verifier injects --install-settings, which mvnval in effective mode rejects (since effective mode derives its own repository configuration and does not allow external settings). Raw mode has no such restriction. Correct fix — the ITs were failing in effective mode for a legitimate reason, not a bug.

No production code changes. No regressions.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review after commits 3700924..fd9b90e — all previous findings addressed

New commits assessed:

  • e6239a3 mvnval: fix withOffline/withWorkspaceReader clone, module-info export, IT settings
  • 61ac635 Merge remote-tracking branch 'origin/master'
  • 069f377 fix: update withOffline Javadoc to reflect in-place mutation
  • fd9b90e Use native paths and raw mode in mvnval tests

Previous findings status:

  1. ✅ withOffline/withWorkspaceReader — clone never happens (HIGH) — Fixed in e6239a3. The broken session.withLocalRepository(session.getLocalRepository()) clone attempt is removed; both methods now mutate the underlying DefaultRepositorySystemSession in-place with a clear comment explaining the safety invariant ("Safe only because validateAll reassigns session immediately and does not retain the pre-mutation reference"). The stale Javadoc phrase "by cloning the underlying resolver session" is gone (069f377). Fix is correct: ApiRunner.createSession() does not freeze the session, and @BeforeEach creates a fresh shared session per test, so there is no cross-test mutation hazard.

  2. ℹ️ TextReporter.contextLines file re-read (LOW) — Informational, no action expected. Still present, still low-severity for a CLI validation tool.

New commit assessment:

  • module-info.java — maven-api-cli now exports org.apache.maven.api.cli.mvnval. Required for module-system access to ValidateOptions and friends. Correct.
  • Path.of("near", "pom.xml") instead of "near/pom.xml:" in the test — correct Windows cross-platform fix.
  • ITs switched to --mode raw — Verifier injects --install-settings by default, which effective mode rightly rejects; raw mode is the correct scope for these tests.
  • newVerifier(testDir, null) instead of newVerifier(testDir.toString()) — uses the overload that does not inject install settings.

No new issues found.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@ikxeno

ikxeno commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

@gnodet

Thanks for your work on this. I've pushed fd9b90e47d on top of your changes. It fixes the Windows path assertion and explicitly selects --mode raw in the three existing mvnval ITs.

Could you please approve the CI run for the updated commit?

@gnodet

gnodet commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

The maven-site documentation is ready: apache/maven-site#1705

Adds:

  • content/markdown/tools/mvnval.md — full page covering modes (raw vs effective), options, exit codes, output formats, and integration
  • content/markdown/tools/index.md — adds mvnval to the tools table

@gnodet gnodet added java Pull requests that update Java code enhancement New feature or request labels Oct 13, 2026
- Add ModelBuilderSession.validate() API method that collects all problems
  (errors and warnings) instead of throwing on the first error, enabling
  complete diagnostic reporting; declared default so existing implementations
  keep compiling unchanged
- Add mvnval CLI tool reachable as `mvnval`, `mvn --val`, and from mvnsh;
  takes any number of POM files (defaults to ./pom.xml), writes text or JSON
  output, and returns structured exit codes: 0=clean, 1=errors, 2=bad usage,
  3=cancelled, 4=warnings-only
- Two validation modes: --mode raw (no repository access, works offline and
  on unpublished POMs) and --mode effective (default, resolves parents and
  BOMs, runs all checks including those needing inherited values)
- Bundle workspace reader for effective mode: pre-scans all given POMs to
  build a GAV index so parent/BOM lookups among the bundle are answered from
  disk, making the verdict order-independent and avoiding redundant downloads
- Honour -o/--offline in effective mode; refuse -s/-ps/-is (cannot redirect
  the settings ApiRunner reads at session-creation time)
- Security hardening: no core extensions loaded, no container stood up, no
  maven.ext.class.path honoured; .mvn/jvm.config still reaches the launcher
  (documented in THREAT_MODEL.md)
- --local-repository and --temp-local-repository options to aim or isolate
  the local repository; throwaway directory deleted on exit and on SIGTERM
- Text output shows coloured severity labels and surrounding XML source
  context around each problem location; JSON output keeps absolute paths
- Deduplicate POMs named multiple times (normalise to real path via
  toRealPath); print paths relative to working directory in text output
- Add integration tests covering raw/effective validation, bundle workspace
  reader, offline mode, and mvnsh registration
@gnodet
gnodet force-pushed the MNG-8650-pom-validator branch from fd9b90e to 327d5b7 Compare October 13, 2026 09:31
@gnodet
gnodet merged commit dabd7b2 into apache:master Oct 13, 2026
1 check passed
@github-actions github-actions Bot added this to the 4.1.0 milestone Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request java Pull requests that update Java code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MNG-8650] Provide a tool to validate a POM

7 participants