gnodet-bot commented on code in PR #14077:
URL: https://github.com/apache/maven/pull/14077#discussion_r4744446621


##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/MojoReport.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api.build.report;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Immutable;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.logging.LogEvent;
+
+/**
+ * Report for a single mojo (plugin goal) execution within a subproject.
+ *
+ * @since 4.2.0
+ * @see SubprojectReport#mojos()
+ */
+@Experimental
+@Immutable
+public interface MojoReport {
+
+    /**
+     * The plugin's group ID.
+     *
+     * @return the group ID, never {@code null}
+     */
+    @Nonnull
+    String groupId();
+
+    /**
+     * The plugin's artifact ID.
+     *
+     * @return the artifact ID, never {@code null}
+     */
+    @Nonnull
+    String artifactId();
+
+    /**
+     * The plugin version.
+     *
+     * @return the version string, never {@code null}
+     */
+    @Nonnull
+    String version();
+
+    /**
+     * The goal that was executed (e.g. {@code "compile"}, {@code "test"}).
+     *
+     * @return the goal name, never {@code null}
+     */
+    @Nonnull
+    String goal();
+
+    /**
+     * The execution ID (e.g. {@code "default-compile"}).
+     *
+     * @return the execution ID, or {@code null} if not set
+     */
+    @Nullable
+    String executionId();
+
+    /**
+     * The lifecycle phase this mojo was bound to (e.g. {@code "compile"}, 
{@code "test"}).
+     *
+     * @return the phase name, or {@code null} if invoked directly
+     */
+    @Nullable
+    String phase();
+
+    /**
+     * The outcome of this mojo execution.
+     *
+     * @return the status, never {@code null}
+     */
+    @Nonnull
+    BuildStatus status();
+
+    /**
+     * When this mojo execution started (wall-clock time).
+     *
+     * @return the start instant, never {@code null}
+     */
+    @Nonnull
+    Instant startTime();
+
+    /**
+     * How long this mojo execution took.
+     *
+     * @return the duration, never {@code null}
+     */
+    @Nonnull
+    Duration duration();
+
+    /**
+     * The trace identifier associated with this mojo execution.
+     * <p>
+     * Tracing extensions can provide this value by setting the
+     * {@code otel.trace_id} key in the SLF4J MDC before the mojo starts.
+     *
+     * @return the trace identifier, or {@code null} if no tracing context was 
provided
+     * @since 4.2.0
+     */
+    @Nullable
+    String traceId();
+
+    /**
+     * The span identifier associated with this mojo execution.
+     * <p>
+     * Tracing extensions can provide this value by setting the
+     * {@code otel.span_id} key in the SLF4J MDC before the mojo starts.
+     *
+     * @return the span identifier, or {@code null} if no tracing context was 
provided
+     * @since 4.2.0
+     */
+    @Nullable
+    String spanId();
+
+    /**
+     * The name of the thread that executed this mojo.
+     * <p>
+     * With concurrent builds ({@code -T}, {@code -bconcurrent}), different
+     * mojos — even within the same module — may run on different threads.
+     * This field enables timeline visualizations that assign each mojo to a
+     * lane, and critical-path analysis that uses actual execution times.
+     *
+     * @return the thread name (e.g. {@code "BuilderThread 0"}), or
+     *         {@code null} if not captured
+     * @since 4.1.0

Review Comment:
   ⚠️ **Wrong `@since` version** — every other method and type in this PR uses 
`@since 4.2.0`; this is `4.1.0`. The entire build report API lands in 
4.2.0-SNAPSHOT.
   
   ```suggestion
        * @since 4.2.0
   ```



##########
impl/maven-impl/src/main/java/org/apache/maven/impl/build/BuildReportCollector.java:
##########
@@ -0,0 +1,816 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.impl.build;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.maven.api.BuildInvocation;
+import org.apache.maven.api.Constants;
+import org.apache.maven.api.ExecutionEvent;
+import org.apache.maven.api.ExecutionListener;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.MonotonicClock;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.build.report.BuildReport;
+import org.apache.maven.api.build.report.BuildStatus;
+import org.apache.maven.api.build.report.FailureReport;
+import org.apache.maven.api.build.report.MojoReport;
+import org.apache.maven.api.build.report.SubprojectReport;
+import org.apache.maven.api.di.Named;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.logging.LogEvent;
+import org.apache.maven.api.logging.LogSink;
+import org.apache.maven.api.spi.SpiService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Collects build lifecycle events and produces a structured {@code 
BuildReport}
+ * at the end of the session.
+ * <p>
+ * Implements {@link ExecutionListener} for typed lifecycle callbacks,
+ * {@link LogSink} for receiving log events from {@code 
ProjectBuildLogAppender},
+ * and {@link SpiService} for auto-discovery via the DI container.
+ * <p>
+ * Thread-safe: concurrent subproject builds (with {@code -T}) each write to 
their
+ * own entry in a {@link ConcurrentHashMap}.
+ * <p>
+ * Log capture: receives already-enriched {@link LogEvent} objects from
+ * {@code ProjectBuildLogAppender} via the {@link LogSink#accept(LogEvent)} 
method.
+ * Uses thread-based tracking to associate events with the currently-executing
+ * mojo or subproject.
+ *
+ * @since 4.2.0
+ */
+@Named
+@Singleton
+public final class BuildReportCollector implements ExecutionListener, LogSink, 
SpiService {
+
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(BuildReportCollector.class);
+
+    static final String REPORT_DIR = "build-reports";
+    static final String REPORT_LATEST = "build-report-latest.json";
+    static final String TRACE_ID_MDC_KEY = "otel.trace_id";
+    static final String SPAN_ID_MDC_KEY = "otel.span_id";
+
+    private static final int DEFAULT_MAX_STACKTRACE_LINES = 30;
+
+    // ---- Per-session config (read from system properties at SessionStarted) 
----
+
+    /** Whether report generation is enabled; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_ENABLED}. */
+    private volatile boolean reportEnabled = true;
+
+    /** Whether PII properties are included; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_INCLUDE_PII}. */
+    private volatile boolean includePii = false;
+
+    /** Cap on log events per scope; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_LOG_EVENTS}. */
+    private volatile int maxLogEventsPerScope = 500;
+
+    /** Cap on stack-trace lines per failure; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES}. */
+    private volatile int maxStacktraceLines = DEFAULT_MAX_STACKTRACE_LINES;
+
+    /** Cap on throwable lines per log event; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES}. */
+    private volatile int maxThrowableLines = 
BuildReportJsonWriter.DEFAULT_MAX_THROWABLE_LINES;
+
+    // ---- Mutable state, populated during the build ----
+
+    /** Per-project mojo tracking: project key -> queue of in-flight/completed 
mojos. */
+    private final Map<String, Queue<MojoTiming>> mojoTimings = new 
ConcurrentHashMap<>();
+
+    /** Per-project start instants for duration computation. */
+    private final Map<String, Instant> projectStartTimes = new 
ConcurrentHashMap<>();
+
+    /** Per-project trace context captured when the project starts. */
+    private final Map<String, TraceContext> projectTraceContexts = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo start instants for duration computation. */
+    private final Map<String, Instant> mojoStartTimes = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo trace context captured when the mojo starts. */
+    private final Map<String, TraceContext> mojoTraceContexts = new 
ConcurrentHashMap<>();
+
+    /** Per-project build status tracked from project events. */
+    private final Map<String, BuildStatus> projectStatuses = new 
ConcurrentHashMap<>();
+
+    /** Per-project build duration tracked from start/finish events. */
+    private final Map<String, Duration> projectDurations = new 
ConcurrentHashMap<>();
+
+    /** Per-project failure causes. */
+    private final Map<String, Throwable> projectFailures = new 
ConcurrentHashMap<>();
+
+    /** Session-level state - set once on SessionStarted. */
+    // visible for testing
+    volatile Session session;
+
+    /** Build invocation - captured once at SessionStarted, immutable 
thereafter. */
+    private volatile BuildInvocation buildInvocation;
+
+    /** Session start time. */
+    private volatile Instant sessionStartTime;
+
+    /** 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();
+
+    // ---- Log capture state ----
+
+    /**
+     * Maps thread ID -> mojo key for the currently-executing mojo on that 
thread.
+     * Lifecycle events and mojo execution run on the same thread, so this is 
safe
+     * for parallel builds with {@code -T}.
+     */
+    private final Map<Long, String> currentMojoByThread = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo log buffers: mojo key -> captured log events. */
+    private final Map<String, BlockingQueue<LogEvent>> mojoLogBuffers = new 
ConcurrentHashMap<>();
+
+    /**
+     * Maps thread ID -> project key for the currently-building project on 
that thread.
+     * Used to route log events that occur between mojo executions to the 
subproject-level buffer.
+     */
+    private final Map<Long, String> currentProjectByThread = new 
ConcurrentHashMap<>();
+
+    /** Per-subproject log buffers: project key -> events captured outside any 
mojo. */
+    private final Map<String, BlockingQueue<LogEvent>> subprojectLogBuffers = 
new ConcurrentHashMap<>();
+
+    /** Build-level log buffer: events captured outside any subproject 
lifecycle. Created at session start. */
+    private volatile BlockingQueue<LogEvent> buildLogBuffer = new 
ArrayBlockingQueue<>(500);
+
+    // ---- LogSink implementation ----
+
+    /**
+     * Receives pre-formed {@link LogEvent} objects from {@code 
ProjectBuildLogAppender}.
+     * Routes to the appropriate buffer (mojo, subproject, or build-level) 
based on
+     * the current thread's lifecycle context.
+     * <p>
+     * No-op when no session is active.
+     */
+    @Override
+    public void accept(LogEvent event) {
+        // No-op when no session is active
+        if (session == null) {
+            return;
+        }
+        long threadId = Thread.currentThread().getId();
+        // 1. Mojo-level
+        String mKey = currentMojoByThread.get(threadId);
+        if (mKey != null) {
+            BlockingQueue<LogEvent> buffer = mojoLogBuffers.get(mKey);
+            if (buffer != null) {
+                buffer.offer(event);
+            }
+            return;
+        }
+        // 2. Module-level
+        String pKey = currentProjectByThread.get(threadId);
+        if (pKey != null) {
+            BlockingQueue<LogEvent> buffer = subprojectLogBuffers.get(pKey);
+            if (buffer != null) {
+                buffer.offer(event);
+            }
+            return;
+        }
+        // 3. Build-level
+        buildLogBuffer.offer(event);
+    }
+
+    // ---- ExecutionListener typed callbacks ----
+
+    @Override
+    public void sessionStarted(ExecutionEvent event) {
+        this.session = event.session();
+        this.sessionStartTime = MonotonicClock.now();
+        // Read configurable caps from session properties (or fall back to 
defaults)
+        this.reportEnabled = readBooleanProperty(session, 
Constants.MAVEN_BUILD_REPORT_ENABLED, true);
+        this.includePii = readBooleanProperty(session, 
Constants.MAVEN_BUILD_REPORT_INCLUDE_PII, false);
+        this.maxLogEventsPerScope = readIntProperty(session, 
Constants.MAVEN_BUILD_REPORT_MAX_LOG_EVENTS, 500);
+        this.maxStacktraceLines = readIntProperty(
+                session, Constants.MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES, 
DEFAULT_MAX_STACKTRACE_LINES);
+        this.maxThrowableLines = readIntProperty(
+                session,
+                Constants.MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES,
+                BuildReportJsonWriter.DEFAULT_MAX_THROWABLE_LINES);
+        this.buildLogBuffer = new 
ArrayBlockingQueue<>(this.maxLogEventsPerScope);
+        this.buildInvocation = session.buildInvocation();
+        if (this.buildInvocation == null) {
+            this.buildInvocation = DefaultBuildInvocation.from(session);
+        }
+        if (!includePii && this.buildInvocation instanceof 
DefaultBuildInvocation inv) {
+            // Strip potentially sensitive system properties from the report 
unless opted in.
+            // Note: this guard only applies when session.buildInvocation() 
returns a
+            // DefaultBuildInvocation (the standard runtime). Embedders that 
supply a custom
+            // BuildInvocation implementation are responsible for filtering 
PII themselves.
+            Map<String, String> filtered = new 
java.util.TreeMap<>(inv.systemInfo());
+            filtered.remove("user.home");
+            filtered.remove("user.name");
+            this.buildInvocation = new DefaultBuildInvocation(
+                    inv.goals(),
+                    inv.userProperties(),
+                    java.util.Collections.unmodifiableMap(filtered),
+                    inv.activeProfiles(),
+                    inv.selectedProjects(),
+                    inv.excludedProjects(),
+                    inv.makeBehavior(),
+                    inv.resumeFrom(),
+                    inv.reactorFailureBehavior(),
+                    inv.offline(),
+                    inv.updateSnapshots(),
+                    inv.batchMode(),
+                    inv.recursive(),
+                    inv.resume(),
+                    inv.threads());
+        }
+        // Remove any leftover hook from a previous build (mvnd / embedded 
Maven reuse).
+        // Must be done before resetting reportWritten to prevent the old hook 
from firing
+        // against the new session's state.
+        removeShutdownHook();
+        this.reportWritten.set(false);
+
+        if (!reportEnabled) {
+            return;
+        }
+
+        Thread hook = new Thread(
+                () -> {
+                    Session activeSession = this.session;
+                    if (activeSession == null || 
!reportWritten.compareAndSet(false, true)) {
+                        return;
+                    }
+                    try {
+                        LOGGER.debug("JVM shutting down: writing partial build 
report");
+                        // hasFailure=true: an interrupted build is always a 
failure.
+                        BuildReport report = buildReport(activeSession, true);
+                        writeReport(report, activeSession);
+                    } catch (Exception e) {
+                        LOGGER.warn("Failed to write partial build report 
during shutdown", e);
+                    }
+                },
+                "maven-build-report-shutdown-hook");
+
+        try {
+            Runtime.getRuntime().addShutdownHook(hook);
+            this.shutdownHook = hook;
+        } catch (IllegalStateException e) {
+            LOGGER.debug("JVM shutdown already in progress", e);
+        }
+    }
+
+    @Override
+    public void sessionEnded(ExecutionEvent event) {
+        removeShutdownHook();
+
+        Session endSession = event.session();
+        if (!reportEnabled || endSession == null || 
!reportWritten.compareAndSet(false, true)) {
+            clearSessionState();
+            return;
+        }
+
+        try {
+            boolean hasFailure = event.exception().isPresent();
+            BuildReport report = buildReport(endSession, hasFailure);
+            writeReport(report, endSession);
+        } catch (Exception e) {
+            // Never let the report collector crash the build
+            LOGGER.debug("Failed to produce build report: {}", e.getMessage(), 
e);
+        } finally {
+            clearSessionState();
+        }
+    }
+
+    @Override
+    public void projectStarted(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            projectStartTimes.put(key, MonotonicClock.now());
+            projectTraceContexts.put(key, currentTraceContext());
+            mojoTimings.putIfAbsent(key, new ConcurrentLinkedQueue<>());
+            subprojectLogBuffers.put(key, new 
ArrayBlockingQueue<>(maxLogEventsPerScope));
+            currentProjectByThread.put(Thread.currentThread().getId(), key);
+        });
+    }
+
+    @Override
+    public void projectSucceeded(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            Instant start = projectStartTimes.get(key);
+            Instant now = MonotonicClock.now();
+            projectStatuses.put(key, BuildStatus.SUCCESS);
+            if (start != null) {
+                projectDurations.put(key, Duration.between(start, now));
+            }
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void projectFailed(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            Instant start = projectStartTimes.get(key);
+            Instant now = MonotonicClock.now();
+            projectStatuses.put(key, BuildStatus.FAILURE);
+            if (start != null) {
+                projectDurations.put(key, Duration.between(start, now));
+            }
+            event.exception().ifPresent(ex -> projectFailures.put(key, ex));
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void projectSkipped(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            projectStatuses.put(key, BuildStatus.SKIPPED);
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void mojoStarted(ExecutionEvent event) {
+        event.project()
+                .ifPresent(project -> event.mojoExecution().ifPresent(mojo -> {
+                    String mKey = mojoKey(project, mojo);
+                    mojoStartTimes.put(mKey, MonotonicClock.now());
+                    mojoTraceContexts.put(mKey, currentTraceContext());
+
+                    currentMojoByThread.put(Thread.currentThread().getId(), 
mKey);
+                    mojoLogBuffers.put(mKey, new 
ArrayBlockingQueue<>(maxLogEventsPerScope));
+                }));
+    }
+
+    @Override
+    public void mojoSucceeded(ExecutionEvent event) {
+        onMojoFinished(event, BuildStatus.SUCCESS);
+    }
+
+    @Override
+    public void mojoFailed(ExecutionEvent event) {
+        onMojoFinished(event, BuildStatus.FAILURE);
+    }
+
+    @Override
+    public void mojoSkipped(ExecutionEvent event) {
+        event.project()
+                .ifPresent(project -> event.mojoExecution().ifPresent(mojo -> {
+                    String pKey = projectKey(project);
+                    Instant now = MonotonicClock.now();
+                    TraceContext traceContext = TraceContext.EMPTY;
+
+                    MojoTiming timing = new MojoTiming(
+                            mojo.plugin().getModel().groupId(),
+                            mojo.plugin().getModel().artifactId(),
+                            mojo.plugin().getModel().version(),
+                            mojo.goal(),
+                            mojo.executionId().orElse(null),
+                            mojo.lifecyclePhase().orElse(null),
+                            BuildStatus.SKIPPED,
+                            now,
+                            Duration.ZERO,
+                            traceContext.traceId,
+                            traceContext.spanId,
+                            Thread.currentThread().getName(),

Review Comment:
   💡 **Nit:** `Thread.currentThread()` here captures the event-dispatch thread, 
not an "execution thread" for the mojo (there is none — it was skipped). The 
API contract says `threadName()` is "the name of the thread that **executed** 
this mojo", which is misleading for `SKIPPED` entries.
   
   Consider returning `null` for skipped mojos:
   ```suggestion
                               null,
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to