Skip to content

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

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

gnodet wants to merge 4 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 from d683d7a to f70ca37 Compare November 19, 2026 12:02
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
@gnodet
gnodet force-pushed the feature/build-report branch 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.

…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().

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

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.

2 participants