gnodet-bot commented on code in PR #14214:
URL: https://github.com/apache/maven/pull/14214#discussion_r4756169507
##########
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlan.java:
##########
@@ -235,4 +236,31 @@ private static void visitNode(BuildStep node,
Set<BuildStep> visited, List<Build
sortedNodes.add(node);
}
}
+
+ /**
+ * Computes critical-path weights for all steps in the plan. When {@code
previousTimings}
+ * is non-empty, uses actual durations (in millis) from a previous build
as step weights;
+ * steps not found in the map fall back to 1. When empty, uses graph depth
(each step = 1).
+ */
+ void computeWeights(Map<String, Long> previousTimings) {
+ List<BuildStep> sorted = sortedNodes();
+ for (int i = sorted.size() - 1; i >= 0; i--) {
+ BuildStep step = sorted.get(i);
+ long maxSuccessorWeight = 0;
+ for (BuildStep successor : step.successors) {
+ maxSuccessorWeight = Math.max(maxSuccessorWeight,
successor.weight);
+ }
+ long selfWeight;
+ if (previousTimings.isEmpty()) {
+ selfWeight = 1;
+ } else {
+ Long millis = previousTimings.get(step.stepId());
+ selfWeight = millis != null ? Math.max(1L, millis) : 1;
+ }
+ step.weight = selfWeight + maxSuccessorWeight;
+ }
+ // Pre-sort by descending weight so executePlan() picks the
heaviest-path steps first
+ // without re-sorting on every scheduler tick.
+ sorted.sort(Comparator.comparingLong((BuildStep s) ->
s.weight).reversed());
Review Comment:
⚠️ **Mutates the shared `sortedNodes` cache.** `sortedNodes()` returns the
internal `this.sortedNodes` reference without a defensive copy. This `sort()`
permanently replaces topological ordering with weight ordering in the cached
field — which is the scheduling goal, but the state change is implicit. A
second call to `computeWeights()` would iterate in reverse over weight-sorted
(not topological) order and produce incorrect weights. Consider storing the
weight-sorted result in a separate field (`weightSortedNodes`) so
`sortedNodes()` retains its original topological contract.
##########
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/StepTimings.java:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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.lifecycle.internal.concurrent;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Reads and writes step timing data for critical-path scheduling.
+ * Each line contains a step ID and its duration in milliseconds, separated by
a tab.
+ */
+class StepTimings {
+
+ private static final Logger LOGGER =
LoggerFactory.getLogger(StepTimings.class);
+
+ static final String TIMINGS_FILE = ".mvn/target/step-timings.txt";
+
+ static Map<String, Long> read(Path rootDirectory) {
+ Path file = rootDirectory.resolve(TIMINGS_FILE);
+ if (!Files.isRegularFile(file)) {
+ return Map.of();
+ }
+ Map<String, Long> timings = new LinkedHashMap<>();
+ try (BufferedReader reader = Files.newBufferedReader(file,
StandardCharsets.UTF_8)) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ line = line.strip();
+ if (line.isEmpty() || line.startsWith("#")) {
+ continue;
+ }
+ int sep = line.indexOf('\t');
+ if (sep > 0) {
+ String stepId = line.substring(0, sep);
+ try {
+ long millis = Long.parseLong(line.substring(sep +
1).strip());
+ timings.put(stepId, millis);
+ } catch (NumberFormatException e) {
+ // skip malformed lines
+ }
+ }
+ }
+ LOGGER.debug("Loaded {} step timings from {}", timings.size(),
file);
+ } catch (IOException e) {
+ LOGGER.debug("Could not read step timings from {}: {}", file,
e.getMessage());
+ }
+ return timings;
+ }
+
+ static void write(Path rootDirectory, BuildPlan plan) {
+ if (rootDirectory == null) {
+ return;
+ }
+ Path file = rootDirectory.resolve(TIMINGS_FILE);
+ try {
+ Files.createDirectories(file.getParent());
+ Path tmp = Files.createTempFile(file.getParent(),
".step-timings-", ".tmp");
+ try {
+ try (BufferedWriter writer = Files.newBufferedWriter(tmp,
StandardCharsets.UTF_8)) {
+ plan.allSteps()
+ .filter(step -> step.startTime != null
+ && step.endTime != null
+ && step.status.get() == BuildStep.EXECUTED)
+ .forEach(step -> {
+ long millis = Duration.between(step.startTime,
step.endTime)
+ .toMillis();
+ try {
+ writer.write(step.stepId());
+ writer.write('\t');
+ writer.write(Long.toString(millis));
+ writer.newLine();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ }
+ Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING);
+ } catch (IOException | RuntimeException e) {
+ Files.deleteIfExists(tmp);
+ throw e;
+ }
+ LOGGER.debug("Wrote step timings to {}", file);
+ } catch (IOException | RuntimeException e) {
+ LOGGER.warn("Could not write step timings to {}: {}", file,
e.getMessage());
Review Comment:
🔍 **Low:** `e.getMessage()` here will print `"java.io.IOException: <actual
message>"` when `e` is the `RuntimeException` wrapper thrown from the lambda
(wrapping the real `IOException`). The inner `catch` re-throws after deleting
the temp file, so this outer catch receives a `RuntimeException`. Consider
`Throwable cause = e instanceof RuntimeException re && re.getCause() != null ?
re.getCause() : e; LOGGER.warn(..., cause.getMessage())` to surface the actual
IO error cleanly.
--
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]