Skip to content

feat: build report — structured JSON report with per-mojo log capture - #14077

Open
gnodet wants to merge 22 commits into
apache:masterfrom
gnodet:feature/build-report
Open

gnodet wants to merge 22 commits into
apache:masterfrom
gnodet:feature/build-report

Conversation

@gnodet

@gnodet gnodet commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Summary

Introduces a structured build report generated at the end of each Maven session. The report captures per-mojo timing, status, and log output, as well as subproject and build-level metadata, and writes an atomic JSON file to target/build-reports/.

This complements the unified Logger/LogEvent/LogSink API introduced in #13832 and uses its fan-out mechanism to route enriched log events to the collector without any static coupling.


Public API (api/maven-api-core)

New package org.apache.maven.api.build.report with the following @Experimental interfaces:

Interface Description
BuildReport Top-level report: status, duration, invocation, subprojects, failures, build log
SubprojectReport Per-subproject: status, duration, mojos, log output, trace context
MojoReport Per-mojo: goal, phase, status, duration, log output, trace context
FailureReport Failure detail: subproject, mojo, exception type, message, truncated stack trace
BuildStatus SUCCESS / FAILURE / SKIPPED
BuildInvocation CLI invocation context: goals, profiles, properties, make-behavior, etc.

New constants in Constants:

  • MAVEN_BUILD_REPORT_MAX_LOG_EVENTS — cap on log events per scope (default: 500)
  • MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES — cap on stack-trace lines per failure (default: 30)
  • MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES — cap on throwable lines per log event (default: 10)

Implementation (impl/maven-impl)

BuildReportCollector implements ExecutionListener + LogSink + SpiService and is auto-discovered via the existing SPI mechanism (lookupList(SpiService.class)). No @Named/Sisu wiring needed.

Log capture is received directly from ProjectBuildLogAppender after it has enriched events with projectId/mojoId. Events are routed to per-mojo, per-subproject, or build-level ring buffers (each capped, default 500 events), then drained into the report at session end.

Timing and status are tracked via typed ExecutionListener callbacks (sessionStarted, mojoStarted, mojoSucceeded, mojoFailed, projectStarted, projectSucceeded, projectFailed, sessionEnded).

Output: an atomic build-report-{timestamp}.json plus an atomic build-report-latest.json symlink under target/build-reports/. Falls back to a plain copy on Windows.

Thread safety: concurrent -T builds write to their own ConcurrentHashMap entries. The singleton is reusable across builds (mvnd / embedded Maven): sessionEnded() clears all per-session state.


Fan-out wiring (impl/maven-core + impl/maven-cli)

ProjectBuildLogAppender replaces the former static reportCapture: Consumer<LogEvent> hook with a clean secondarySinks: List<LogSink> fan-out:

  • New setSpiSinks(List<LogSink>) method on ProjectBuildLogAppender
  • LookupContext gains a projectBuildLogAppender field so lookup() can reach the already-constructed appender
  • LookupInvoker.lookup() discovers all SpiService instances that implement LogSink and wires them in after the DI container is initialized (safely after configureLogging())

JSON output format

{
  "reportVersion": "1.0",
  "invocation": {
    "goals": ["clean", "install"],
    "offline": false,
    "updateSnapshots": false,
    "batchMode": false,
    "threads": 1
  },
  "status": "SUCCESS",
  "startTime": "2025-07-29T14:30:00Z",
  "durationMs": 12345,
  "mavenVersion": "4.2.0",
  "javaVersion": "21.0.2",
  "projectId": "org.example:my-app:1.0.0",
  "multiSubproject": false,
  "threads": 1,
  "subprojects": [
    {
      "groupId": "org.example",
      "artifactId": "my-app",
      "version": "1.0.0",
      "status": "SUCCESS",
      "durationMs": 500,
      "mojos": [
        {
          "goal": "compile",
          "phase": "compile",
          "groupId": "org.apache.maven.plugins",
          "artifactId": "maven-compiler-plugin",
          "version": "3.15.0",
          "executionId": "default-compile",
          "status": "SUCCESS",
          "startTime": "2025-07-29T14:30:00.100Z",
          "durationMs": 300,
          "output": [
            { "level": "INFO", "message": "Compiling 42 source files" }
          ]
        }
      ],
      "output": []
    }
  ],
  "failures": [],
  "problems": [],
  "output": []
}

Tests

  • BuildReportCollectorTest (10 tests in impl/maven-impl) — full lifecycle simulation, log-capture routing, cap enforcement, state-clear between builds, trace context capture, mojo skipping
  • BuildReportJsonWriterTest (10 tests in impl/maven-impl + mirrored in impl/maven-core) — JSON serialization, truncation of stack traces and throwables, edge cases (null fields, empty collections)

Checklist

  • New API types are @Experimental
  • No static coupling between maven-impl and maven-core (SPI fan-out only)
  • maven-impl does not depend on maven-core
  • Thread-safe for parallel builds (-T)
  • mvnd / embedded Maven reuse safe (state cleared at session end)
  • Atomic file writes (temp + rename)
  • Windows fallback (copy instead of symlink)
  • All caps configurable via system/user properties

Hermes Agent (Claude Sonnet 4.5) on behalf of Guillaume Nodet

@gnodet
gnodet force-pushed the feature/build-report branch 2 times, most recently from f70ca37 to 8205931 Compare November 19, 2026 12:46
@gnodet gnodet mentioned this pull request Nov 19, 2026
1 task done
@gnodet
gnodet marked this pull request as ready for review November 21, 2026 20:17

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

Build Report Feature — Code Review

New feature is well-structured overall. Five findings below, two of which should be addressed before merge.


🔴 Medium — No opt-out for the build report feature

BuildReportCollector.sessionEnded() unconditionally calls writeReport() and there is no mechanism to disable the feature. Constants defined in Constants.java (MAVEN_BUILD_REPORT_OUTPUT_FILE, MAVEN_BUILD_REPORT_INCLUDE_LOG, and MAX_* properties) control the output location and content, but no MAVEN_BUILD_REPORT_ENABLED or equivalent toggle is provided. LookupInvoker unconditionally wires all SpiService LogSink implementations, so every build — including failed builds — writes JSON to disk with no way to disable it.

Suggested path: add a maven.build.report.enabled=true property (default true for backward compat) and gate the collector in sessionEnded() or in the invoker wiring.


🔴 Medium — needsMetadata() drops secondary-sink awareness → null sourceClassName/sourceMethodName in report

The diff changes ProjectBuildLogAppender.Sink.needsMetadata() from:

return needsMetadata || reportCapture != null;

to:

return needsMetadata;

The reportCapture field was replaced by secondarySinks (which includes BuildReportCollector), but the new needsMetadata() does not check whether any secondary sink needs metadata. BuildReportCollector does not override needsMetadata(), so it inherits the LogSink default of false. Meanwhile BuildReportJsonWriter writes sourceClassName and sourceMethodName fields (useful for diagnosing plugin failures). When the primary sink's needsMetadata field is false, StackWalker resolution is skipped and those fields will always be null in the report JSON.

Fix (choose one):

// Option A — check secondary sinks
return needsMetadata || secondarySinks.stream().anyMatch(LogSink::needsMetadata);

// Option B — BuildReportCollector overrides needsMetadata()
@Override
public boolean needsMetadata() { return true; }

🟡 Low — projectKey() omits version — unsafe as map key in multi-version reactors

projectKey() returns groupId + ":" + artifactId without version. This is used as the key for all per-project maps (mojoTimings, projectStartTimes, projectStatuses, etc.). In a reactor with two modules sharing the same groupId:artifactId but different versions (legal in Maven), all state would be comingled under a single key. Consider including the version: groupId + ":" + artifactId + ":" + version.


🟡 Low — projects.get(0) may not be the top-level project

topProject is determined by endSession.getProjects().get(0). In standard builds this is the aggregator POM, but with -pl or --resume-from, the first project may not be the root. session.getTopLevelProject() (Maven 4 API) returns the correct root regardless of project ordering.


🟡 Low — PII captured in report without enforcement mechanism

user.home and user.name are written to the JSON sysInfo block. The adjacent comment acknowledges the risk and notes the report is "local and gitignored," but this is a weak mitigation: CI systems routinely upload build artifacts (including target/) to artifact stores or log collectors. The comment even warns "Do not include these properties in reports that may be shared externally" without providing any mechanism to enforce this.

Consider either (a) omitting these properties from the default output, or (b) adding a maven.build.report.include-pii=false property to let users opt out.


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.

Following up on my earlier review — the five findings from SHA 8205931b are not yet addressed (this new commit adds separate functionality). They remain open:

  1. 🔴 Medium — No maven.build.report.enabled toggle to opt out of the feature
  2. 🔴 Medium — needsMetadata() does not check secondary sinks → sourceClassName/sourceMethodName will always be null in the report (fix: return needsMetadata || secondarySinks.stream().anyMatch(LogSink::needsMetadata))
  3. 🟡 Low — projectKey() omits version — unsafe as map key in multi-version reactors
  4. 🟡 Low — projects.get(0) may not be the top-level project; use session.getTopLevelProject()
  5. 🟡 Low — user.home / user.name written to JSON without an opt-out mechanism

New commit: "Write partial build report on shutdown"

The shutdown-hook mechanism is well-designed — idempotency via AtomicBoolean.compareAndSet correctly prevents the hook and sessionEnded() from writing competing reports, and the mvnd-reuse path (hook removal + reportWritten reset in sessionStarted) is covered by the new tests. Two issues below.


🟡 Low — @Named/@Singleton + META-INF/services registration — dual-discovery risk

Adding @Named/@Singleton while META-INF/services/org.apache.maven.api.spi.SpiService already lists BuildReportCollector creates two discovery paths. Maven's DI container (doBindImplicit) walks all supertypes including interfaces, so a @Named @Singleton class bound as SpiService will be returned by lookupList(SpiService.class). As long as this yields the same singleton that the services file would have produced, there's no double-registration — but this depends on whether the services file is also consumed independently (e.g. via ServiceLoader) in any code path.

Before merging, verify that no ServiceLoader.load(SpiService.class) or equivalent exists in the DI-wired runtime that would create a second instance alongside the Sisu singleton. If the services file is now redundant (Sisu is the only discovery path), consider removing it to avoid confusion. If ServiceLoader is still used somewhere, the two instances will silently diverge.

🟡 Low — Package-private fields widened for test access without @VisibleForTesting

session, shutdownHook, and reportWritten are changed from private to package-private to enable direct access in tests. On a @Singleton, leaking internal state via package visibility is a maintenance hazard — another class in the same package could inadvertently read or write these fields. Add // visible for testing comments on each field (or use @VisibleForTesting from Guava/the project's own annotation if available) to make the intent explicit and discourage accidental use.

    // visible for testing
    volatile Session session;
    /** JVM shutdown hook used to persist a partial build report on unexpected termination. */
    // visible for testing
    volatile Thread shutdownHook;

    /** Ensures that normal completion and shutdown hook do not write competing reports. */
    // visible for testing
    final AtomicBoolean reportWritten = new AtomicBoolean();

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.

Following up on my earlier reviews — none of the 7 open findings have been addressed. The latest commit (e59696271) correctly fixes RequestTraceTest to use assertFalse(x.contains(listener)) instead of assertTrue(x.isEmpty()), which was needed because BuildReportCollector auto-registers as an SpiService listener. No new issues in this commit. ✅


The 7 findings from previous reviews remain open:

From the initial review (SHA 8205931b)

🔴 Medium — No opt-out for the build report feature

BuildReportCollector.sessionEnded() unconditionally writes JSON to disk with no way to disable it. Add a maven.build.report.enabled=true property (default true) gating the collector.

🔴 Medium — needsMetadata() does not check secondary sinks

The change from return needsMetadata || reportCapture != null to return needsMetadata drops secondary-sink awareness. BuildReportCollector doesn't override needsMetadata(), so sourceClassName/sourceMethodName will always be null in the report JSON. Fix:

// Option A
return needsMetadata || secondarySinks.stream().anyMatch(LogSink::needsMetadata);
// Option B — in BuildReportCollector
@Override public boolean needsMetadata() { return true; }

🟡 Low — projectKey() omits version — unsafe in multi-version reactors

groupId + ":" + artifactId is used as the map key for all per-project state. Two modules sharing the same groupId:artifactId but different versions would have their state comingled. Use groupId + ":" + artifactId + ":" + version.

🟡 Low — projects.get(0) may not be the top-level project

With -pl or --resume-from, the first project may not be the root. Use session.getTopLevelProject() instead.

🟡 Low — PII captured without enforcement mechanism

user.home and user.name written to JSON sysInfo block with only a comment as mitigation. Add a maven.build.report.include-pii=false opt-out property.


From the second review (SHA 4ecf4145)

🟡 Low — @Named/@Singleton + META-INF/services — dual-discovery risk

BuildReportCollector now has both @Named @Singleton and a META-INF/services/org.apache.maven.api.spi.SpiService registration. Verify no ServiceLoader.load(SpiService.class) path exists that would create a second instance alongside the Sisu singleton. If the services file is now redundant, remove it.

🟡 Low — Package-private fields widened without @VisibleForTesting

session, shutdownHook, and reportWritten changed from private to package-private for test access on a @Singleton. Add // visible for testing comments (or @VisibleForTesting) on each field to make intent explicit.


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.

Following up on my earlier reviews — the 7 open findings from prior reviews remain unaddressed. The latest commit (a49a22c4) is a Javadoc-only fix for JDK 17 compatibility (replacing {@link} with {@code} in internal classes, removing invalid @param on record class-level Javadoc). No new behavioural issues introduced. One minor doc nit on the {@code} conversion below.


Open findings from previous reviews (all still unresolved)

🔴 Medium — No opt-out for the build report feature
BuildReportCollector.sessionEnded() unconditionally writes JSON to disk. No maven.build.report.enabled toggle exists. Add a property (default true) to allow users to disable the collector.

🔴 Medium — needsMetadata() does not check secondary sinks
The change from return needsMetadata || reportCapture != null to return needsMetadata drops secondary-sink awareness. BuildReportCollector does not override needsMetadata(), so sourceClassName/sourceMethodName will always be null in the JSON report.
Fix: return needsMetadata || secondarySinks.stream().anyMatch(LogSink::needsMetadata);

🟡 Low — projectKey() omits version — unsafe in multi-version reactors
groupId + ":" + artifactId is used as the map key for all per-project state. Use groupId + ":" + artifactId + ":" + version to handle multi-version reactors correctly.

🟡 Low — projects.get(0) may not be the top-level project
With -pl or --resume-from, the first project may not be the root. Use session.getTopLevelProject().

🟡 Low — PII captured without enforcement mechanism
user.home and user.name written to JSON sysInfo block with only a comment as mitigation. Add a maven.build.report.include-pii=false opt-out property.

🟡 Low — @Named/@Singleton + META-INF/services — dual-discovery risk
BuildReportCollector has both @Named @Singleton and a META-INF/services/org.apache.maven.api.spi.SpiService registration. Verify no ServiceLoader.load(SpiService.class) path exists that would create a second instance. If the services file is now redundant, remove it.

🟡 Low — Package-private fields widened without @VisibleForTesting
session, shutdownHook, and reportWritten changed from private to package-private for test access on a @Singleton. Add // visible for testing comments on each field.


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.

Following up on my earlier reviews — 1 of the 7 open findings has been addressed in this batch of commits; the other 6 remain open.


✅ Resolved — Dual-discovery risk (@Named/@Singleton + META-INF/services)

The impl/maven-impl/src/main/resources/META-INF/services/org.apache.maven.api.spi.SpiService file has been deleted. BuildReportCollector is now discovered exclusively through Sisu DI (@Named @Singleton). No second instance can be created via ServiceLoader. ✅


Still open from previous reviews

🔴 Medium — No opt-out for the build report feature

BuildReportCollector.sessionEnded() unconditionally writes JSON to disk with no way to disable it. Add a maven.build.report.enabled=true property (default true) gating the collector in sessionEnded().

🔴 Medium — needsMetadata() does not check secondary sinks

ProjectBuildLogAppender.Sink.needsMetadata() returns only needsMetadata (the primary sink flag). BuildReportCollector does not override needsMetadata(), so sourceClassName/sourceMethodName will always be null in the JSON report. Fix:

// Option A — check secondary sinks in ProjectBuildLogAppender.Sink
return needsMetadata || secondarySinks.stream().anyMatch(LogSink::needsMetadata);

// Option B — override in BuildReportCollector
@Override
public boolean needsMetadata() { return true; }

🟡 Low — projectKey() omits version — unsafe in multi-version reactors

groupId + ":" + artifactId is used as the map key for all per-project state (mojoTimings, projectStartTimes, projectStatuses, etc.). Two modules sharing the same groupId:artifactId but different versions would have their state comingled. Use groupId + ":" + artifactId + ":" + version.

🟡 Low — projects.get(0) may not be the top-level project

topProject = projects.get(0) in buildReport(). With -pl or --resume-from, the first project in the list may not be the root. Use session.getTopLevelProject().

🟡 Low — PII captured without enforcement mechanism

user.home and user.name are written to the JSON sysInfo block with only a comment as mitigation. Add a maven.build.report.include-pii=false opt-out property.

🟡 Low — Package-private fields widened without @VisibleForTesting

session, shutdownHook, and reportWritten are package-private for test access on a @Singleton. Add // visible for testing comments (or @VisibleForTesting) on each field.


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

@gnodet
gnodet force-pushed the feature/build-report branch 3 times, most recently from 75ff3b6 to 0ba1dbd Compare November 27, 2026 08:28

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

Following up on my earlier reviews — all 7 open findings have been addressed in the latest commits. Details below.


✅ Finding 1 — No opt-out for the build report feature

maven.buildReport.enabled constant added in Constants.java with @Config(type = "java.lang.Boolean", defaultValue = "true"). sessionStarted() reads it via readBooleanProperty() and gates both the shutdown-hook registration and sessionEnded() on the flag. The reportWritten.set(false) and removeShutdownHook() are still called before the early-return when !reportEnabled, ensuring clean state on session reuse (mvnd). ✅

✅ Finding 2 — needsMetadata() does not check secondary sinks

Fixed to return needsMetadata || secondarySinks.stream().anyMatch(LogSink::needsMetadata). secondarySinks is a volatile List<LogSink> replaced with a CopyOnWriteArrayList on setSpiSinks(), so the stream() call is thread-safe. ✅

✅ Finding 3 — projectKey() omits version

Now returns groupId + ":" + artifactId + ":" + project.version(). ✅

✅ Finding 4 — projects.get(0) may not be top-level project

Replaced with a path-based match against endSession.getTopDirectory(): the stream filters for the project whose basedir equals the top directory, with get(0) as a fallback. session.getTopLevelProject() does not exist on the Maven 4 Session API, so this is the correct approach. ✅

✅ Finding 5 — PII captured without enforcement mechanism

maven.buildReport.includePii constant added (default false). When false, sessionStarted() creates a filtered copy of DefaultBuildInvocation with user.home and user.name removed from systemInfo. ✅

✅ Finding 6 — Dual-discovery risk (resolved in 5th review)

Confirmed resolved — META-INF/services file removed in a prior commit. ✅

✅ Finding 7 — Package-private fields without @VisibleForTesting

// visible for testing comments added to session, shutdownHook, and reportWritten. ✅


🟡 Low — PII stripping silently skips non-DefaultBuildInvocation implementations

The PII filter uses a pattern-match guard:

if (!includePii && this.buildInvocation instanceof DefaultBuildInvocation inv) {

If session.buildInvocation() returns a non-DefaultBuildInvocation implementation (e.g. from an embedder), user.home/user.name are not stripped even when includePii=false. The intent of the property is to suppress PII regardless of the implementation. Consider either (a) having BuildInvocation expose a withoutPii() method (interface contract), or (b) documenting that this opt-out only applies when DefaultBuildInvocation is the provider.


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.

Following up on my earlier reviews — the new commit (c0c224f2) is a correct module-info fix that adds the missing qualified export of org.apache.maven.impl.build to the same five modules as the adjacent impl.* exports. No new findings from this commit. ✅


Still open from the previous review

🟡 Low — PII stripping silently skips non-DefaultBuildInvocation implementations

The PII filter uses a pattern-match guard:

if (!includePii && this.buildInvocation instanceof DefaultBuildInvocation inv) {

If session.buildInvocation() returns a non-DefaultBuildInvocation implementation (e.g. from an embedder), user.home/user.name are not stripped even when includePii=false. The intent of the property is to suppress PII regardless of the implementation. Consider either (a) having BuildInvocation expose a withoutPii() method (interface contract), or (b) documenting that this opt-out only applies when DefaultBuildInvocation is the provider.


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.

Following up on my earlier reviews — the last open finding has been addressed in this commit.


✅ Finding — PII stripping silently skips non-DefaultBuildInvocation implementations

The comment in BuildReportCollector.sessionStarted() now explicitly documents that the PII opt-out (maven.buildReport.includePii=false) only applies when session.buildInvocation() returns a DefaultBuildInvocation, and that embedders supplying a custom implementation are responsible for filtering PII themselves (option b from the previous review). ✅


All previous findings are resolved. LGTM.

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

@gnodet
gnodet force-pushed the feature/build-report branch from 08148ff to 944e543 Compare November 27, 2026 09:46

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

Following up on my earlier reviews — previous findings are all resolved. These 3 commits are clean.

One low-severity observation on the from(Session) refactor:

The method-level Javadoc (@return a new immutable build invocation instance) is accurate but the description above it ("Creates a BuildInvocation snapshot from the current session state") overstates what this method now returns: goals, activeProfiles, selectedProjects, excludedProjects, makeBehavior, resumeFrom, and reactorFailureBehavior are all empty/defaulted. Only userProperties, systemInfo, and threads are populated from the session.

Worth updating the Javadoc to reflect the narrowed scope (e.g. "Creates a minimal BuildInvocation from generic Session properties").

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.

Following up on my earlier reviews — previous findings are all resolved. This new commit (2db65809) adds threadName to MojoReport. Two observations.


🔴 Medium — @since 4.1.0 on threadName() is wrong

Every method and type introduced by this PR uses @since 4.2.0. The threadName() method has @since 4.1.0, which is inconsistent and incorrect — this feature lands in 4.2.0-SNAPSHOT.


🟡 Low — threadName for SKIPPED mojos captures the event-dispatch thread, not an execution thread

In BuildReportCollector.mojoSkipped(), Thread.currentThread().getName() captures the thread that fires the event, not a thread that executed the mojo (there is none — the mojo was skipped). The API contract says "the name of the thread that executed this mojo", which is misleading for BuildStatus.SKIPPED entries.

Options:

  • Return null for skipped mojos (Javadoc already allows it: "or null if not captured")
  • Or update the Javadoc of threadName() to clarify that for SKIPPED mojos the value is the event-dispatch thread and may not be meaningful

🔁 Still open — DefaultBuildInvocation.from(Session) Javadoc overstates scope

Raised in my previous review: the Javadoc on the from(Session) method (line 87: "Creates a {@link BuildInvocation} snapshot from the current session state") overstates what the method returns — only userProperties, systemInfo, and threads are populated; goals and lifecycle fields default to empty. Still not addressed.

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.

Following up on my earlier reviews.

Still open — 2 findings from the threadName commit (2db65809)

🔴 Medium — @since 4.1.0 on MojoReport.threadName()

Every method in this PR uses @since 4.2.0; this one has @since 4.1.0. Should be @since 4.2.0.

🟡 Low — DefaultBuildInvocation.from(Session) Javadoc overstates scope

Raised twice previously. The method description ("Creates a {@link BuildInvocation} snapshot from the current session state") overstates the return: only userProperties, systemInfo, and threads are populated. Still not updated.


New findings from this commit (3d00913b) — StepReport


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

@gnodet
gnodet force-pushed the feature/build-report branch from 3d00913 to 1e0affc Compare December 1, 2026 07:33

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

Following up on my earlier reviews.

Still open — 2 @since version errors

🔴 Medium — @since 4.1.0 on MojoReport.threadName()

Already raised twice previously. Every method and type introduced by this PR uses @since 4.2.0. The threadName() method has @since 4.1.0, which is incorrect — this feature lands in 4.2.0. The adjacent traceId() and spanId() methods correctly use @since 4.2.0.

🔴 Medium — @since 4.1.0 on StepReport class (new)

The StepReport interface class-level Javadoc uses @since 4.1.0. This is a new type introduced in this PR — it should be @since 4.2.0, consistent with every other new type in the build.report package.


New findings from commit 3d00913b — StepReport

🟡 Medium — startTime captures scheduling time, not execution start

step.startTime = MonotonicClock.now() is set on the scheduler thread at line 609, before executor.execute() submits the lambda at line 612. The StepReport.startTime() Javadoc says "When this step started executing (wall-clock time)" — but the value reflects when the step was scheduled onto the executor queue, not when the worker thread actually began executing it. Under thread pool contention (more steps ready than worker threads), the gap is non-trivial and will produce misleading timeline visualizations. Moving the assignment inside the lambda body (after step.threadName = Thread.currentThread().getName()) would capture the true execution start.

🟡 Medium — stepReportData.clear() is never called — stale data leaks across builds

StepReportData has a clear() method that sets steps = null, but clearSessionState() in BuildReportCollector does not call it. clearSessionState() resets every other per-session map (mojoTimings, projectStartTimes, etc.) but leaves stepReportData populated. In Maven daemon (mvnd) or embedded Maven reuse scenarios, step data from a previous build will appear in the next build's report. Add if (stepReportData != null) { stepReportData.clear(); } to clearSessionState().

🟡 Low — writeStep() serialization path is completely untested

All 10 DefaultBuildReport constructor calls in BuildReportJsonWriterTest pass List.of() for the steps parameter. The writeStep() method and the conditional "steps" array emission are dead code from the test suite's perspective — a serialization bug in that path would go undetected. At minimum, add a test with a DefaultStepReport with non-empty predecessors to cover the predecessors array serialization.


Still open — threadName for SKIPPED mojos captures event-dispatch thread

🟡 Low — Raised in my previous review. BuildReportCollector.mojoSkipped() captures Thread.currentThread().getName() as the thread name, but no thread executed the mojo (it was skipped). The value is the event-dispatch thread and has no semantic meaning in reports. Consider passing null instead, consistent with how StepReport.threadName() returns null for skipped steps.


Still open — DefaultBuildInvocation.from(Session) Javadoc overstates scope

🟡 Low — Raised three times previously. The method description ("Creates a {@link BuildInvocation} snapshot from the current session state") overstates what is returned: goals, activeProfiles, selectedProjects, excludedProjects, makeBehavior, and resumeFrom all default to empty. Only userProperties, systemInfo, and threads are populated from the session. Still not updated.


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.

Following up on my earlier reviews — all open findings are addressed in this commit.


✅ @since 4.1.0 → @since 4.2.0 on MojoReport.threadName()

Fixed: MojoReport.java line 147.

✅ @since 4.1.0 → @since 4.2.0 on StepReport

Fixed: StepReport.java line 43.

✅ startTime now captures execution start, not scheduling time

Fixed: BuildPlanExecutor.java — step.startTime = MonotonicClock.now() moved inside the executor lambda, after the thread is assigned to the step.

✅ stepReportData cleared in clearSessionState()

Fixed: BuildReportCollector.java — stepReportData.clear() added, preventing stale step data from leaking across sequential builds in mvnd.

✅ threadName for skipped mojos now null

Fixed: BuildReportCollector.mojoSkipped() now passes null instead of Thread.currentThread().getName(), consistent with the StepReport.threadName() contract for skipped entries.

✅ DefaultBuildInvocation.from(Session) Javadoc updated

Fixed: Javadoc now explicitly lists which fields are populated (userProperties, systemInfo, threads) and which are not (goals, activeProfiles, etc.).

✅ writeStep() serialization now covered by tests

Fixed: testStepsSerialization() added in BuildReportJsonWriterTest.java, covering the writeStep() path with two steps (one with an empty predecessor list, one with a non-empty predecessor list).


LGTM. All findings resolved. 🎉

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.

Following up on my earlier review — the previous APPROVE was on 546c3fef.

Three commits have been pushed since then. Two of them are correct follow-up fixes for the DefaultStepReport visibility: making the record public and adding public to its compact constructor are both required by the Java specification when a cross-module caller (here: BuildPlanExecutor in org.apache.maven.core) needs access. The module-info export and the @param Javadoc additions are clean.

One issue in these commits:


🔴 Medium — Unrelated deletion of a deliberately committed test fixture

Commit 09d851bf removes its/core-it-suite/src/test/resources/mng-2871/ejbs/target/classes/test.properties. The comment inside that file explicitly states this is not generated build output but a static fixture that must exist for the MNG-2871 integration test to work:

# NOTE: This build output is a static part of the test and not generated by the actual test run, so apparently
# shouldn't be cleaned.

The file still exists on master — this deletion appears to be accidental (a stray git add or git clean during the DefaultStepReport visibility fix). Removing it will break the MNG-2871 IT on the next run.

Please restore the file:

git checkout master -- its/core-it-suite/src/test/resources/mng-2871/ejbs/target/classes/test.properties

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

Guillaume Nodet and others added 4 commits December 1, 2026 19:31
Introduces a structured build report generated at the end of each Maven
session. The report captures per-mojo timing, status, and log output, as
well as subproject and build-level metadata, and writes an atomic JSON
file to `target/build-reports/`.

## Public API (api/maven-api-core)

- `BuildReport` / `SubprojectReport` / `MojoReport` / `FailureReport`
  — read-only interfaces in `org.apache.maven.api.build.report`
- `BuildInvocation` — captures the CLI invocation context (goals,
  profiles, properties, make-behavior, etc.)
- `BuildStatus` — SUCCESS / FAILURE / SKIPPED enum
- Constants for tuning caps:
  `MAVEN_BUILD_REPORT_MAX_LOG_EVENTS`,
  `MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES`,
  `MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES`

## Implementation (impl/maven-impl)

`BuildReportCollector` implements `ExecutionListener + LogSink + SpiService`
and is auto-discovered via the SPI mechanism (`lookupList(SpiService.class)`).

- Receives enriched `LogEvent` objects via `LogSink.accept()` after the
  `ProjectBuildLogAppender` has already stamped `projectId`/`mojoId`
- Routes events to per-mojo, per-subproject, or build-level ring buffers
  (each capped at a configurable maximum, default 500)
- Tracks timing and build status via typed `ExecutionListener` callbacks
- Writes a timestamped `build-report-${timestamp}.json` plus an atomic
  `build-report-latest.json` symlink; falls back to a plain copy on
  filesystems that don't support symlinks (Windows)
- Thread-safe: concurrent subproject builds with `-T` write to their own
  `ConcurrentHashMap` entries
- mvnd / embedded Maven safe: `sessionEnded()` clears all per-session
  state so the singleton is reusable across builds

## Fan-out wiring (impl/maven-core + impl/maven-cli)

`ProjectBuildLogAppender` gains a `secondarySinks: List<LogSink>` fan-out
list (replacing the former static `reportCapture` hook):

- `setSpiSinks(List<LogSink>)` — called by `LookupInvoker.lookup()` after
  the DI container is initialized, to register all `SpiService` instances
  that implement `LogSink`
- The appender stores the `ProjectBuildLogAppender` instance on
  `LookupContext.projectBuildLogAppender` so `lookup()` can reach it

## JSON output format

```json
{
  "reportVersion": "1.0",
  "invocation": { "goals": [...], "offline": false, ... },
  "status": "SUCCESS",
  "startTime": "2025-07-29T14:30:00Z",
  "durationMs": 12345,
  "mavenVersion": "4.2.0",
  "javaVersion": "21.0.2",
  "subprojects": [
    {
      "groupId": "org.example", "artifactId": "my-app", ...,
      "mojos": [
        { "goal": "compile", "durationMs": 500, "status": "SUCCESS",
          "output": [ { "level": "INFO", "message": "..." } ] }
      ]
    }
  ],
  "failures": [ { "subproject": "...", "message": "...", "stackTrace": "..." } ]
}
```

## Tests

- `BuildReportCollectorTest` (10 tests) — full lifecycle simulation,
  log-capture routing, cap enforcement, state-clear between builds
- `BuildReportJsonWriterTest` (10 tests) — JSON serialization, truncation,
  edge cases
…ter unregister

BuildReportCollector is now auto-registered as an SpiService listener,
so the list is no longer empty after programmatic listeners are removed.
Check that the specific listener is absent rather than asserting isEmpty().
The aggregate Javadoc site build (mvn site -Preporting) failed on JDK 17
with 24 errors in the new internal build report implementation classes.

Two categories of issues:

1. Cross-module {@link} references in package-private/internal classes
   The aggregate Javadoc for maven-core cannot resolve {@link} references
   to types from maven-api-core (a separate JPMS module) on JDK 17.
   Fix: replace {@link BuildReport}, {@link MojoReport}, etc. with
   {@code BuildReport}, {@code MojoReport} in class-level Javadoc of
   internal implementation classes.
   Affected: BuildReportJsonWriter, DefaultBuildReport, DefaultMojoReport,
   DefaultFailureReport, DefaultSubprojectReport (both maven-core and
   maven-impl copies).

2. @PARAM on record class-level Javadoc
   JDK 17 Javadoc reports 'invalid use of @PARAM' for @PARAM tags on
   record component names in the class-level Javadoc block. This feature
   was added in JDK 18. Fix: remove the @PARAM block from DefaultBuildInvocation
   class-level Javadoc in both maven-core and maven-impl.
gnodet and others added 17 commits December 1, 2026 19:31
…tion record

Previous fix (a2869c5) only added @PARAM tags to the maven-impl copy.
Checkstyle requires @PARAM tags for all record components in the class-level
Javadoc — the maven-core copy was left without them, causing 15 Checkstyle
violations.
Address all 7 findings raised in the gnodet-bot code reviews:

1. Add maven.buildReport.enabled toggle (default: true)
   Gate sessionEnded() and the shutdown hook on this flag so that
   users can suppress the JSON report with -Dmaven.buildReport.enabled=false.

2. Fix needsMetadata() in ProjectBuildLogAppender.Sink to check
   secondary sinks: return needsMetadata || secondarySinks.stream()
   .anyMatch(LogSink::needsMetadata) so that BuildReportCollector
   receiving enriched log events is not accidentally skipped.

3. Fix projectKey() to include the version component (groupId:artifactId:version)
   to avoid collisions in reactors with multi-version projects.

4. Use session.getTopLevelProject() instead of projects.get(0) when
   computing the top-level project GAV for the report metadata.

5. Add maven.buildReport.includePii flag (default: false). When false,
   user.home and user.name are stripped from the systemInfo section of
   the build invocation snapshot, preventing unintended disclosure in
   reports that might be shared externally.

6. Remove META-INF/services/org.apache.maven.api.spi.SpiService entry
   for BuildReportCollector. The @nAmed @singleton DI annotation is the
   correct discovery mechanism for LookupInvoker.lookupList(); the
   services file risked creating a second ServiceLoader instance.

7. Mark package-private test-visible fields with // visible for testing
   comments (session, shutdownHook, reportWritten).
DefaultSession (in maven-core) imports DefaultBuildInvocation from the
org.apache.maven.impl.build package (in maven-impl), but that package
was not exported. This caused a Javadoc failure during full-build:

  error: package org.apache.maven.impl.build is not visible
  import org.apache.maven.impl.build.DefaultBuildInvocation;
  (package org.apache.maven.impl.build is declared in module
   org.apache.maven.impl, which does not export it)

Add the missing qualified export following the same pattern as the
other impl packages exported to org.apache.maven.core.
Add MojoReport.threadName() — the name of the thread that executed the
mojo. With concurrent builds (-T, -bconcurrent), different mojos may
run on different threads, even within the same module. This field
enables:

- Timeline visualizations that assign each mojo to a swim lane
  (like maven-timeline-extension does)
- Critical-path analysis using actual per-mojo execution times
  from previous build reports

The thread name is captured at mojo completion time in
BuildReportCollector and serialized in the JSON report.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add StepReport — per-step timing and predecessor data from the
concurrent builder's execution plan. Each step records its module,
name (e.g. "before:compile", "$setup$"), status, start time,
duration, thread name, and the list of predecessor step IDs.

This data enables:
- Timeline reconstruction with the full scheduling graph
- Critical-path analysis from actual execution times
- Identifying which dependency edges cause idle gaps
- Feeding historical timing back into the scheduler

The step data is collected by BuildPlanExecutor after execution,
converted to StepReport objects, and passed to BuildReportCollector
via StepReportData (a shared singleton). Steps are serialized in
the JSON report under the "steps" array.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix @SInCE 4.1.0 → @SInCE 4.2.0 on MojoReport.threadName() and StepReport (both introduced in 4.2.0)
- Pass null threadName for skipped mojos — no thread executed them, the event-dispatch thread name is meaningless
- Move step.startTime capture inside executor lambda so it records actual execution start, not scheduling time
- Clear stepReportData in clearSessionState() to prevent stale step data leaking across builds in mvnd
- Narrow DefaultBuildInvocation.from(Session) Javadoc to reflect that only userProperties, systemInfo, and threads are populated
- Add testStepsSerialization() to cover the writeStep() path including predecessors array serialization
A public record's canonical constructor must be at least as accessible
as the record itself. The compact constructor was left package-private
after making the record public, causing a compilation error.
)

Rebase on latest master which added startTime/endTime/weight fields
to BuildStep and restructured BuildPlanExecutor. Deduplicate the
fields (the PR also added startTime/endTime), remove redundant
assignments in executeStep(), and pass the new StepReportData
parameter to BuildPlanExecutor constructors in tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@gnodet
gnodet force-pushed the feature/build-report branch from c71fb7a to acc86b3 Compare December 1, 2026 18:40

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

Following up on my earlier review — the previous COMMENT review (c71fb7af) raised one issue.

⚠️ Still open — mng-2871 test fixture not restored

The file its/core-it-suite/src/test/resources/mng-2871/ejbs/target/classes/test.properties is still deleted in this PR. The comment inside the file explicitly states this is a static fixture required for the MNG-2871 integration test:

# NOTE: This build output is a static part of the test and not generated by the actual test run, so apparently
# shouldn't be cleaned.
key = value

This file exists on master and removing it will break the MNG-2871 IT. This appears to be an accidental deletion carried over from earlier commits. Please restore it:

git checkout master -- its/core-it-suite/src/test/resources/mng-2871/ejbs/target/classes/test.properties

✅ Latest commit (acc86b32) — merge conflict resolution with #14193

The deduplication of startTime/endTime fields in BuildStep is correct: the PR had added startTime/endTime/threadName fields while #14193 had already added startTime/endTime/weight. The resolution keeps the single authoritative set, moves startTime capture to the lambda entry (correctly capturing actual execution start, not scheduling time on the scheduler thread), and adds endTime capture on the outer Throwable escape path. Clean.


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

The file its/core-it-suite/src/test/resources/mng-2871/ejbs/target/classes/test.properties
is a static fixture required by the MNG-2871 integration test and was
accidentally removed during earlier commits.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

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

Following up on my earlier review — the previous COMMENT on acc86b32 raised one issue.

✅ mng-2871 test fixture restored

The file its/core-it-suite/src/test/resources/mng-2871/ejbs/target/classes/test.properties has been restored in commit bceeb967. The fix correctly addresses the accidental deletion that was flagged.

All findings are now resolved. LGTM.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants