You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2026/09/29 18:28:22 UTC

(pulsar) branch lh-improve-perf-bottleneck-tooling created (now ea548ef9b0ce)

This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a change to branch lh-improve-perf-bottleneck-tooling
in repository https://gitbox.apache.org/repos/asf/pulsar.git


      at ea548ef9b0ce [improve][test] Record lessons of the first bottleneck elimination iterations in the agent guide

This branch includes the following new commits:

     new a85c3f8463ad [improve][test] Document the bottleneck elimination strategy and per-thread CPU analysis
     new 401c05a9e3ca [improve][test] Sample the host's CPU utilization and disk throughput during performance runs
     new 427207f87baa [improve][test] Give the performance scenarios' bookies BookKeeper's default cache sizes
     new ea548ef9b0ce [improve][test] Record lessons of the first bottleneck elimination iterations in the agent guide

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(pulsar) 03/04: [improve][test] Give the performance scenarios' bookies BookKeeper's default cache sizes

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch lh-improve-perf-bottleneck-tooling
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 427207f87baa9e624a509f3ff05a04824fb1f508
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Tue Sep 29 17:34:12 2026 +0300

    [improve][test] Give the performance scenarios' bookies BookKeeper's default cache sizes
    
    The test image's run-bookie.sh sets dbStorage_writeCacheMaxSizeMb and dbStorage_readAheadCacheMaxSizeMb to 16 MB
    unless they are set. With a 16 MB write cache, a bookie taking large entries flushes it about 17 times per second
    and throttles adds while it does (bookie_throttled_write): at 128 KB unbatched entries the max-rate scenario reached
    2.1k msg/s, and 3.5k msg/s with 256 MB. Set both caches to a quarter of the bookies' direct memory, BookKeeper's
    default, in the cluster memory configurations.
    
    Assisted-by: Claude Code (claude-opus-5-5)
---
 tests/performance/scenarios/configs/cluster-high-mem.yaml   | 4 ++++
 tests/performance/scenarios/configs/cluster-low-mem.yaml    | 4 ++++
 tests/performance/scenarios/configs/cluster-medium-mem.yaml | 4 ++++
 3 files changed, 12 insertions(+)

diff --git a/tests/performance/scenarios/configs/cluster-high-mem.yaml b/tests/performance/scenarios/configs/cluster-high-mem.yaml
index a13539cbf335..4b847f8c88d8 100644
--- a/tests/performance/scenarios/configs/cluster-high-mem.yaml
+++ b/tests/performance/scenarios/configs/cluster-high-mem.yaml
@@ -26,3 +26,7 @@ cluster:
   bookies:
     env:
       PULSAR_MEM: -Xms1g -Xmx1g -XX:MaxDirectMemorySize=1g -XX:+UseTransparentHugePages -XX:+AlwaysPreTouch
+      # The test image's run-bookie.sh sets both DbLedgerStorage caches to 16 MB unless they are set, which throttles
+      # adds of large entries during its flushes; use BookKeeper's defaults, a quarter of the direct memory each.
+      dbStorage_writeCacheMaxSizeMb: "256"
+      dbStorage_readAheadCacheMaxSizeMb: "256"
diff --git a/tests/performance/scenarios/configs/cluster-low-mem.yaml b/tests/performance/scenarios/configs/cluster-low-mem.yaml
index 18575949f00a..cdccbb4674f7 100644
--- a/tests/performance/scenarios/configs/cluster-low-mem.yaml
+++ b/tests/performance/scenarios/configs/cluster-low-mem.yaml
@@ -31,3 +31,7 @@ cluster:
     replicas: 1
     env:
       PULSAR_MEM: -Xmx512m -XX:MaxDirectMemorySize=512m
+      # The test image's run-bookie.sh sets both DbLedgerStorage caches to 16 MB unless they are set, which throttles
+      # adds of large entries during its flushes; use BookKeeper's defaults, a quarter of the direct memory each.
+      dbStorage_writeCacheMaxSizeMb: "128"
+      dbStorage_readAheadCacheMaxSizeMb: "128"
diff --git a/tests/performance/scenarios/configs/cluster-medium-mem.yaml b/tests/performance/scenarios/configs/cluster-medium-mem.yaml
index f5bb8918a3bf..e3050e77f290 100644
--- a/tests/performance/scenarios/configs/cluster-medium-mem.yaml
+++ b/tests/performance/scenarios/configs/cluster-medium-mem.yaml
@@ -30,3 +30,7 @@ cluster:
     replicas: 2
     env:
       PULSAR_MEM: -Xms512m -Xmx512m -XX:MaxDirectMemorySize=512m -XX:+UseTransparentHugePages -XX:+AlwaysPreTouch
+      # The test image's run-bookie.sh sets both DbLedgerStorage caches to 16 MB unless they are set, which throttles
+      # adds of large entries during its flushes; use BookKeeper's defaults, a quarter of the direct memory each.
+      dbStorage_writeCacheMaxSizeMb: "128"
+      dbStorage_readAheadCacheMaxSizeMb: "128"


(pulsar) 02/04: [improve][test] Sample the host's CPU utilization and disk throughput during performance runs

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch lh-improve-perf-bottleneck-tooling
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 401c05a9e3caa2f0dbcfbd10ca4724c804b405b1
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Tue Sep 29 17:14:10 2026 +0300

    [improve][test] Sample the host's CPU utilization and disk throughput during performance runs
    
    Write host-io.csv next to host-stats.csv: once per second, the busy and I/O-wait share of all CPUs from /proc/stat,
    and each physical disk's read and write MB/s and busy share from /proc/diskstats. All the containers of a run share
    the host, so this shows whether a run is limited by the host's CPUs or by its storage, which the bookies share and
    which their own metrics can't show.
    
    Assisted-by: Claude Code (claude-opus-5-5)
---
 tests/performance/AGENTS.md                        |   1 +
 tests/performance/docs/run-reports.md              |   4 +-
 .../tests/performance/launcher/HostIoSampler.java  | 206 +++++++++++++++++++++
 .../performance/launcher/PerformanceLauncher.java  |  19 ++
 .../performance/launcher/HostIoSamplerTest.java    |  97 ++++++++++
 5 files changed, 326 insertions(+), 1 deletion(-)

diff --git a/tests/performance/AGENTS.md b/tests/performance/AGENTS.md
index f6369835cca0..3f2f59cd47c2 100644
--- a/tests/performance/AGENTS.md
+++ b/tests/performance/AGENTS.md
@@ -230,6 +230,7 @@ commit segment can be absent). Use the exact recording names linked from the pro
 | `gateways/gateways-latency.hdr`, `applications/<application>/application-latency.hdr` | The latency interval logs | `renderHdrHistograms`, HistogramLogAnalyzer |
 | `topic-stats.csv` | The broker's topic stats, sampled once per second: backlog and message counters per subscription | DuckDB, or any CSV reader |
 | `host-stats.csv` | The host's CPU temperature, frequency and throttle counters, sampled once per second; on Linux only | DuckDB, or any CSV reader |
+| `host-io.csv` | The host's CPU busy and I/O-wait share and each disk's read/write MB/s and busy share, sampled once per second; on Linux only. CPUs near 100 % busy delay every thread; a disk near 100 % busy limits the bookies | DuckDB, or any CSV reader |
 | `throughput.svg`, `backlog.svg`, `latency-percentiles.svg`, `latency-timeline.svg`, `host-temperature.svg`, `host-frequency.svg` | The report's charts, each with a PNG beside it | View the PNG |
 | `metrics.json` | What querying the run's metrics needs: its label selector, time range, jobs and instances, and the URLs and credentials of VictoriaMetrics and Grafana, see [metrics.json](docs/metrics.md#metricsjson) | `jq`, then VictoriaMetrics' Prometheus API |
 | `grafana-panels/*.png` | Panels of Grafana's dashboards over the run | View |
diff --git a/tests/performance/docs/run-reports.md b/tests/performance/docs/run-reports.md
index 4f9da6c04b55..b684e8d035ab 100644
--- a/tests/performance/docs/run-reports.md
+++ b/tests/performance/docs/run-reports.md
@@ -90,7 +90,7 @@ The run directory that the launcher printed at the start still has what the run
 - `applications/<application>/application-summary.json`, with the application's unique messages, duplicates, ordering
   violations and invalid messages, and `applications/<application>/ordering-violations.txt`, with samples of the
   ordering violations, when the application got as far as its checks
-- `topic-stats.csv` and `host-stats.csv`, sampled until the failure
+- `topic-stats.csv`, `host-stats.csv` and `host-io.csv`, sampled until the failure
 
 The applications' container exits with an error when an application found ordering violations or invalid messages, or
 didn't receive every message, and the launcher fails a run when an application's state shows that it missed messages
@@ -106,6 +106,7 @@ didn't receive every message, and the launcher fails a run when an application's
 ├── throughput.svg, backlog.svg, latency-percentiles.svg, latency-timeline.svg,
 │   host-temperature.svg, host-frequency.svg    the charts, each also as PNG
 ├── topic-stats.csv, host-stats.csv    the sampled topic stats and host CPU
+├── host-io.csv                        the sampled host CPU utilization and disk throughput
 ├── gateways/                          the gateways' outputs, and their recordings in a profiled run
 ├── applications/                      the applications' container log, and their recordings in a profiled run
 │   └── <application>/                 one directory per application, named after its subscription,
@@ -181,6 +182,7 @@ beside it, rendered with [commonmark-java](https://github.com/commonmark/commonm
 | `host-temperature.svg`, `.png`, `host-frequency.svg`, `.png` | The CPU package and hottest core temperature, and the mean and lowest core frequency, over the run |
 | `topic-stats.csv` | The broker's topic stats sampled once per second: backlog and message counters per subscription |
 | `host-stats.csv` | The host's CPU sampled once per second from Linux's sysfs files: package and hottest core temperature, mean and lowest core frequency, the kernel's thermal throttle counters and the fastest fan |
+| `host-io.csv` | The host's CPU utilization and disk throughput sampled once per second from Linux's `/proc/stat` and `/proc/diskstats`: the busy and I/O-wait share of all CPUs, and each physical disk's read and write MB/s and busy share. It shows whether a run is limited by the host's CPUs or its storage, which the bookies share |
 | `gateways/gateways-summary.json` | The gateways' counts and throughput, and the epoch-millisecond boundaries of the measurement |
 | `gateways/gateways-latency.hdr`, `.hgrm` | The publish latency log, and its percentile distribution in milliseconds, see [Latency logs](#latency-logs) |
 | `gateways/gateways-state.bin` | The gateways' next sequence number for each device. The launcher compares it with each application's `application-state.bin` and fails the run when they differ, which catches messages missing at the end, where no gap shows |
diff --git a/tests/performance/launcher/src/main/java/org/apache/pulsar/tests/performance/launcher/HostIoSampler.java b/tests/performance/launcher/src/main/java/org/apache/pulsar/tests/performance/launcher/HostIoSampler.java
new file mode 100644
index 000000000000..91b6ca0fc892
--- /dev/null
+++ b/tests/performance/launcher/src/main/java/org/apache/pulsar/tests/performance/launcher/HostIoSampler.java
@@ -0,0 +1,206 @@
+/*
+ * 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.pulsar.tests.performance.launcher;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+/**
+ * Samples the host's CPU utilization and its disks' throughput once per second into {@code host-io.csv}: the share of
+ * CPU time that is busy and that waits for I/O, and each physical disk's read and write megabytes per second and busy
+ * share. All the containers of a run share the host, so these show whether a run is limited by the host's CPUs or by
+ * its storage, which the containers' own metrics can't show when the bookies share one disk.
+ *
+ * <p>The values are deltas of Linux's cumulative counters in {@code /proc/stat} and {@code /proc/diskstats} between
+ * samples. The disks are the block devices under {@code /sys/block} that have a {@code device} link, so partitions,
+ * device-mapper volumes, loop and RAM devices are left out. A host without these files, such as one that isn't Linux,
+ * is not sampled.
+ */
+final class HostIoSampler implements AutoCloseable {
+    static final String FILE_NAME = "host-io.csv";
+    private static final long INTERVAL_MILLIS = 1000;
+    private static final int SECTOR_BYTES = 512;
+
+    /** One reading of the cumulative counters. */
+    record Counters(long epochMillis, long cpuTotal, long cpuIdle, long cpuIowait, Map<String, long[]> disks) {
+    }
+
+    private final Path procfs;
+    private final List<String> disks;
+    private final BufferedWriter writer;
+    private final ScheduledExecutorService executor;
+    private Counters previous;
+
+    private HostIoSampler(Path procfs, List<String> disks, BufferedWriter writer) {
+        this.procfs = procfs;
+        this.disks = disks;
+        this.writer = writer;
+        this.executor = Executors.newSingleThreadScheduledExecutor(runnable -> {
+            Thread thread = new Thread(runnable, "host-io-sampler");
+            thread.setDaemon(true);
+            return thread;
+        });
+    }
+
+    /** Starts sampling into {@code runDirectory}, or returns {@code null} when the host has no such counters. */
+    static HostIoSampler start(Path procfs, Path sysfs, Path runDirectory) throws IOException {
+        List<String> disks = physicalDisks(sysfs);
+        if (read(procfs.resolve("stat"), System.currentTimeMillis(), disks) == null) {
+            return null;
+        }
+        BufferedWriter writer = Files.newBufferedWriter(runDirectory.resolve(FILE_NAME));
+        writer.write(header(disks));
+        writer.newLine();
+        HostIoSampler sampler = new HostIoSampler(procfs, disks, writer);
+        sampler.executor.scheduleAtFixedRate(sampler::sample, 0, INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
+        return sampler;
+    }
+
+    static String header(List<String> disks) {
+        StringBuilder header = new StringBuilder("epochMs,cpuBusyPercent,cpuIowaitPercent");
+        for (String disk : disks) {
+            header.append(',').append(disk).append("ReadMBps,").append(disk).append("WriteMBps,")
+                    .append(disk).append("BusyPercent");
+        }
+        return header.toString();
+    }
+
+    /** The block devices that are disks: those with a {@code device} link under {@code /sys/block}. */
+    static List<String> physicalDisks(Path sysfs) {
+        Path block = sysfs.resolve("block");
+        if (!Files.isDirectory(block)) {
+            return List.of();
+        }
+        try (Stream<Path> entries = Files.list(block)) {
+            return entries.filter(entry -> Files.exists(entry.resolve("device")))
+                    .map(entry -> entry.getFileName().toString()).sorted().toList();
+        } catch (IOException e) {
+            return List.of();
+        }
+    }
+
+    /** Reads the counters, or returns {@code null} when {@code /proc/stat} is missing. */
+    Counters read(long epochMillis) {
+        return read(procfs.resolve("stat"), epochMillis, disks);
+    }
+
+    private static Counters read(Path stat, long epochMillis, List<String> disks) {
+        List<String> statLines = lines(stat);
+        String cpu = statLines.stream().filter(line -> line.startsWith("cpu ")).findFirst().orElse(null);
+        if (cpu == null) {
+            return null;
+        }
+        String[] fields = cpu.trim().split("\\s+");
+        long total = 0;
+        // user nice system idle iowait irq softirq steal; guest time is already included in user and nice
+        for (int i = 1; i <= Math.min(8, fields.length - 1); i++) {
+            total += Long.parseLong(fields[i]);
+        }
+        long idle = fields.length > 4 ? Long.parseLong(fields[4]) : 0;
+        long iowait = fields.length > 5 ? Long.parseLong(fields[5]) : 0;
+        Map<String, long[]> diskCounters = new LinkedHashMap<>();
+        for (String line : lines(stat.resolveSibling("diskstats"))) {
+            String[] d = line.trim().split("\\s+");
+            // major minor name reads merged sectorsRead msRead writes merged sectorsWritten msWrite inFlight msIo ...
+            if (d.length >= 13 && disks.contains(d[2])) {
+                diskCounters.put(d[2], new long[] {Long.parseLong(d[5]), Long.parseLong(d[9]),
+                        Long.parseLong(d[12])});
+            }
+        }
+        return new Counters(epochMillis, total, idle, iowait, diskCounters);
+    }
+
+    /** One CSV row from two readings, or {@code null} for the first reading. */
+    static String row(Counters previous, Counters current, List<String> disks) {
+        if (previous == null) {
+            return null;
+        }
+        double seconds = Math.max(1, current.epochMillis() - previous.epochMillis()) / 1000.0;
+        long total = Math.max(1, current.cpuTotal() - previous.cpuTotal());
+        long idle = current.cpuIdle() - previous.cpuIdle();
+        long iowait = current.cpuIowait() - previous.cpuIowait();
+        StringBuilder row = new StringBuilder().append(current.epochMillis()).append(',')
+                .append(percent(total - idle - iowait, total)).append(',').append(percent(iowait, total));
+        for (String disk : disks) {
+            long[] before = previous.disks().get(disk);
+            long[] after = current.disks().get(disk);
+            if (before == null || after == null) {
+                row.append(",,,");
+                continue;
+            }
+            row.append(',').append(megabytes(after[0] - before[0], seconds))
+                    .append(',').append(megabytes(after[1] - before[1], seconds))
+                    .append(',').append(percent(after[2] - before[2], (long) (seconds * 1000)));
+        }
+        return row.toString();
+    }
+
+    private void sample() {
+        try {
+            Counters current = read(System.currentTimeMillis());
+            String row = row(previous, current, disks);
+            previous = current;
+            if (row != null) {
+                writer.write(row);
+                writer.newLine();
+                writer.flush();
+            }
+        } catch (IOException | RuntimeException e) {
+            System.out.println("Host I/O sample failed: " + e);
+        }
+    }
+
+    @Override
+    public void close() throws IOException {
+        executor.shutdownNow();
+        try {
+            executor.awaitTermination(10, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+        }
+        writer.close();
+    }
+
+    private static String percent(long part, long whole) {
+        return String.format(Locale.ROOT, "%.1f", Math.min(100.0, Math.max(0.0, 100.0 * part / Math.max(1, whole))));
+    }
+
+    private static String megabytes(long sectors, double seconds) {
+        return String.format(Locale.ROOT, "%.1f", sectors * (double) SECTOR_BYTES / 1_000_000 / seconds);
+    }
+
+    private static List<String> lines(Path file) {
+        try {
+            return Files.readAllLines(file);
+        } catch (IOException e) {
+            return new ArrayList<>();
+        }
+    }
+}
diff --git a/tests/performance/launcher/src/main/java/org/apache/pulsar/tests/performance/launcher/PerformanceLauncher.java b/tests/performance/launcher/src/main/java/org/apache/pulsar/tests/performance/launcher/PerformanceLauncher.java
index e207d621addd..1792e2198e72 100644
--- a/tests/performance/launcher/src/main/java/org/apache/pulsar/tests/performance/launcher/PerformanceLauncher.java
+++ b/tests/performance/launcher/src/main/java/org/apache/pulsar/tests/performance/launcher/PerformanceLauncher.java
@@ -358,6 +358,7 @@ public class PerformanceLauncher implements Callable<Integer> {
         TopicStatsSampler topicStatsSampler = null;
         ProgressMonitor progress = null;
         HostStatsSampler hostStatsSampler = startHostStatsSampler(sensors, runOutput);
+        HostIoSampler hostIoSampler = startHostIoSampler(runOutput);
         HeapDumper heapDumper = heapDumpSettings.any()
                 ? new HeapDumper(runOutput, PulsarContainer.DEFAULT_IMAGE_NAME, heapDumpSettings.gzipLevel()) : null;
         MetricsCollection metricsCollection = null;
@@ -496,6 +497,11 @@ public class PerformanceLauncher implements Callable<Integer> {
                     hostStatsSampler.close();
                 }
             });
+            shutDown("closing the host I/O sampler", () -> {
+                if (hostIoSampler != null) {
+                    hostIoSampler.close();
+                }
+            });
             if (gateToStop != null) {
                 gateToStop.interrupt();
             }
@@ -802,6 +808,19 @@ public class PerformanceLauncher implements Callable<Integer> {
         }
     }
 
+    /**
+     * Starts sampling the host's CPU utilization and disk throughput into {@code host-io.csv}. Sampling is an
+     * observation, so a failure to start it is reported and the run goes on without it.
+     */
+    private HostIoSampler startHostIoSampler(Path runOutput) {
+        try {
+            return HostIoSampler.start(Path.of("/proc"), sysfs, runOutput);
+        } catch (Exception e) {
+            System.out.println("Host I/O sampling is off for this run: " + e);
+            return null;
+        }
+    }
+
     /**
      * Waits until the CPU package has cooled down to --cooldown-temperature, or --cooldown-timeout has passed, so
      * that a run doesn't start on a CPU that the previous run or the image build left hot. Returns what happened,
diff --git a/tests/performance/launcher/src/test/java/org/apache/pulsar/tests/performance/launcher/HostIoSamplerTest.java b/tests/performance/launcher/src/test/java/org/apache/pulsar/tests/performance/launcher/HostIoSamplerTest.java
new file mode 100644
index 000000000000..fdb14cd57092
--- /dev/null
+++ b/tests/performance/launcher/src/test/java/org/apache/pulsar/tests/performance/launcher/HostIoSamplerTest.java
@@ -0,0 +1,97 @@
+/*
+ * 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.pulsar.tests.performance.launcher;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class HostIoSamplerTest {
+    private Path root;
+
+    @BeforeMethod
+    public void createRoot() throws IOException {
+        root = Files.createTempDirectory("host-io");
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void deleteRoot() throws IOException {
+        try (Stream<Path> paths = Files.walk(root)) {
+            for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
+                Files.delete(path);
+            }
+        }
+    }
+
+    @Test
+    public void physicalDisksAreBlockDevicesWithADevice() throws IOException {
+        Files.createDirectories(root.resolve("sys/block/nvme0n1/device"));
+        Files.createDirectories(root.resolve("sys/block/sda/device"));
+        Files.createDirectories(root.resolve("sys/block/dm-0"));
+        Files.createDirectories(root.resolve("sys/block/loop0"));
+
+        assertThat(HostIoSampler.physicalDisks(root.resolve("sys"))).containsExactly("nvme0n1", "sda");
+    }
+
+    @Test
+    public void rowIsTheRateBetweenTwoReadings() {
+        List<String> disks = List.of("nvme0n1");
+        HostIoSampler.Counters before = new HostIoSampler.Counters(1_000, 1_000, 600, 100,
+                Map.of("nvme0n1", new long[] {0, 0, 0}));
+        // One second later: 100 more jiffies, of which 20 idle and 10 waiting for I/O; 2,000,000 sectors read
+        // (1,024 MB) and 4,000,000 written (2,048 MB); the disk busy for 500 of the 1,000 ms
+        HostIoSampler.Counters after = new HostIoSampler.Counters(2_000, 1_100, 620, 110,
+                Map.of("nvme0n1", new long[] {2_000_000, 4_000_000, 500}));
+
+        assertThat(HostIoSampler.row(null, before, disks)).isNull();
+        assertThat(HostIoSampler.row(before, after, disks)).isEqualTo("2000,70.0,10.0,1024.0,2048.0,50.0");
+        assertThat(HostIoSampler.header(disks))
+                .isEqualTo("epochMs,cpuBusyPercent,cpuIowaitPercent,nvme0n1ReadMBps,nvme0n1WriteMBps,"
+                        + "nvme0n1BusyPercent");
+    }
+
+    @Test
+    public void readsProcCounters() throws IOException {
+        Path proc = Files.createDirectories(root.resolve("proc"));
+        Files.writeString(proc.resolve("stat"), "cpu  100 5 50 800 20 3 2 0 0 0\ncpu0 1 2 3 4 5 6 7 8 0 0\n");
+        Files.writeString(proc.resolve("diskstats"),
+                "259 0 nvme0n1 10 0 2048 5 20 0 4096 7 0 30 12\n259 1 nvme0n1p1 1 0 8 1 1 0 8 1 0 1 1\n");
+        Files.createDirectories(root.resolve("sys/block/nvme0n1/device"));
+
+        HostIoSampler.Counters counters;
+        try (HostIoSampler sampler = HostIoSampler.start(proc, root.resolve("sys"), root)) {
+            assertThat(sampler).isNotNull();
+            counters = sampler.read(5_000);
+        }
+        assertThat(counters.cpuTotal()).isEqualTo(980);
+        assertThat(counters.cpuIdle()).isEqualTo(800);
+        assertThat(counters.cpuIowait()).isEqualTo(20);
+        assertThat(counters.disks().get("nvme0n1")).containsExactly(2048, 4096, 30);
+        assertThat(Files.readAllLines(root.resolve(HostIoSampler.FILE_NAME)).get(0))
+                .startsWith("epochMs,cpuBusyPercent,cpuIowaitPercent,nvme0n1ReadMBps");
+    }
+}


(pulsar) 01/04: [improve][test] Document the bottleneck elimination strategy and per-thread CPU analysis

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch lh-improve-perf-bottleneck-tooling
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit a85c3f8463ad5ab2521094fb8ea44850a8ef8c60
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Tue Sep 29 16:22:44 2026 +0300

    [improve][test] Document the bottleneck elimination strategy and per-thread CPU analysis
    
    Add an "Eliminating bottlenecks" mode to the performance tests' agent guide: find the limiting stage (a busy serial
    thread, blocked time, run-queue time, a saturated resource outside the broker), compare cost per unit of work, screen
    one change at a time quickly, check large unbatched entry sizes, add metrics to check assumptions, and record where
    the limit moved after each change.
    
    Document per-thread CPU analysis: split the measurement recording's CPU samples by thread with the converter's
    --threads option and rank threads, thread pools and the busiest thread's frames with DuckDB's quack_flamegraph.
    
    Assisted-by: Claude Code (claude-opus-5-5)
---
 tests/performance/AGENTS.md                  | 38 ++++++++++++++++++++++++
 tests/performance/docs/analyzing-profiles.md | 43 ++++++++++++++++++++++++++++
 2 files changed, 81 insertions(+)

diff --git a/tests/performance/AGENTS.md b/tests/performance/AGENTS.md
index 2f52c1843998..f6369835cca0 100644
--- a/tests/performance/AGENTS.md
+++ b/tests/performance/AGENTS.md
@@ -50,6 +50,43 @@ real-world use. Express experiments and new scenarios in the domain's terms, as
    source control. Restore host settings and stop services that this experiment started, within the user's
    authorization; leave a pre-existing metrics stack running.
 
+## Eliminating bottlenecks
+
+Use this mode when the task is to raise a scenario's capacity rather than to validate one change. A system has one
+limiting stage at a time; removing it moves the limit somewhere else, so the fastest progress comes from short
+iterations that each find the current limit, remove it and look again. Validate a change deeply only once it has
+shown that it moves the limit.
+
+1. **Find the limiting stage.** Profile the scenario (`profile` with `--extends configs/profile-broker`) and look
+   for, in this order:
+   - a single thread that is busy all the time, such as a topic's managed-ledger thread, which is a serial stage
+     that no other headroom helps: split the CPU samples by thread as
+     [Per-thread CPU](docs/analyzing-profiles.md#per-thread-cpu) describes and compare each thread's busy share
+     with 100 %;
+   - blocked time with an application frame in the off-CPU digest, such as a contended lock or monitor;
+   - run-queue time in the off-CPU capture, which means that the host has run out of CPU;
+   - a saturated resource outside the broker, in the bookies' and the host's metrics: storage flushes and throttled
+     writes, the journal, the network.
+2. **Measure per unit of work.** Compare CPU samples and blocked time per million messages, per thread and per
+   thread pool, between runs; the throughput of a saturated scenario follows the cost per message of its serial
+   stage. Prefer changes that take work off the limiting stage, or remove it, over micro-optimizations elsewhere.
+   Reduce allocation only when garbage collection or allocation is a measurable part of the limiting stage's CPU.
+3. **Make one change and screen it quickly.** One profiled run and one or two unprofiled runs per change are enough
+   to see whether the limit moved; note which stage limits the new run. Keep the changes that help on an
+   experiment branch and build on them; drop the ones that don't.
+4. **Check the other entry sizes.** Entry size changes which stage limits the broker and the bookies: run the
+   scenario with small entries (128 bytes) and with large unbatched ones, such as 8 KB and 128 KB. Scale the measured
+   messages, the gateways' `maxOutstanding` and the workload containers' direct memory with the payload size.
+   Batching is a client-side feature; for the broker and the bookies it only changes the entry size.
+5. **Add observability when an assumption can't be checked.** When a profile suggests a cause that no existing
+   metric shows, add a counter or a metric that does, in the experiment branch, and check the assumption with
+   it in the next run.
+6. **Record every iteration at a high level:** the limiting stage and its evidence, the change, the result, and
+   where the limit moved. A stage outside Pulsar's control, such as the host's single disk under all the bookies,
+   is a result too: record it and continue with the scenarios it does not limit.
+
+Before proposing a change for review, validate it as the [Experiment loop](#experiment-loop) describes.
+
 ## Quick reference
 
 Run commands from the repository root. Gradle properties (`-P...`) configure the task; launcher options go inside
@@ -260,6 +297,7 @@ augment those reports; their absence need not block analysis of the saved summar
 | Did the workload complete correctly, and what changed? | Run `README.md`, `resolved-config.yaml`, `run-info.json` and workload summaries | Compare measured throughput, latency percentiles and backlog; inspect logs for exclusions |
 | Where does a busy process wait? | `jonoffcpu-summary.md` and `offcpu-no-idle-app-root.collapsed` | The digest already ranks blocking callsites; use the optional correlator CLI for comparisons or other slices, and check coverage and loss in `jonoffcpu-report.json` |
 | Where does it use CPU or allocate? | `cpu.collapsed`, `alloc.collapsed`, then `.measurement.jfr` | Thread views find serial bottlenecks; heatmaps and JFR place CPU, allocation and GC activity in time |
+| Which thread limits the throughput? | `.measurement.jfr`, converted with `--threads` | Rank threads and pools and break down the busiest thread with DuckDB, see [Per-thread CPU](docs/analyzing-profiles.md#per-thread-cpu) |
 | How can an agent query stack profiles automatically? | A `.collapsed` or `.folded` file | Use DuckDB with quack_flamegraph; the [SQL examples](docs/analyzing-profiles.md#analyzing-collapsed-stacks-with-duckdb) rank stacks, methods and call edges and export machine-readable JSON or CSV |
 | Which cluster component explains a stall? | `metrics.json`, `grafana-panels/*.png`, `topic-stats.csv` | Use Grafana's run annotations and VictoriaMetrics queries to relate broker, bookie and ZooKeeper behavior to the measurement |
 | What retains the heap? | `heap-dumps.csv` and an `.hprof` dump | Use dominators, retained sizes and paths to GC roots; capture a separate diagnostic run with `--extends configs/heap-dumps-broker` as [Heap dumps](docs/heap-dumps.md) describes |
diff --git a/tests/performance/docs/analyzing-profiles.md b/tests/performance/docs/analyzing-profiles.md
index a603f4c14f58..17704cf432f5 100644
--- a/tests/performance/docs/analyzing-profiles.md
+++ b/tests/performance/docs/analyzing-profiles.md
@@ -268,6 +268,49 @@ duckdb -no-init -bail -csv -header < analysis.sql > analysis.csv
 Use one result query per output file so that JSON contains a single array and CSV contains one table with a header.
 `-bail` stops on SQL errors; check the exit status before consuming the output.
 
+### Per-thread CPU
+
+The flame graphs' `cpu.collapsed` merges all threads. A serial stage, such as a topic's managed-ledger thread,
+shows only when the samples are split by thread: write collapsed stacks with the thread as their first frame from the
+measurement recording, with the converter's `--threads` option:
+
+```bash
+./gradlew -q :tests:performance:report-tool:runJfrConverter \
+  --args="--cpu --threads --norm -o collapsed /absolute/path/to/recording.measurement.jfr /tmp/cpu-threads.collapsed"
+```
+
+Each stack then starts with a frame such as `[BookKeeperClientWorker-OrderedExecutor-12-0 tid=123]`. This ranks the
+thread pools, with the numeric suffix of each thread's name replaced so that a pool's threads group together:
+
+```sql
+SET VARIABLE profile = '/tmp/cpu-threads.collapsed';
+SELECT regexp_replace(regexp_extract(frames[1], '^\[(.*) tid=[0-9]+\]$', 1), '-[0-9]+$', '-N') AS pool,
+       sum(samples) AS samples,
+       round(100.0 * sum(samples) / (SELECT sum(samples) FROM read_folded(getvariable('profile'))), 1) AS pct
+FROM flamegraph_hot_stacks(getvariable('profile'))
+GROUP BY pool ORDER BY samples DESC LIMIT 20;
+```
+
+Group by `regexp_extract(frames[1], '^\[(.*) tid=[0-9]+\]$', 1)` instead to rank single threads. A thread's samples
+per second of the measurement window, times the sampling interval (10 ms by default), is its busy share of one core:
+a thread near 100 % is a serial stage. This query shows where one thread spends its CPU, counting each stack once per
+matching frame:
+
+```sql
+SET VARIABLE thread = 'BookKeeperClientWorker-OrderedExecutor-12-0';
+SET VARIABLE pkg = '^org[./]apache[./](pulsar|bookkeeper)[./]';
+WITH t AS (SELECT frames, samples FROM flamegraph_hot_stacks(getvariable('profile'))
+           WHERE regexp_extract(frames[1], '^\[(.*) tid=[0-9]+\]$', 1) = getvariable('thread')),
+     total AS (SELECT sum(samples) AS n FROM t)
+SELECT f AS frame, sum(samples) AS samples, round(100.0 * sum(samples) / any_value(n), 1) AS pct_of_thread
+FROM (SELECT unnest(list_distinct(frames[2:])) AS f, samples FROM t), total
+WHERE regexp_matches(f, getvariable('pkg'))
+GROUP BY f ORDER BY samples DESC LIMIT 30;
+```
+
+To compare runs, divide the samples by each run's measured messages in millions; the throughput of a saturated
+scenario follows the cost per message of its busiest serial thread.
+
 
 
 


(pulsar) 04/04: [improve][test] Record lessons of the first bottleneck elimination iterations in the agent guide

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch lh-improve-perf-bottleneck-tooling
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit ea548ef9b0ced698e8ee268235dfff6669c81ae2
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Tue Sep 29 18:14:19 2026 +0300

    [improve][test] Record lessons of the first bottleneck elimination iterations in the agent guide
    
    Assisted-by: Claude Code (claude-opus-5-5)
---
 tests/performance/AGENTS.md | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/tests/performance/AGENTS.md b/tests/performance/AGENTS.md
index 3f2f59cd47c2..b16814b26c87 100644
--- a/tests/performance/AGENTS.md
+++ b/tests/performance/AGENTS.md
@@ -85,6 +85,22 @@ shown that it moves the limit.
    where the limit moved. A stage outside Pulsar's control, such as the host's single disk under all the bookies,
    is a result too: record it and continue with the scenarios it does not limit.
 
+Lessons from earlier iterations:
+
+- When no thread is near 100 % busy but the throughput stops rising, read `host-io.csv`: at 80–90 % CPU busy the
+  host is the limit, and every thread waits for a CPU now and then. The clients share the host, so profile them too
+  (`--extends configs/profile-gateways --extends configs/profile-applications`) and account for all the
+  components' CPU per message; they are Pulsar clients, so their costs are Pulsar's to reduce as well.
+- Compare the broker's publish latency (`pulsar_broker_publish_latency`) and the managed ledger's add latencies
+  (`pulsar_ml_AddEntryLatencyBuckets`, `pulsar_ml_LedgerAddEntryLatencyBuckets`) with the bookies' own request and
+  journal latencies to find where a queue builds up.
+- When a stage outside the broker limits a run, check the test setup's defaults before the code: the test image's
+  `run-bookie.sh` sets 16 MB DbLedgerStorage caches unless a scenario sets them, which throttled bookie writes
+  (`bookie_throttled_write`) of large entries.
+- The launcher doesn't profile the bookies. Their metrics (`bookie_throttled_write`, `bookie_flush`, journal queue
+  and flush latencies, `bookkeeper_server_ADD_ENTRY*`) and their threads' CPU, sampled from `/proc/<pid>/task/*/stat`
+  inside the container with `docker exec`, show whether a bookie thread or its storage is the limit.
+
 Before proposing a change for review, validate it as the [Experiment loop](#experiment-loop) describes.
 
 ## Quick reference