diff --git a/.github/workflows/cppreportcard.yml b/.github/workflows/cppreportcard.yml index 8e15828..2a6a8f0 100644 --- a/.github/workflows/cppreportcard.yml +++ b/.github/workflows/cppreportcard.yml @@ -52,10 +52,10 @@ jobs: id: analysis_inputs run: | cmake -S . -B build/report -G Ninja \ - -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER=clang++-18 \ + -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_COMPILER=clang-18 -DCMAKE_CXX_COMPILER=clang++-18 \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DLINKERBOT_TRANSPORT_BUILD_TESTS=ON -DLINKERBOT_TRANSPORT_BUILD_EXAMPLES=ON \ - -DLINKERBOT_TRANSPORT_BUILD_BENCHMARKS=ON + -DLINKERBOT_TRANSPORT_BUILD_BENCHMARKS=ON -DLINKERBOT_PERF_BUILD_STRESS=ON cmake --build build/report --parallel 4 cmake --install build/report --prefix "$PWD/build/report-install" cmake -S examples/quickstart -B build/report-quickstart -G Ninja \ diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml index af466b0..4a45ba6 100644 --- a/.github/workflows/style.yml +++ b/.github/workflows/style.yml @@ -48,7 +48,7 @@ jobs: shell: bash run: | set -o pipefail - git ls-files -z -- '*.cpp' '*.hpp' '*.h' \ + git ls-files -z -- '*.c' '*.cpp' '*.hpp' '*.h' \ | xargs -0 clang-format-18 --dry-run --Werror 2>&1 \ | tee clang-format.log - name: Configure the static-analysis database diff --git a/.gitignore b/.gitignore index 4638fae..5e920c1 100644 --- a/.gitignore +++ b/.gitignore @@ -368,3 +368,13 @@ Temporary Items # add your custom gitignore here: !.gitignore !.gitsubmodules + +# Local benchmark runs; retain the historical baseline and selected formal results. +/benchmarks/results/* +!/benchmarks/results/arm64-linux-2026-11-03/ +!/benchmarks/results/stress-20261110-152431/ +/benchmarks/results/stress-20261110-152431/* +!/benchmarks/results/stress-20261110-152431/README.md +!/benchmarks/results/stress-20261110-152431/stress-report.md +!/benchmarks/results/stress-20261110-152431/stress-raw-data.tar.gz +/benchmarks/**/__pycache__/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 99ea1fd..90334ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -376,9 +376,13 @@ install(FILES examples/quickstart/CMakeLists.txt examples/quickstart/main.cpp DESTINATION ${CMAKE_INSTALL_DATADIR}/linkerbot-transport/examples/quickstart) install(DIRECTORY docs/ DESTINATION ${CMAKE_INSTALL_DATADIR}/linkerbot-transport/docs FILES_MATCHING PATTERN "*.md" PATTERN "*.csv" PATTERN "ci-performance-*.json") -install(FILES benchmarks/README.md benchmarks/summarize.py +install(FILES benchmarks/README.md DESTINATION ${CMAKE_INSTALL_DATADIR}/linkerbot-transport/benchmarks) -install(DIRECTORY benchmarks/results/ +install(FILES benchmarks/micro/README.md benchmarks/micro/summarize.py + DESTINATION ${CMAKE_INSTALL_DATADIR}/linkerbot-transport/benchmarks/micro) +install(FILES benchmarks/stress/README.md + DESTINATION ${CMAKE_INSTALL_DATADIR}/linkerbot-transport/benchmarks/stress) +install(DIRECTORY benchmarks/results/arm64-linux-2026-11-03 DESTINATION ${CMAKE_INSTALL_DATADIR}/linkerbot-transport/benchmarks/results FILES_MATCHING PATTERN "*.md" PATTERN "*.csv") diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index afbf3fb..f306e6f 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -13,9 +13,16 @@ if(NOT TARGET linkerbot::can) set(LINKERBOT_ALLOW_DEPENDENCY_DOWNLOADS OFF CACHE BOOL "" FORCE) add_subdirectory(.. transport) endif() -add_executable(linkerbot-perf main.cpp) +add_executable(linkerbot-perf micro/main.cpp) target_link_libraries(linkerbot-perf PRIVATE linkerbot::can) target_compile_features(linkerbot-perf PRIVATE cxx_std_17) option(LINKERBOT_PERF_COUNT_ALLOCATIONS "Instrument benchmark C++ allocations" OFF) target_compile_definitions(linkerbot-perf PRIVATE LINKERBOT_PERF_COUNT_ALLOCATIONS=$) + +# Optional convenience target; the stress runner normally builds this separately +# in a fresh temporary directory against the selected local source tree. +option(LINKERBOT_PERF_BUILD_STRESS "Build end-to-end stress workers" OFF) +if(LINKERBOT_PERF_BUILD_STRESS) + add_subdirectory(stress) +endif() diff --git a/benchmarks/README.md b/benchmarks/README.md index 41717c6..1a0811d 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,77 +1,34 @@ -# Linux performance baselines +# 性能测试 / Benchmarks -Run these build commands from a complete source checkout. Installed packages -include the measurement notes, CSV results and summary script, but not the -benchmark build sources. Configure this standalone project in Release mode; -it needs no Catch2 or hardware: +本目录包含两类测试,均需完整源码仓库;软件测试结果不代表物理 CAN 带宽。 -```sh -cmake -S benchmarks -B build/perf -G Ninja -DCMAKE_BUILD_TYPE=Release -cmake --build build/perf --parallel 4 -./build/perf/linkerbot-perf --iterations 200000 --idle-ms 500 --repetitions 5 -``` +- [`micro/`](micro/README.md):内部操作基准,测订阅快照、订阅变更和 Session 空闲开销。`main.cpp` 输出 CSV,`summarize.py` 比较修改前后耗时、CPU 和分配次数。 +- [`stress/`](stress/README.md):完整通信链路压测,扫描内存/vcan 的经典 CAN 与 CAN FD,逐帧校验,输出吞吐、P99、CPU、RSS、丢帧及性能对照报告。 +- `results/`:结果集中存放。每次完整压测自动新建目录,避免覆盖;本机生成结果由 Git 忽略。已跟踪的基准记录和选定正式压测结果保留。 -The default `LINKERBOT_PERF_COUNT_ALLOCATIONS=OFF` build is for timing and CPU -measurements. It does not override global allocation functions or update allocation -counters; its CSV rows have `allocation_tracking=0` and `NA` in both allocation -columns. Build a separate instrumented executable for allocation measurements: +已保存的 Ubuntu 正式结果:[Transport 0.3.4 压测报告(英文)](results/stress-20261110-152431/stress-report.md) · [原始数据包](results/stress-20261110-152431/stress-raw-data.tar.gz) · [英文归档校验说明](results/stress-20261110-152431/README.md)。测试于 2026-11-10 完成,共 119 档,四类吞吐均通过两次 60 秒确认。被测通信库提交为 `0e190032d65ed0b315337b45b3779cf4f650ed68`,运行发生在工具迁入仓库之前;报告和压缩包保留当时的版本、路径及计数,中文说明已翻译为英文。 -```sh -cmake -S benchmarks -B build/perf-alloc -G Ninja -DCMAKE_BUILD_TYPE=Release \ - -DLINKERBOT_PERF_COUNT_ALLOCATIONS=ON -cmake --build build/perf-alloc --parallel 4 -./build/perf-alloc/linkerbot-perf --iterations 200000 --idle-ms 500 --repetitions 5 -``` +从通信库根目录运行完整压测: -Instrumented rows have `allocation_tracking=1`. Use them for allocation counts, -not for the primary performance comparison: atomic counter updates add overhead -only to operations that allocate, and can exaggerate the benefit of removing -allocations. Compare before/after timing with instrumentation OFF, and compare -before/after allocation counts with it ON. Keep all remaining build and run -conditions the same within each comparison. +```bash +python3 benchmarks/stress/run.py --quick # 快速验证,非正式结果 +python3 benchmarks/stress/run.py # 正式流程,约 40 分钟 +``` -Redirect stdout to a CSV file outside the source tree. Keep the source commit, -compiler/standard-library versions, flags, kernel, CPU architecture, affinity and -container CPU limits with each result. Run before and after binaries under the -same conditions, preferably in alternating order. Do not compare sanitizer builds. +默认结果为 `results/quick-YYYYMMDD-HHMMSS/` 或 `results/stress-YYYYMMDD-HHMMSS/`(相对于 benchmarks)。每个结果目录仅保留报告和原始数据压缩包;构建和展开采样均使用临时目录。允许用 `--output DIR` 指定其他位置。 -`snapshot_copy` or `snapshot_view` measures one registry snapshot plus invocation of every subscriber; -`operations` is the number of snapshots, not callbacks. `checksum` must equal -`subjects * operations`. `mutation` measures a subscribe/unsubscribe pair while -holding the stated number of existing subscribers. These direct registry cases -isolate software overhead and do not measure CAN throughput or scheduler latency. -`mutation_snapshot` additionally acquires and releases a snapshot after each -subscribe and each unsubscribe, exposing cold snapshot-rebuild costs. Each -operation is still one subscribe/unsubscribe pair; its checksum must equal -`operations * (2 * subjects + 1)`. Plain `mutation` does not acquire snapshots. -The same source automatically selects `snapshot_view()` when the revision provides -it, otherwise `snapshot()`. The CSV scenario records the selected path; compare -these rows by subscriber count and repetition. The invocation loop and all other -instrumentation remain identical. +内部基准的现有构建方式保持不变: -Alternatively, the parent project may enable its optional benchmark target via -`-DLINKERBOT_TRANSPORT_BUILD_BENCHMARKS=ON`; the standalone project does not force the -parent project's test/example choices when the library target already exists. +```bash +cmake -S benchmarks -B build/perf -DCMAKE_BUILD_TYPE=Release +cmake --build build/perf --parallel 4 +mkdir -p benchmarks/results/micro-example +./build/perf/linkerbot-perf --iterations 200000 --idle-ms 500 --repetitions 5 \ + > benchmarks/results/micro-example/before-timing.csv +``` -`idle_unrouted` creates 0/1/8/32 Sessions with no inbox; `idle_routed` also retains -one subscribed inbox per Session, without injecting any frames. Each Session -owns one passive transport. Its reader -uses a 10 ms condition-variable timeout. The zero-Session case measures the -baseline cost of the measuring process. A 200 ms warmup precedes each sample; -creation and shutdown are excluded. `transport_reads` separately identifies -reader activity, so it must not be mistaken for writer wakeups. +完整的两种分配计数模式与 before/after 比较流程见 [micro/README.md](micro/README.md)。需要同时构建完整压测程序时,可加 `-DLINKERBOT_PERF_BUILD_STRESS=ON`;通常由 `stress/run.py` 单独构建,保证每次使用新的 Release 产物。 -All times are nanoseconds. `cpu_ns` and context switches come from process-wide -Linux counters and include every benchmark thread. Voluntary switches are a -proxy for scheduling activity, not an exact count of Session wakeups. Allocation -counts/bytes include successful C++ global new/new[] calls (including aligned -forms) during measurement; requested bytes do not include allocator metadata, -direct C malloc, kernel allocations or resident memory. Atomic instrumentation -itself adds overhead. The instrumented benchmark does not intercept deallocation -or measure peak live memory. Never compare an instrumented binary's time with an -uninstrumented binary's time. +安装包仅包含测量说明、micro 汇总脚本和已跟踪的 ARM64 基准记录,不包含测试构建源码、本机 stress/quick 结果或 `results/history/`。 -Warmup, setup, output and cleanup are outside allocation measurement. CSV keeps -raw per-repetition results; report medians and dispersion rather than one fastest -sample. Preserve callback ordering, cancellation barriers, self-unsubscribe, -concurrent unsubscribe/clear, and cleanup/recovery behavior when optimizing. +历史结果整理至 `results/history/`,保留当时的版本、数值和命令。新结果不替代历史证据。原有压缩备份仍位于工作区的 `archives/`,不纳入通信库发布包。 diff --git a/benchmarks/micro/README.md b/benchmarks/micro/README.md new file mode 100644 index 0000000..74d0b76 --- /dev/null +++ b/benchmarks/micro/README.md @@ -0,0 +1,78 @@ +# Linux performance baselines + +Run these build commands from a complete source checkout. Installed packages +include the measurement notes, recorded baseline CSVs and summary script, but not +the benchmark build sources. The source lives in `benchmarks/micro/`; run build +commands from the repository root. Configure this standalone project in Release mode; +it needs no Catch2 or hardware: + +```sh +cmake -S benchmarks -B build/perf -G Ninja -DCMAKE_BUILD_TYPE=Release +cmake --build build/perf --parallel 4 +./build/perf/linkerbot-perf --iterations 200000 --idle-ms 500 --repetitions 5 +``` + +The default `LINKERBOT_PERF_COUNT_ALLOCATIONS=OFF` build is for timing and CPU +measurements. It does not override global allocation functions or update allocation +counters; its CSV rows have `allocation_tracking=0` and `NA` in both allocation +columns. Build a separate instrumented executable for allocation measurements: + +```sh +cmake -S benchmarks -B build/perf-alloc -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DLINKERBOT_PERF_COUNT_ALLOCATIONS=ON +cmake --build build/perf-alloc --parallel 4 +./build/perf-alloc/linkerbot-perf --iterations 200000 --idle-ms 500 --repetitions 5 +``` + +Instrumented rows have `allocation_tracking=1`. Use them for allocation counts, +not for the primary performance comparison: atomic counter updates add overhead +only to operations that allocate, and can exaggerate the benefit of removing +allocations. Compare before/after timing with instrumentation OFF, and compare +before/after allocation counts with it ON. Keep all remaining build and run +conditions the same within each comparison. + +Redirect stdout to a CSV file in a new ignored `benchmarks/results/micro-YYYYMMDD-HHMMSS/` directory. Keep the source commit, +compiler/standard-library versions, flags, kernel, CPU architecture, affinity and +container CPU limits with each result. Run before and after binaries under the +same conditions, preferably in alternating order. Do not compare sanitizer builds. + +`snapshot_copy` or `snapshot_view` measures one registry snapshot plus invocation of every subscriber; +`operations` is the number of snapshots, not callbacks. `checksum` must equal +`subjects * operations`. `mutation` measures a subscribe/unsubscribe pair while +holding the stated number of existing subscribers. These direct registry cases +isolate software overhead and do not measure CAN throughput or scheduler latency. +`mutation_snapshot` additionally acquires and releases a snapshot after each +subscribe and each unsubscribe, exposing cold snapshot-rebuild costs. Each +operation is still one subscribe/unsubscribe pair; its checksum must equal +`operations * (2 * subjects + 1)`. Plain `mutation` does not acquire snapshots. +The same source automatically selects `snapshot_view()` when the revision provides +it, otherwise `snapshot()`. The CSV scenario records the selected path; compare +these rows by subscriber count and repetition. The invocation loop and all other +instrumentation remain identical. + +Alternatively, the parent project may enable its optional benchmark target via +`-DLINKERBOT_TRANSPORT_BUILD_BENCHMARKS=ON`; the standalone project does not force the +parent project's test/example choices when the library target already exists. + +`idle_unrouted` creates 0/1/8/32 Sessions with no inbox; `idle_routed` also retains +one subscribed inbox per Session, without injecting any frames. Each Session +owns one passive transport. Its reader +uses a 10 ms condition-variable timeout. The zero-Session case measures the +baseline cost of the measuring process. A 200 ms warmup precedes each sample; +creation and shutdown are excluded. `transport_reads` separately identifies +reader activity, so it must not be mistaken for writer wakeups. + +All times are nanoseconds. `cpu_ns` and context switches come from process-wide +Linux counters and include every benchmark thread. Voluntary switches are a +proxy for scheduling activity, not an exact count of Session wakeups. Allocation +counts/bytes include successful C++ global new/new[] calls (including aligned +forms) during measurement; requested bytes do not include allocator metadata, +direct C malloc, kernel allocations or resident memory. Atomic instrumentation +itself adds overhead. The instrumented benchmark does not intercept deallocation +or measure peak live memory. Never compare an instrumented binary's time with an +uninstrumented binary's time. + +Warmup, setup, output and cleanup are outside allocation measurement. CSV keeps +raw per-repetition results; report medians and dispersion rather than one fastest +sample. Preserve callback ordering, cancellation barriers, self-unsubscribe, +concurrent unsubscribe/clear, and cleanup/recovery behavior when optimizing. diff --git a/benchmarks/main.cpp b/benchmarks/micro/main.cpp similarity index 100% rename from benchmarks/main.cpp rename to benchmarks/micro/main.cpp diff --git a/benchmarks/summarize.py b/benchmarks/micro/summarize.py similarity index 98% rename from benchmarks/summarize.py rename to benchmarks/micro/summarize.py index a9c3b40..a4f5f98 100644 --- a/benchmarks/summarize.py +++ b/benchmarks/micro/summarize.py @@ -135,7 +135,7 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "directory", nargs="?", type=Path, - default=Path(__file__).parent / "results" / "arm64-linux-2026-11-03", + default=Path(__file__).resolve().parents[1] / "results" / "arm64-linux-2026-11-03", ) args = parser.parse_args() try: diff --git a/benchmarks/results/arm64-linux-2026-11-03/README.md b/benchmarks/results/arm64-linux-2026-11-03/README.md index 6dbe3ff..0f27062 100644 --- a/benchmarks/results/arm64-linux-2026-11-03/README.md +++ b/benchmarks/results/arm64-linux-2026-11-03/README.md @@ -52,7 +52,7 @@ From the repository root, validate the CSV schema, modes and checksums and summarize medians and ranges with: ```sh -python3 benchmarks/summarize.py benchmarks/results/arm64-linux-2026-11-03 +python3 benchmarks/micro/summarize.py benchmarks/results/arm64-linux-2026-11-03 ``` The uninstrumented median for snapshot acquisition plus invocation at 1, 8 and diff --git a/benchmarks/results/stress-20261110-152431/README.md b/benchmarks/results/stress-20261110-152431/README.md new file mode 100644 index 0000000..5125118 --- /dev/null +++ b/benchmarks/results/stress-20261110-152431/README.md @@ -0,0 +1,22 @@ +# Transport 0.3.4 Stress Test Results + +- [Stress test report](stress-report.md) +- [Raw data archive](stress-raw-data.tar.gz) + +The test ran on November 10, 2026 against commit `0e190032d65ed0b315337b45b3779cf4f650ed68`. It covered 119 configurations, including six failed overload configurations. All four scenarios completed two consecutive 60-second lossless confirmations. + +This English edition retains the condensed test-information section. The report, diagnostic descriptions and archived Python tool snapshot have been translated. All numeric measurements, CSV samples, logs, environment metadata, compiler records, C/C++ sources and compiled artifacts are unchanged. The archive includes `localization.json` with the original hashes and translation scope, and a regenerated `manifest.json`. + +## Verify the English Archive + +Use the translated verifier bundled in the archive. The current repository verifier renders Chinese reports and is intended for its original-format output, not this English edition. From this directory, run: + +```sh +archive_path="$PWD/stress-raw-data.tar.gz" +verify_dir=$(mktemp -d) +tar -xzf "$archive_path" -C "$verify_dir" tool-source/run.py +PYTHONDONTWRITEBYTECODE=1 python3 "$verify_dir/tool-source/run.py" --verify "$archive_path" +rm -r -- "$verify_dir" +``` + +The verifier checks every archive checksum, per-configuration JSON records, validity assessments, socket counters, RSS summaries, the linked-library checksum, confirmation records and report regeneration. Verification does not run the stress test or open a hardware channel. Expected summary: 119 records, four confirmed scenarios, unchanged source, and no run-level errors. The six failed overload configurations remain recorded separately. diff --git a/benchmarks/results/stress-20261110-152431/stress-raw-data.tar.gz b/benchmarks/results/stress-20261110-152431/stress-raw-data.tar.gz new file mode 100644 index 0000000..07c6a2f Binary files /dev/null and b/benchmarks/results/stress-20261110-152431/stress-raw-data.tar.gz differ diff --git a/benchmarks/results/stress-20261110-152431/stress-report.md b/benchmarks/results/stress-20261110-152431/stress-report.md new file mode 100644 index 0000000..0f183cf --- /dev/null +++ b/benchmarks/results/stress-20261110-152431/stress-report.md @@ -0,0 +1,91 @@ +# Transport 0.3.4 Stress Test Report + +## Ubuntu System Stress Test + +### Test Information + +| Item | Details | +| --- | --- | +| Test time | 2026-11-10 14:45:57+08:00 to 2026-11-10 15:24:31+08:00 | +| Status | Formal run completed; all four lossless confirmations are valid; 119 configurations, 6 failed; failed configurations are excluded from lossless results | +| System | Ubuntu 25.10, Linux 6.17.0-41-generic, x86_64 | +| CPU | AMD Ryzen 7 H 260, 8 physical cores / 16 logical CPUs | +| Build | c++ (Ubuntu 15.2.0-4ubuntu4) 15.2.0; C++17; Release (`-O3 -DNDEBUG`) | +| Tested version | Transport 0.3.4, commit `0e190032d65ed0b315337b45b3779cf4f650ed68` | +| Source state | Clean working tree; unchanged throughout the test | + +Full environment details, source fingerprints and linked-library checksums are in the [raw data archive](stress-raw-data.tar.gz). + +### Test Method + +The selected local source was compiled directly in a fresh temporary directory, without fetching remote changes or using release packages. Memory loopback and vcan in an isolated network namespace were tested with 8-byte Classic CAN frames and 64-byte CAN FD+BRS frames. +The scan used 1/2/4/8/16/32 sender threads, 1/8 frames per batch and an initial window of 8 batches per thread. Additional runs used 1/8 threads, 32/128 frames per batch and a 1-batch window. The fastest candidate was then tested with windows of 1/4/16/32 batches (at most 4096 frames and 1024 batches in flight). Each screening run lasted 15 seconds. The two fastest lossless candidates were retested for 30 seconds, then the better candidate underwent two consecutive 60-second confirmations; the second candidate was tried if confirmation failed. +Each thread submits the batches within its window, waits for send receipts and all replies in order, then continues. Validation checks IDs, frame flags, lengths, sequence numbers and payload patterns. Throughput is the number of correctly validated replies divided by actual elapsed seconds; one request plus one reply counts as one complete round trip. All 8 Classic CAN bytes carry the sequence number and timestamp; the other 56 FD bytes are also checked individually. +Normal vcan throughput runs requested a 4 MiB receive buffer at both endpoints, changing only the sockets used by this test. Controls covered default-buffer overload at 8 threads x 8 frames x 8 batches, larger buffers, smaller windows, thread counts at equal in-flight limits, and per-frame versus batched peers with the same FD configuration. +P99 is the upper bound of a 10-microsecond histogram bucket (the final bucket uses the actual maximum). CPU 100% means one logical CPU; process CPU includes the stress driver, communication library and simulated peer, with kernel CPU time counted as system time. RSS covers the whole process. Software loopback results do not represent physical CAN bandwidth. + +### Test Results + +- **Memory loopback Classic CAN:** Two confirmations: **1.1358 / 1.1351 million complete round trips/s**; 8 threads, 128 frames/batch, a 4-batch window per thread, at most 4096 frames in flight. Validated counts: **68150272 / 68111360**; P99: **4.249 / 4.289 ms**; CPU: **2.31 / 2.31 logical CPUs**; RSS sample range: **7.36-7.64 MiB**; library overflows: **0 / 0**; kernel drops: **Not applicable (no kernel sockets)**. Raw records: `020-confirm-memory-can-t8-b128-w4`, `021-confirm-memory-can-t8-b128-w4`. +- **Memory loopback CAN FD:** Two confirmations: **1.2885 / 1.2773 million complete round trips/s**; 1 thread, 128 frames/batch, a 16-batch window per thread, at most 2048 frames in flight. Validated counts: **77314048 / 76638208**; P99: **1.909 / 1.919 ms**; CPU: **2.03 / 2.03 logical CPUs**; RSS sample range: **5.97-6.10 MiB**; library overflows: **0 / 0**; kernel drops: **Not applicable (no kernel sockets)**. Raw records: `080-confirm-memory-fd-t1-b128-w16`, `081-confirm-memory-fd-t1-b128-w16`. +- **vcan Classic CAN:** Two confirmations: **0.3306 / 0.3337 million complete round trips/s**; 8 threads, 8 frames/batch, a 8-batch window per thread, at most 512 frames in flight. Validated counts: **19838848 / 20024256**; P99: **2.009 / 2.029 ms**; CPU: **3.59 / 3.61 logical CPUs**; RSS sample range: **5.96-6.01 MiB**; library overflows: **0 / 0**; kernel drops: **Session 0 / 0, peer 0 / 0**. Raw records: `045-confirm-vcan-can-t8-b8-w8`, `046-confirm-vcan-can-t8-b8-w8`. +- **vcan CAN FD:** Two confirmations: **0.3258 / 0.3265 million complete round trips/s**; 8 threads, 32 frames/batch, a 1-batch window per thread, at most 256 frames in flight. Validated counts: **19548352 / 19591904**; P99: **0.979 / 0.959 ms**; CPU: **3.29 / 3.28 logical CPUs**; RSS sample range: **5.88-6.04 MiB**; library overflows: **0 / 0**; kernel drops: **Session 0 / 0, peer 0 / 0**. Raw records: `103-confirm-vcan-fd-t8-b32-w1`, `104-confirm-vcan-fd-t8-b32-w1`. + +Actual socket receive buffers (kernel-reported values, which may be twice the requested size): + +- vcan Classic CAN: session=8388608 B/peer=8388608 B; session=8388608 B/peer=8388608 B. +- vcan CAN FD: session=8388608 B/peer=8388608 B; session=8388608 B/peer=8388608 B. + +### Performance Analysis + +#### 1. Frame Loss Under High Concurrency + +- Classic CAN `047-overload-vcan-can-t8-b8-w8`: FAIL; 8 x 8 x 8, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=1408/1408/1331/1331/1331/1262; kernel drops: Session=0, peer=77; library overflows=0. +- Classic CAN `048-overload-vcan-can-t8-b8-w8`: FAIL; 8 x 8 x 8, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=3648/3648/3640/3640/3640/3572; kernel drops: Session=0, peer=8; library overflows=0. +- Classic CAN `049-overload-vcan-can-t8-b8-w8`: FAIL; 8 x 8 x 8, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=5696/5696/5674/5674/5674/5593; kernel drops: Session=0, peer=22; library overflows=0. +- Classic CAN `050-buffer-control-vcan-can-t8-b8-w8`: PASS; 8 x 8 x 8, large buffers (session=8388608 B, peer=8388608 B); submitted/library TX/peer RX/peer TX/library RX/validated=9973888/9973888/9973888/9973888/9973888/9973888; kernel drops: Session=0, peer=0; library overflows=0. +- Classic CAN `051-window-control-vcan-can-t8-b8-w1`: PASS; 8 x 8 x 1, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=4894744/4894744/4894744/4894744/4894744/4894744; kernel drops: Session=0, peer=0; library overflows=0. + +Classic CAN: Kernel counters confirmed socket receive-queue drops at the simulated peer receiver. Both larger-buffer and smaller-window controls passed, supporting burst receive-queue overload as the explanation. No library overflows were observed in these overload runs. + +- CAN FD `105-overload-vcan-fd-t8-b8-w8`: FAIL; 8 x 8 x 8, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=3776/3776/3711/3711/3711/3450; kernel drops: Session=0, peer=65; library overflows=0. +- CAN FD `106-overload-vcan-fd-t8-b8-w8`: FAIL; 8 x 8 x 8, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=1856/1856/1831/1831/1815/1686; kernel drops: Session=16, peer=25; library overflows=0. +- CAN FD `107-overload-vcan-fd-t8-b8-w8`: FAIL; 8 x 8 x 8, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=1472/1472/1472/1472/1447/1367; kernel drops: Session=25, peer=0; library overflows=0. +- CAN FD `108-buffer-control-vcan-fd-t8-b8-w8`: PASS; 8 x 8 x 8, large buffers (session=8388608 B, peer=8388608 B); submitted/library TX/peer RX/peer TX/library RX/validated=9763648/9763648/9763648/9763648/9763648/9763648; kernel drops: Session=0, peer=0; library overflows=0. +- CAN FD `109-window-control-vcan-fd-t8-b8-w1`: PASS; 8 x 8 x 1, default buffers (session=212992 B, peer=212992 B); submitted/library TX/peer RX/peer TX/library RX/validated=4938600/4938600/4938600/4938600/4938600/4938600; kernel drops: Session=0, peer=0; library overflows=0. + +CAN FD: Kernel counters confirmed socket receive-queue drops at the simulated peer receiver, Session receiver. Both larger-buffer and smaller-window controls passed, supporting burst receive-queue overload as the explanation. No library overflows were observed in these overload runs. + +#### 2. Performance Bottlenecks + +- Classic CAN: 2 threads x 8 frames x 8 batches, at most 128 frames in flight, 2 valid control runs; mean 0.3283 million round trips/s, mean P99 0.539 ms, CPU 3.49 logical CPUs, peer CPU 0.99 logical CPUs. +- Classic CAN: 8 threads x 8 frames x 2 batches, at most 128 frames in flight, 2 valid control runs; mean 0.3299 million round trips/s, mean P99 0.509 ms, CPU 3.64 logical CPUs, peer CPU 0.99 logical CPUs. +- Classic CAN: 8 threads x 8 frames x 8 batches, at most 512 frames in flight, 2 valid control runs; mean 0.3333 million round trips/s, mean P99 1.989 ms, CPU 3.64 logical CPUs, peer CPU 0.99 logical CPUs. + +Classic CAN: At the same 128-frame in-flight limit, increasing threads from 2 to 8 changed throughput by +0.5%. With 8 threads, increasing the limit from 128 to 512 frames changed throughput by +1.0%, while mean P99 increased from 0.509 to 1.989 ms. Scheduling and run-to-run variation affect these differences; they support only comparisons between the tested configurations. + +- CAN FD: 2 threads x 8 frames x 8 batches, at most 128 frames in flight, 2 valid control runs; mean 0.3292 million round trips/s, mean P99 0.529 ms, CPU 3.51 logical CPUs, peer CPU 0.99 logical CPUs. +- CAN FD: 8 threads x 8 frames x 2 batches, at most 128 frames in flight, 2 valid control runs; mean 0.3327 million round trips/s, mean P99 0.504 ms, CPU 3.66 logical CPUs, peer CPU 0.99 logical CPUs. +- CAN FD: 8 threads x 8 frames x 8 batches, at most 512 frames in flight, 2 valid control runs; mean 0.3359 million round trips/s, mean P99 2.009 ms, CPU 3.64 logical CPUs, peer CPU 0.99 logical CPUs. + +CAN FD: At the same 128-frame in-flight limit, increasing threads from 2 to 8 changed throughput by +1.1%. With 8 threads, increasing the limit from 128 to 512 frames changed throughput by +1.0%, while mean P99 increased from 0.504 to 2.009 ms. Scheduling and run-to-run variation affect these differences; they support only comparisons between the tested configurations. + +- FD, identical 2 x 8 x 8 configuration with large buffers, library peer, per-frame: 0.3279 million round trips/s, P99 0.549 ms, peer CPU 0.99 logical CPUs (`116-peer-comparison-vcan-fd-t2-b8-w8`). +- FD, identical 2 x 8 x 8 configuration with large buffers, raw socket peer, per-frame: 0.3515 million round trips/s, P99 0.489 ms, peer CPU 0.99 logical CPUs (`117-peer-comparison-vcan-fd-t2-b8-w8`). +- FD, identical 2 x 8 x 8 configuration with large buffers, raw socket peer, batches of 32 frames: 0.3972 million round trips/s, P99 0.419 ms, peer CPU 0.98 logical CPUs (`118-peer-comparison-vcan-fd-t2-b8-w8`). + +Changing only the raw socket peer from per-frame to batched processing changed throughput by +13.0% in this run. The test peer implementation affects observed throughput. +No function-level or lock profiling evidence was collected, so a unique bottleneck cannot be identified. The best result in this finite parameter search is not an absolute throughput limit of the communication library. RSS describes only the observed finite duration and does not prove freedom from long-term leaks. + +### Failed Configurations and Integrity + +- `047-overload-vcan-can-t8-b8-w8`: Exit code 1; Stress validation failed or JSON missing; peer kernel drops 77. Raw stdout/log: `047-overload-vcan-can-t8-b8-w8.json` / `047-overload-vcan-can-t8-b8-w8.log`. +- `048-overload-vcan-can-t8-b8-w8`: Exit code 1; Stress validation failed or JSON missing; peer kernel drops 8. Raw stdout/log: `048-overload-vcan-can-t8-b8-w8.json` / `048-overload-vcan-can-t8-b8-w8.log`. +- `049-overload-vcan-can-t8-b8-w8`: Exit code 1; Stress validation failed or JSON missing; peer kernel drops 22. Raw stdout/log: `049-overload-vcan-can-t8-b8-w8.json` / `049-overload-vcan-can-t8-b8-w8.log`. +- `105-overload-vcan-fd-t8-b8-w8`: Exit code 1; Stress validation failed or JSON missing; peer kernel drops 65. Raw stdout/log: `105-overload-vcan-fd-t8-b8-w8.json` / `105-overload-vcan-fd-t8-b8-w8.log`. +- `106-overload-vcan-fd-t8-b8-w8`: Exit code 1; Stress validation failed or JSON missing; session kernel drops 16; peer kernel drops 25. Raw stdout/log: `106-overload-vcan-fd-t8-b8-w8.json` / `106-overload-vcan-fd-t8-b8-w8.log`. +- `107-overload-vcan-fd-t8-b8-w8`: Exit code 1; Stress validation failed or JSON missing; session kernel drops 25. Raw stdout/log: `107-overload-vcan-fd-t8-b8-w8.json` / `107-overload-vcan-fd-t8-b8-w8.log`. + +Raw data: `stress-raw-data.tar.gz` in the same directory. The archive contains this report, per-configuration JSON/CSV/logs, socket counters, environment records, source fingerprints, tool sources, compiler options and the linked library. The original collection process verified per-file SHA256 checksums before removing temporary files. + +This English edition translates the report, diagnostic descriptions and the archived tool snapshot. Measurement values, CSV samples, logs, environment metadata and compiled artifacts are unchanged. Original hashes and the translation scope are recorded in `localization.json`; `manifest.json` contains the updated archive checksums. The translated tool snapshot is not byte-identical to the tool used for the original measurement. diff --git a/benchmarks/stress/CMakeLists.txt b/benchmarks/stress/CMakeLists.txt new file mode 100644 index 0000000..0c95212 --- /dev/null +++ b/benchmarks/stress/CMakeLists.txt @@ -0,0 +1,28 @@ +cmake_minimum_required(VERSION 3.16) +project(local_transport_stress LANGUAGES C CXX) +set(TRANSPORT_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/../.." CACHE PATH "Local transport source") +get_filename_component(TRANSPORT_SOURCE "${TRANSPORT_SOURCE}" REALPATH) +if(NOT EXISTS "${TRANSPORT_SOURCE}/include/linkerbot/transport/session.hpp") + message(FATAL_ERROR "TRANSPORT_SOURCE must be a local communication library source tree") +endif() +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +if(NOT TARGET linkerbot::can) + set(LINKERBOT_TRANSPORT_BUILD_TESTS OFF CACHE BOOL "" FORCE) + set(LINKERBOT_TRANSPORT_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) + set(LINKERBOT_TRANSPORT_BUILD_BENCHMARKS OFF CACHE BOOL "" FORCE) + set(LINKERBOT_ALLOW_DEPENDENCY_DOWNLOADS OFF CACHE BOOL "" FORCE) + set(LINKERBOT_TRANSPORT_ENABLE_COVERAGE OFF CACHE BOOL "" FORCE) + set(LINKERBOT_TRANSPORT_ENABLE_SERIAL OFF CACHE BOOL "" FORCE) + set(LINKERBOT_TRANSPORT_ENABLE_MODBUS OFF CACHE BOOL "" FORCE) + add_subdirectory("${TRANSPORT_SOURCE}" local-library) +endif() +foreach(worker throughput profile) + add_executable(${worker}_worker src/${worker}.cpp) + target_compile_features(${worker}_worker PRIVATE cxx_std_17) + target_link_libraries(${worker}_worker PRIVATE linkerbot::can) + target_link_options(${worker}_worker PRIVATE "-Wl,-Map=${CMAKE_CURRENT_BINARY_DIR}/${worker}_worker.map") +endforeach() +add_library(socket_probe SHARED src/socket_probe.c) +target_link_libraries(socket_probe PRIVATE pthread) +file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/linked-library.txt" + CONTENT "$\n$\n${TRANSPORT_SOURCE}\n") diff --git a/benchmarks/stress/README.md b/benchmarks/stress/README.md new file mode 100644 index 0000000..c1ec4f4 --- /dev/null +++ b/benchmarks/stress/README.md @@ -0,0 +1,40 @@ +# 本地通信库 Ubuntu 压测 + +从通信库根目录执行: + +```bash +python3 benchmarks/stress/run.py --quick +python3 benchmarks/stress/run.py +python3 benchmarks/stress/run.py --source /path/to/another/local/transport +python3 benchmarks/stress/run.py --output /path/to/results +python3 benchmarks/stress/run.py --verify /path/to/generated/archive.tar.gz +``` + +已保存的 2026-11-10 正式结果已翻译为英文,使用归档内的英文校验器;具体步骤见[英文结果说明](../results/stress-20261110-152431/README.md)。上述 `--verify` 命令用于本工具生成的原始格式归档。 + +默认测试本工具所在通信库的实际源码,不联网同步、不使用发布包。即使从其他工作目录启动也能定位源码;`--source` 可选择另一个本地 Git 工作树。需要 Ubuntu、Python 3.10+、CMake、GCC/G++、Git、iproute2、kmod 和 vcan 内核支持,以及可免交互执行 `ip netns`、`modprobe vcan`、`kill` 的 `sudo -n`。无需物理 CAN 设备。 + +源码按职责存放: + +- `run.py`:参数扫描、数据校验、环境记录、报告、归档及资源清理。 +- `src/throughput.cpp`:内存/vcan 吞吐、逐帧校验及队列边界/恢复契约。 +- `src/profile.cpp`:线程/窗口对照、队列延迟、CPU 和模拟端逐帧/批量对照。 +- `src/socket_probe.c`:在 CAN socket 打开/关闭时读取内核丢帧及实际接收缓冲,仅调整本次 socket,不拦截逐帧读写。 +- `CMakeLists.txt`:独立构建;已有 `linkerbot::can` 目标时可复用,独立运行时构建所选本地源码。 +- `tests/test_run.py`:失败判定、超时清理、归档完整性及输出目录自检。 + +每次在新的临时目录构建 Release,链接 `linkerbot::can`,关闭库自身测试、示例、基准、串口/Modbus及依赖下载。记录版本、HEAD、工作树、源码 SHA256 清单、编译命令、链接映射及实际库摘要。构建后和测试后复核源码,并在运行中轮询;发现变化即标记无效。允许带本地变更,报告会明确记录。 + +正式扫描内存/vcan × CAN 8 字节/FD+BRS 64 字节:1/2/4/8/16/32 线程,每批 1/8 帧、窗口 8 批;补测 1/8 线程、每批 32/128 帧、窗口 1 批;调整最快候选窗口为 1/4/16/32 批。每档 15 秒,最快两个无损候选复测 30 秒,择优连续两次确认 60 秒。失败档单列,不计入无损成绩。正常 vcan 两端申请 4 MiB 接收缓冲,记录实际值与内核丢帧。另做默认缓冲过载、扩大缓冲/缩小窗口对照、相同在途量线程对照,以及 FD 模拟端逐帧/批量对照。 + +默认结果保存到 `benchmarks/results/stress-时间戳/`,仅有 `压测报告.md`、`压测原始数据.tar.gz`。`--quick` 每档 2 秒、缩减筛选,结果放 `benchmarks/results/quick-时间戳/`,仅有 `快速验证报告.md`、`快速验证原始数据.tar.gz`,明确标记非正式。同秒启动也分配不同目录;同一源码的压测不并发执行。`--output DIR` 指定确切目录,重复指定同一目录会替换其中的两个结果文件。 + +结果目录已加入 Git 忽略,不会干扰源码变化检测。逐档 JSON/CSV/日志、构建、静态库及链接映射全部位于临时目录,归档逐项 SHA256 和报告指标校验后清理。包内保留实际运行的工具源码(含 src/tests 子目录)。历史正式报告与压缩包直接迁移,不修改测量内容或原始源码路径;归档中的旧路径描述当时的运行环境。 + +只创建本次独立网络命名空间内的 vcan,不操作物理接口或全局 sysctl。正常、超时、异常及 SIGINT/SIGTERM 均停止本次进程组、清理命名空间并归档现有证据。失败返回非零,报告标记不完整;归档失败不会宣称成功。SIGKILL/断电不可捕获,可按终端打印的命名空间名称检查。CPU/RSS 包含模拟端,短时 RSS 不证明长期无泄漏,软件吞吐不代表物理总线带宽。 + +自检: + +```bash +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s benchmarks/stress/tests -p 'test_*.py' +``` diff --git a/benchmarks/stress/run.py b/benchmarks/stress/run.py new file mode 100644 index 0000000..a606108 --- /dev/null +++ b/benchmarks/stress/run.py @@ -0,0 +1,639 @@ +#!/usr/bin/env python3 +"""Build local transport sources and produce an Ubuntu benchmark report + raw archive.""" +import argparse +import csv +import datetime as dt +import fcntl +import hashlib +import io +import json +import math +import os +from pathlib import Path +import platform +import shutil +import signal +import subprocess +import tarfile +import tempfile +import time +import threading + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +RESULTS = HERE.parent / "results" +LARGE_BUFFER = 4 * 1024 * 1024 +LABELS = {'memory-can': '内存回环经典 CAN', 'memory-fd': '内存回环 CAN FD', + 'vcan-can': 'vcan 经典 CAN', 'vcan-fd': 'vcan CAN FD'} + + +def now(): + return dt.datetime.now().astimezone().isoformat() + + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for block in iter(lambda: f.read(1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def save(path, value): + Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n') + + +def capture(command, required=True, timeout=30): + p = subprocess.run(command, capture_output=True, text=True, timeout=timeout) + r = dict(command=command, exit_code=p.returncode, stdout=p.stdout, stderr=p.stderr) + if required and p.returncode: + raise RuntimeError(f'命令失败: {command}\n{p.stderr}') + return r + + +def snapshot(source): + git = lambda *args: capture(['git', '-C', str(source), *args])['stdout'] + # Include tracked content (also dirty/deleted files), nonignored new files and symlink targets. + files = git('ls-files', '-z', '--cached', '--others', '--exclude-standard').split('\0') + manifest = {} + for name in sorted(set(filter(None, files))): + p = source / name + manifest[name] = digest(p) if p.is_file() else ('missing' if not p.exists() else 'directory') + return dict(path=str(source), commit=git('rev-parse', 'HEAD').strip(), + status=git('status', '--porcelain=v1', '--untracked-files=all'), files=manifest, + fingerprint=hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()) + + +def same_source(a, b): + return all(a[k] == b[k] for k in ('commit', 'status', 'fingerprint')) + + +def stop(process, privileged=False): + if process.poll() is not None: + return + for sig in (signal.SIGTERM, signal.SIGKILL): + if privileged: + capture(['sudo', '-n', 'kill', f'-{sig.name[3:]}', '--', f'-{process.pid}'], required=False) + else: + try: + os.killpg(process.pid, sig) + except ProcessLookupError: + pass + try: + process.wait(timeout=5) + return + except subprocess.TimeoutExpired: + continue + raise RuntimeError('无法停止压测进程组') + + +def execute(command, stdout, stderr, timeout, privileged=False): + """No orphan worker/peer processes on timeout or Python SIGINT/SIGTERM.""" + with Path(stdout).open('w') as out, Path(stderr).open('w') as err: + p = subprocess.Popen(command, stdout=out, stderr=err, start_new_session=True) + timed_out = False + try: + p.wait(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = True + stop(p, privileged) + except BaseException: + stop(p, privileged) + raise + return p.returncode, timed_out + + +def assess(record): + """Treat worker exit, full accounting and both kernel socket counters as evidence.""" + r = record.get('result') + errors = [] + if record['timed_out']: + errors.append('超时') + if record['exit_code'] != 0: + errors.append(f"退出码 {record['exit_code']}") + if not isinstance(r, dict) or r.get('pass') is not True: + errors.append('压测校验未通过或 JSON 缺失') + else: + count = r.get('validated', r.get('received', 0)) + keys = ['tx_frames', 'rx_frames', 'submitted' if 'submitted' in r else 'sent'] + if count <= 0 or any(r.get(k) != count for k in keys): + errors.append('完整收发计数不一致') + if record['backend'] == 'vcan' and any(r.get(k) != count for k in ['peer_received', 'peer_sent']): + errors.append('模拟端计数不一致') + if any(r.get(k, -1) != 0 for k in ['overflows', 'route_misses', 'invalid_frames', 'inbox_pending']): + errors.append('库健康计数异常') + if not all(isinstance(r.get(k), (int, float)) and math.isfinite(r[k]) and r[k] >= 0 for k in + ['frames_per_second', 'seconds', 'roundtrip_p99_us_upper', 'cpu_percent_one_core', 'rss_final_kib']): + errors.append('指标缺失') + elif r['seconds'] < record['requested_seconds'] or r['seconds'] <= 0 or not math.isclose(r['frames_per_second'], count/r['seconds'], rel_tol=1e-8): + errors.append('时长或吞吐计算不一致') + if record['backend'] == 'vcan': + probes = record.get('probes', []) + for role in ['session', 'peer']: + opened = [x for x in probes if x.get('role') == role and x.get('event') == 'open'] + closed = [x for x in probes if x.get('role') == role and x.get('event') == 'close'] + if len(opened) != 1 or len(closed) != 1: + errors.append(f'{role} 内核计数缺失') + continue + if any(x['probe_errno'] or x['tune_errno'] for x in opened + closed): + errors.append(f'{role} 内核计数/缓冲设置失败') + if closed[0]['drops'] != opened[0]['drops']: + errors.append(f"{role} 内核丢帧 {closed[0]['drops'] - opened[0]['drops']}") + if record['buffer'] == 'large' and opened[0]['rcvbuf'] < LARGE_BUFFER: + errors.append(f'{role} 接收缓冲不足') + return errors + + +def drops(record, role): + values = {p['event']: p['drops'] for p in record.get('probes', []) if p['role'] == role} + return values['close'] - values['open'] if 'close' in values and 'open' in values else None + + +class Suite: + def __init__(self, source, raw, quick): + self.source, self.raw, self.quick = source, raw, quick + self.build = raw / 'build' + self.ns = f'lbt-stress-{os.getpid()}' + self.created = False + self.watch_stop = threading.Event() + self.watcher = None + self.source_changed = False + self.records, self.confirmed = [], {} + self.meta = dict(started_at=now(), quick=quick, source_before=snapshot(source), namespace=self.ns, + host=dict(uname=platform.uname()._asdict(), os=Path('/etc/os-release').read_text(), + cpu=capture(['lscpu'])['stdout'], compiler=capture(['c++', '--version'])['stdout'], + cpu_affinity=sorted(os.sched_getaffinity(0))), + buffer_requested_bytes=LARGE_BUFFER, errors=[]) + self.flush() + + def flush(self): + save(self.raw / 'runs.json', self.records) + save(self.raw / 'metadata.json', self.meta) + save(self.raw / 'confirmed.json', self.confirmed) + + def ns_cmd(self, cmd): + return ['sudo', '-n', 'ip', 'netns', 'exec', self.ns] + cmd + + def configure(self, cmd, required=True): + r = capture(cmd, required=required) + self.meta.setdefault('configuration', []).append(r) + self.flush() + return r + + def setup(self): + print(f'本次网络命名空间:{self.ns};临时目录:{self.raw}', flush=True) + self.configure(['sudo', '-n', 'true']) + self.meta['interfaces_before'] = capture(['ip', '-j', '-d', 'link', 'show']) + self.configure(['sudo', '-n', 'modprobe', 'vcan']) + self.configure(['sudo', '-n', 'ip', 'netns', 'add', self.ns]) + self.created = True + self.configure(self.ns_cmd(['ip', 'link', 'add', 'vcan0', 'type', 'vcan'])) + self.configure(self.ns_cmd(['ip', 'link', 'set', 'vcan0', 'up'])) + command = ['cmake', '-S', str(HERE), '-B', str(self.build), '-DCMAKE_BUILD_TYPE=Release', + f'-DTRANSPORT_SOURCE={self.source}'] + self.meta['build_command'] = command + for name, cmd in [('configure', command), ('compile', ['cmake', '--build', str(self.build), '-j', str(min(8, os.cpu_count() or 1))])]: + code, timed_out = execute(cmd, self.raw / f'{name}.stdout', self.raw / f'{name}.stderr', 180) + if code or timed_out: + raise RuntimeError(f'{name} 构建失败或超时,请查原始记录') + library, version, linked_source = (self.build / 'linked-library.txt').read_text().splitlines() + library = Path(library) + if linked_source != str(self.source) or not library.resolve().is_relative_to(self.build.resolve()): + raise RuntimeError('链接来源不属于本次本地源码构建') + self.meta['library'] = dict(path=str(library), sha256=digest(library), version=version, source=linked_source) + for worker in ['throughput', 'profile']: + link_map = (self.build / f'{worker}_worker.map').read_text() + linked_paths = [line.split(None, 1)[1] for line in link_map.splitlines() if line.startswith('LOAD ')] + if not any((self.build / path).resolve() == library.resolve() for path in linked_paths): + raise RuntimeError(f'{worker} 链接映射缺少本次构建的库') + commands = json.loads((self.build / 'compile_commands.json').read_text()) + if not any(str(self.source / 'src') in x['file'] for x in commands): + raise RuntimeError('未实际编译所选本地源码') + self.meta['source_after_build'] = snapshot(self.source) + if not same_source(self.meta['source_before'], self.meta['source_after_build']): + raise RuntimeError('构建期间源码变化,测试无效') + code, timed_out = execute([str(self.build / 'throughput_worker'), '--contracts'], + self.raw / 'contracts.json', self.raw / 'contracts.log', 60) + self.meta['contracts'] = dict(exit_code=code, timed_out=timed_out, + result=json.loads((self.raw / 'contracts.json').read_text())) + if code or timed_out or not self.meta['contracts']['result'].get('pass'): + raise RuntimeError('队列边界/恢复契约测试失败') + self.flush() + def watch_source(): + while not self.watch_stop.wait(1): + try: + if not same_source(self.meta['source_before'], snapshot(self.source)): + self.source_changed = True + self.meta['errors'].append('测试期间检测到源码变化,测试无效(即使随后恢复)') + return + except Exception as exc: + self.meta['errors'].append(f'源码监测异常:{exc}') + return + self.watcher = threading.Thread(target=watch_source, daemon=True) + self.watcher.start() + + def mode(self, fd): + self.configure(self.ns_cmd(['ip', 'link', 'set', 'vcan0', 'down'])) + self.configure(self.ns_cmd(['ip', 'link', 'set', 'vcan0', 'mtu', '72' if fd else '16'])) + self.configure(self.ns_cmd(['ip', 'link', 'set', 'vcan0', 'up'])) + + def run(self, backend, fd, phase, seconds, threads, batch, window, buffer='large', peer=None): + seconds = min(seconds, 2) if self.quick else seconds + name = f'{len(self.records):03d}-{phase}-{backend}-{"fd" if fd else "can"}-t{threads}-b{batch}-w{window}' + worker = 'profile' if peer is not None else 'throughput' + cmd = [str(self.build / f'{worker}_worker'), '--seconds', str(seconds), '--threads', str(threads), + '--batch', str(batch), '--window', str(window), '--samples', str(self.raw / f'{name}.csv')] + if fd: + cmd.append('--fd') + if peer is not None and peer: + cmd += ['--raw-peer', '--peer-batch', str(peer)] + if backend == 'vcan': + if peer is None: + cmd += ['--vcan', 'vcan0'] + env = [f'LD_PRELOAD={self.build / "libsocket_probe.so"}', f'LBT_PROBE_LOG={self.raw / (name + ".jsonl")}'] + if buffer == 'large': + env += [f'LBT_SESSION_RCVBUF={LARGE_BUFFER}', f'LBT_PEER_RCVBUF={LARGE_BUFFER}'] + cmd = self.ns_cmd(['env', *env, *cmd]) + print(f'START {name} ({seconds}s)', flush=True) + started = time.monotonic() + before = capture(self.ns_cmd(['ip', '-j', '-s', 'link', 'show', 'vcan0'])) if backend == 'vcan' else None + code, timed_out = execute(cmd, self.raw / f'{name}.json', self.raw / f'{name}.log', seconds + 20, backend == 'vcan') + try: + result = json.loads((self.raw / f'{name}.json').read_text()) + except (ValueError, OSError): + result = None + probe = self.raw / f'{name}.jsonl' + try: + probes = [json.loads(line) for line in probe.read_text().splitlines()] if probe.exists() else [] + except ValueError: + probes = [] + record = dict(name=name, backend=backend, fd=fd, phase=phase, requested_seconds=seconds, + threads=threads, batch=batch, window=window, buffer=buffer, peer=peer, + command=cmd, exit_code=code, timed_out=timed_out, wall_seconds=time.monotonic()-started, + result=result, probes=probes, interface_before=before, + interface_after=capture(self.ns_cmd(['ip', '-j', '-s', 'link', 'show', 'vcan0'])) if backend == 'vcan' else None) + samples = list(csv.DictReader(io.StringIO((self.raw / f'{name}.csv').read_text()))) if (self.raw / f'{name}.csv').exists() else [] + rss = [int(x['rss_kib']) for x in samples] + record['rss_samples_kib'] = dict(min=min(rss), max=max(rss), first=rss[0], last=rss[-1]) if rss else None + record['errors'] = assess(record) + record['pass'] = not record['errors'] + if timed_out or result is None: + self.meta['errors'].append(f'{name} 超时或缺失有效 JSON') + self.records.append(record) + self.flush() + print(f"END {name}: " + (f"PASS {result['frames_per_second']:.0f} fps" if record['pass'] else '; '.join(record['errors'])), flush=True) + return record + + def top(self, backend, fd, phases): + return sorted([r for r in self.records if r['backend'] == backend and r['fd'] == fd and + r['phase'] in phases and r['pass']], key=lambda r: r['result']['frames_per_second'], reverse=True) + + def search(self, backend, fd): + smoke = self.run(backend, fd, 'smoke', 2, 1, 1, 8) + if not smoke['pass']: + raise RuntimeError(f'{backend}/{fd} 基础收发失败') + configs = [(t, b, 8) for b in [1, 8] for t in [1, 2, 4, 8, 16, 32]] + configs += [(t, b, 1) for b in [32, 128] for t in [1, 8]] + if self.quick: + configs = [(1, 8, 8), (8, 128, 1)] + for t, b, w in configs: + self.run(backend, fd, 'screen', 15, t, b, w) + best = self.top(backend, fd, ['screen']) + if not best: + raise RuntimeError('没有无损筛选候选') + best = best[0] + for w in ([1] if self.quick else [1, 4, 16, 32]): + if best['threads'] * best['batch'] * w > 4096 or best['threads'] * w > 1024: + continue + if any(r['backend'] == backend and r['fd'] == fd and (r['threads'], r['batch'], r['window']) == + (best['threads'], best['batch'], w) for r in self.records): + continue + self.run(backend, fd, 'window', 15, best['threads'], best['batch'], w) + for r in self.top(backend, fd, ['screen', 'window'])[:2]: + self.run(backend, fd, 'retest', 30, r['threads'], r['batch'], r['window']) + for candidate in self.top(backend, fd, ['retest'])[:2]: + trials = [] + for _ in range(2): + r = self.run(backend, fd, 'confirm', 60, candidate['threads'], candidate['batch'], candidate['window']) + if not r['pass']: + break + trials.append(r['name']) + if len(trials) == 2: + self.confirmed[f'{backend}-{"fd" if fd else "can"}'] = trials + self.flush() + return + raise RuntimeError(f'{backend}/{fd} 无配置通过两次连续确认') + + def diagnostics(self, fd): + for _ in range(1 if self.quick else 3): + self.run('vcan', fd, 'overload', 15, 8, 8, 8, 'default', peer=0) + for phase, t, b, w, buffer, seconds in [('buffer-control', 8, 8, 8, 'large', 30), + ('window-control', 8, 8, 1, 'default', 15)]: + self.run('vcan', fd, phase, seconds, t, b, w, buffer, peer=0) + for _ in range(1 if self.quick else 2): + for t, w in [(2, 8), (8, 2), (8, 8)]: + self.run('vcan', fd, 'matched', 15, t, 8, w, peer=0) + if fd: + # Identical raw peer code paths: change only read/write vs recvmmsg/sendmmsg. + for peer in [0, 1, 32]: + self.run('vcan', fd, 'peer-comparison', 60, 2, 8, 8, peer=peer) + + def cleanup(self): + self.watch_stop.set() + if self.watcher: + self.watcher.join(timeout=40) + if self.watcher.is_alive(): + self.meta["errors"].append("源码监测未正常结束") + if self.created: + pids = capture(['sudo', '-n', 'ip', 'netns', 'pids', self.ns], required=False) + if pids['stdout'].strip(): + capture(['sudo', '-n', 'kill', '-KILL', *pids['stdout'].split()], required=False) + result = capture(['sudo', '-n', 'ip', 'netns', 'delete', self.ns], required=False) + self.meta['cleanup'] = result + if result['exit_code']: + self.meta['errors'].append('网络命名空间清理失败') + self.created = False + self.meta['source_after'] = snapshot(self.source) + self.meta['source_unchanged'] = not self.source_changed and same_source(self.meta['source_before'], self.meta['source_after']) + if not self.meta['source_unchanged']: + self.meta['errors'].append('测试期间源码变化,测试无效') + self.meta['finished_at'] = now() + self.meta['interfaces_after'] = capture(['ip', '-j', '-d', 'link', 'show'], required=False) + self.flush() + + +def render_report(meta, records, confirmed): + library = meta.get('library', {}) + formal = not meta.get('quick') + valid = len(confirmed) == 4 and meta.get('source_unchanged') is True and not meta.get('errors') + by_name = {r['name']: r for r in records} + failed = [r for r in records if not r['pass']] + lines = [f"# Transport {library.get('version', '未知版本')} 压测报告" + ('' if formal else '(快速验证,非正式结果)'), '', + '## 一、Ubuntu 系统压测', '', '### 测试信息', '', + f"测试时间:{meta.get('started_at')} 至 {meta.get('finished_at', '未完成')}。", + f"状态:{'正式流程完成,四项无损确认有效' if valid and formal else '快速验证完成(不可作为正式性能成绩)' if valid else '流程未完成或测试无效'}。共 {len(records)} 档,失败 {len(failed)} 档,失败档不计入无损成绩。", '', + f"系统:{meta.get('host', {}).get('os', '未知').strip()}。", + f"内核:{meta.get('host', {}).get('uname', {}).get('release', '未知')};逻辑核:{len(meta.get('host', {}).get('cpu_affinity', []))}。", '', + '```text', meta.get('host', {}).get('cpu', '未采集').strip(), '```', '', + f"编译器:{meta.get('host', {}).get('compiler', '未采集').splitlines()[0]}。Release(CMake 默认 -O3 -DNDEBUG),C++17;库自身测试、示例、基准及依赖下载均关闭。", '', + f"源码目录:`{meta.get('source_before', {}).get('path', '未知')}`;版本:`{library.get('version', '未知')}`。", + f"提交:`{meta.get('source_before', {}).get('commit', '未知')}`。工作树:{'有本地变更,见压缩包 metadata.json' if meta.get('source_before', {}).get('status') else '干净'}。", + f"源码 SHA256 指纹:`{meta.get('source_before', {}).get('fingerprint', '未采集')}`;测试期间源码{'保持一致' if meta.get('source_unchanged') else '未能确认一致,结果无效'}。", + f"实际链接库:`{library.get('path', '未构建')}`,SHA256:`{library.get('sha256', '未构建')}`。静态库、链接映射、compile_commands.json、CMakeCache.txt 和构建日志均在原始数据包中。", '', + '### 压测方式', '', + '直接编译所选本地源码,不拉取远程、不使用发布包;每次在新的临时目录构建。内存回环与独立网络命名空间内 vcan 各测经典 CAN 8 字节、CAN FD+BRS 64 字节。', + ('快速验证缩减扫描,仅用每档 2 秒覆盖四条路径、候选复测、两次确认及全部对照;以下均为非正式结果。' if not formal else + '发送线程为 1/2/4/8/16/32,每批 1/8 帧、初始窗口 8 批;补测 1/8 线程、每批 32/128 帧、窗口 1 批,再调整最快候选窗口为 1/4/16/32 批(总在途不超过 4096 帧、1024 批)。每档筛选 15 秒,最快两个无损配置各复测 30 秒,择优连续两次确认 60 秒;若失败则尝试第二候选。'), + '每线程提交窗口内各批,等发送凭据完成并按序收到所有回复后继续。校验 ID、帧标志、长度、序号及负载模式;以正确回复数量÷实际运行秒数计吞吐,一次请求与一次回复只计一次完整收发。经典 CAN 的 8 字节全部为序号及时间戳;FD 其余 56 字节也逐字节校验。', + '正常 vcan 吞吐两端均申请 4 MiB 接收缓冲,只改变本次 socket。另测默认缓冲区 8 线程×8 帧×8 批过载,扩大缓冲和缩小窗口的对照;相同在途量比较线程数,并以相同 FD 配置比较逐帧、批量模拟端。', + 'P99 为 10µs 直方图桶上界(末桶使用实际最大值)。CPU 100% 表示一个逻辑核,包含压测程序、通信库和模拟端的进程 CPU,内核开销计入 system;RSS 为整个进程。软件回环成绩不代表物理 CAN 带宽。', '', + '### 测试结果', ''] + for key, label in LABELS.items(): + trials = [by_name[n] for n in confirmed.get(key, [])] + if len(trials) != 2 or not all(r['pass'] for r in trials): + lines += [f'- **{label}:**未完成两次无损确认,不给出正式成绩。'] + continue + a = trials[0] + results = [r['result'] for r in trials] + f = lambda metric, scale=1, digits=3: ' / '.join(f'{r[metric]/scale:.{digits}f}' for r in results) + counts = ' / '.join(str(r.get('validated', r.get('received'))) for r in results) + rss = [r['rss_samples_kib'] for r in trials if r['rss_samples_kib']] + rss_text = f"{min(x['min'] for x in rss)/1024:.2f}~{max(x['max'] for x in rss)/1024:.2f}" if rss else '缺失' + lines += [f"- **{label}:**两次确认 **{f('frames_per_second', 10000, 2)} 万次完整收发/秒**;" + f"{a['threads']} 线程,每批 {a['batch']} 帧,每线程窗口 {a['window']} 批,总在途上限 {a['threads']*a['batch']*a['window']} 帧。" + f"校验数量 **{counts}**;P99 **{f('roundtrip_p99_us_upper', 1000)} ms**;CPU **{f('cpu_percent_one_core', 100, 2)} 核**;" + f"RSS 采样范围 **{rss_text} MiB**;库内溢出 **0 / 0**;内核丢帧 **{'Session 0 / 0,模拟端 0 / 0' if a['backend']=='vcan' else '不适用(未经过内核 socket)'}**。" + f"原始记录:`{'`、`'.join(confirmed[key])}`。"] + lines += ['', '实际 socket 接收缓冲(内核返回值,可能为申请值的两倍):'] + for key in ['vcan-can', 'vcan-fd']: + rs = [by_name[n] for n in confirmed.get(key, [])] + if rs: + sizes = ['/'.join(f"{p['role']}={p['rcvbuf']} B" for p in r['probes'] if p['event'] == 'open') for r in rs] + lines.append(f"- {LABELS[key]}:" + ';'.join(sizes) + '。') + lines += ['', '### 性能分析', '', '#### 1. 高并发下丢帧', ''] + for fd, label in [(False, '经典 CAN'), (True, 'CAN FD')]: + overloads = [r for r in records if r['fd'] == fd and r['phase'] == 'overload'] + if not overloads: + lines.append(f'{label}:未完成过载测试,证据不足。') + continue + for r in overloads + [x for x in records if x['fd'] == fd and x['phase'] in ['buffer-control', 'window-control']]: + x = r['result'] or {} + buffers = ', '.join(f"{p['role']}={p['rcvbuf']} B" for p in r['probes'] if p['event'] == 'open') + lines += [f"- {label} `{r['name']}`:{'通过' if r['pass'] else '失败'};{r['threads']}×{r['batch']}×{r['window']},{r['buffer']} 缓冲({buffers});" + f"提交/库发/模拟收/模拟回/库收/校验={x.get('submitted', '?')}/{x.get('tx_frames', '?')}/{x.get('peer_received', '?')}/{x.get('peer_sent', '?')}/{x.get('rx_frames', '?')}/{x.get('validated', '?')};" + f"内核丢帧 Session={drops(r, 'session')}、模拟端={drops(r, 'peer')};库内溢出={x.get('overflows', '?')}。"] + lost_roles = {role for role in ['session', 'peer'] if any((drops(r, role) or 0) > 0 for r in overloads)} + controls = [r for r in records if r['fd'] == fd and r['phase'] in ['buffer-control', 'window-control']] + if lost_roles: + roles = '、'.join('Session 接收端' if x == 'session' else '模拟回复接收端' for x in sorted(lost_roles)) + lines += [f"\n{label}:本轮内核计数确认 {roles} 的 socket 接收队列发生丢帧。" + + ('扩大缓冲及减少在途量两项对照均通过,支持突发接收队列过载的解释。' if len(controls) == 2 and all(r['pass'] for r in controls) else '部分对照未通过,不能仅据此排除其他原因。') + + ('这些过载记录未见库内溢出。' if all((r['result'] or {}).get('overflows') == 0 for r in overloads) else '库内溢出情况见各档计数。')] + else: + lines += [f'\n{label}:本轮未记录到默认缓冲的内核丢帧,未复现旧报告中的接收队列丢帧;失败原因需结合本次日志,不能沿用历史结论。'] + lines.append('') + lines += ['#### 2. 性能瓶颈', ''] + for fd, label in [(False, '经典 CAN'), (True, 'CAN FD')]: + groups = [] + for t, w in [(2, 8), (8, 2), (8, 8)]: + rs = [r for r in records if r['fd'] == fd and r['phase'] == 'matched' and r['threads'] == t and r['window'] == w and r['pass']] + if not rs: + continue + avg = lambda k: sum(r['result'][k] for r in rs) / len(rs) + groups.append((t, w, avg('frames_per_second'), avg('roundtrip_p99_us_upper'))) + lines.append(f"- {label}:{t} 线程×8 帧×{w} 批,{t*8*w} 帧在途上限,{len(rs)} 次有效对照;" + f"平均 {avg('frames_per_second')/10000:.2f} 万次/秒,平均 P99 {avg('roundtrip_p99_us_upper')/1000:.3f} ms," + f"CPU {avg('cpu_percent_one_core')/100:.2f} 核,模拟端 CPU {avg('peer_cpu_percent')/100:.2f} 核。") + if len(groups) == 3: + a, b, c = groups + lines.append(f"\n{label}:相同 128 帧在途上限时,2→8 线程吞吐变化 {(b[2]/a[2]-1)*100:+.1f}%;" + f"8 线程将上限从 128→512 帧时,吞吐变化 {(c[2]/b[2]-1)*100:+.1f}%,平均 P99 从 {b[3]/1000:.3f}→{c[3]/1000:.3f} ms。差异受调度与运行波动影响,只支持本次配置间比较。\n") + else: + lines.append(f'{label} 对照有效数据不足,无法评价线程或在途量的影响。\n') + peer_runs = [r for r in records if r['phase'] == 'peer-comparison' and r['pass']] + for r in peer_runs: + x = r['result'] + lines.append(f"- FD 相同 2×8×8、大缓冲配置,{'库模拟端逐帧' if r['peer']==0 else '原始 socket 模拟端逐帧' if r['peer']==1 else '原始 socket 模拟端批量 32 帧'}:" + f"{x['frames_per_second']/10000:.2f} 万次/秒,P99 {x['roundtrip_p99_us_upper']/1000:.3f} ms,模拟端 CPU {x['peer_cpu_percent']/100:.2f} 核(`{r['name']}`)。") + peers = {r['peer']: r for r in peer_runs} + if 1 in peers and 32 in peers: + gain = (peers[32]['result']['frames_per_second']/peers[1]['result']['frames_per_second']-1)*100 + lines += [f'\n仅将原始 socket 模拟端从逐帧改为批量后,本轮吞吐变化 {gain:+.1f}%;' + + ('说明测试端实现影响观测吞吐。' if abs(gain) >= 5 else '本轮未观察到超过 5% 的变化,无法据此认定模拟端是主导瓶颈。')] + else: + lines += ['\nFD 模拟端对照数据不足,不判断批量回复收益。'] + lines += ['本次没有单函数或锁的剖析证据,不能确定唯一瓶颈,也不能把有限参数搜索的最高成绩视为通信库的绝对上限。RSS 仅表示本次有限时长内的观测,不能证明长期无泄漏。', '', '### 失败配置与完整性', ''] + if failed: + for r in failed: + lines.append(f"- `{r['name']}`:" + ';'.join(r['errors']) + f"。原始 stdout/日志:`{r['name']}.json` / `{r['name']}.log`。") + else: + lines.append('本轮已执行档位均通过;仅代表上述实际覆盖范围。') + for error in meta.get('errors', []): + lines.append(f'- 流程异常:{error}') + lines += ['', '原始数据见同目录 `压测原始数据.tar.gz`' + ('(快速验证使用 `快速验证原始数据.tar.gz`)' if not formal else '') + '。' + '压缩包包含本报告副本、逐档 JSON/CSV/日志、socket 计数、运行环境、源码指纹、工具源码、编译参数和实际链接库。归档文件逐项 SHA256 校验后才清理临时目录。', ''] + return '\n'.join(lines) + + +def verify_archive(path, expected_report=None): + with tarfile.open(path, 'r:gz') as archive: + members = {m.name: m for m in archive.getmembers() if m.isfile()} + read = lambda name: archive.extractfile(members[name]).read() + manifest = json.loads(read('manifest.json')) + if set(manifest) != set(members) - {'manifest.json'}: + raise RuntimeError('压缩包文件清单不一致') + for name, sha in manifest.items(): + if hashlib.sha256(read(name)).hexdigest() != sha: + raise RuntimeError(f'归档校验失败: {name}') + meta, runs, confirmed = [json.loads(read(name)) for name in ['metadata.json', 'runs.json', 'confirmed.json']] + for r in runs: + if r['result'] is not None and json.loads(read(r['name'] + '.json')) != r['result']: + raise RuntimeError(f"原始 JSON 与汇总不一致: {r['name']}") + if r['errors'] != assess(r) or r['pass'] != (not assess(r)): + raise RuntimeError(f"有效性判定不一致: {r['name']}") + if meta.get('library'): + lib_member = 'build/' + str(Path(meta['library']['path']).relative_to(Path(meta['library']['path']).parents[1])) + if hashlib.sha256(read(lib_member)).hexdigest() != meta['library']['sha256']: + raise RuntimeError('实际链接库摘要与归档不一致') + for r in runs: + probe_name = r['name'] + '.jsonl' + if probe_name in members and [json.loads(x) for x in read(probe_name).decode().splitlines()] != r['probes']: + raise RuntimeError('socket 原始计数与汇总不一致') + csv_name = r['name'] + '.csv' + if csv_name in members: + rss = [int(x['rss_kib']) for x in csv.DictReader(io.StringIO(read(csv_name).decode()))] + expected = dict(min=min(rss), max=max(rss), first=rss[0], last=rss[-1]) if rss else None + if expected != r['rss_samples_kib']: + raise RuntimeError('RSS 采样与汇总不一致') + for key, names in confirmed.items(): + rs = [r for name in names for r in runs if r['name'] == name] + if key not in LABELS or len(rs) != 2 or len(set(names)) != 2 or not all(r['pass'] and r['phase'] == 'confirm' and r['requested_seconds'] == (2 if meta['quick'] else 60) for r in rs): + raise RuntimeError('确认数据不完整') + report = render_report(meta, runs, confirmed) + if read('report.md').decode() != report or (expected_report is not None and report != expected_report): + raise RuntimeError('报告与本次原始记录不一致') + return dict(records=len(runs), confirmed=len(confirmed), source_unchanged=meta.get('source_unchanged'), errors=meta['errors']) + + +def publish(raw, output, quick, meta, records, confirmed): + report = render_report(meta, records, confirmed) + (raw / 'report.md').write_text(report) + # Include exactly the sources which ran, not __pycache__ or previous results. + tools = raw / 'tool-source' + tools.mkdir(exist_ok=True) + for p in HERE.rglob("*"): + if p.is_file() and p.suffix in ['.py', '.cpp', '.c', '.txt', '.md']: + target = tools / p.relative_to(HERE) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(p, target) + manifest = {str(p.relative_to(raw)): digest(p) for p in raw.rglob('*') if p.is_file() and p.name != 'manifest.json'} + save(raw / 'manifest.json', manifest) + prefix = '快速验证' if quick else '压测' + archive_path, report_path = output / f'{prefix}原始数据.tar.gz', output / f'{prefix}报告.md' + with tempfile.NamedTemporaryFile(prefix='.stress-archive-', dir=output, delete=False) as tmp: + pending = Path(tmp.name) + try: + with tarfile.open(pending, 'w:gz') as archive: + for p in sorted(raw.rglob('*')): + if p.is_file(): + archive.add(p, arcname=str(p.relative_to(raw)), recursive=False) + verify_archive(pending, report) + os.replace(pending, archive_path) + with tempfile.NamedTemporaryFile(mode='w', prefix='.stress-report-', dir=output, delete=False) as tmp: + tmp.write(report) + pending = Path(tmp.name) + os.replace(pending, report_path) + finally: + pending.unlink(missing_ok=True) + print(f'OUTPUT {report_path}\nOUTPUT {archive_path}\n归档及报告一致性校验通过', flush=True) + + +def interrupted(signum, frame): + raise KeyboardInterrupt(f'收到信号 {signum}') + + +def prepare_output(output, quick): + if output is not None: + output = output.resolve() + output.mkdir(parents=True, exist_ok=True) + return output + RESULTS.mkdir(parents=True, exist_ok=True) + stamp = dt.datetime.now().astimezone().strftime('%Y%m%d-%H%M%S') + base = RESULTS / f'{"quick" if quick else "stress"}-{stamp}' + candidate = base + counter = 1 + while True: + try: + candidate.mkdir() + return candidate + except FileExistsError: + candidate = base.with_name(f'{base.name}-{counter:02d}') + counter += 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, default=ROOT, help='本地源码目录,不自动同步远程') + parser.add_argument('--quick', action='store_true', help='2 秒档位快速验证,单独命名,不产生正式成绩') + parser.add_argument('--output', type=Path, help='输出目录;默认 benchmarks/results/{stress|quick}-时间戳/') + parser.add_argument('--verify', type=Path, help='只校验已生成的原始数据包及报告指标') + args = parser.parse_args() + if args.verify: + print(json.dumps(verify_archive(args.verify), ensure_ascii=False)) + return 0 + source = args.source.resolve() + output = prepare_output(args.output, args.quick) + print(f'结果目录:{output}', flush=True) + # Serialize runs against the same source without a workspace lock file. + lock_path = Path(tempfile.gettempdir()) / ('lbt-stress-' + hashlib.sha256(str(source).encode()).hexdigest()[:16] + '.lock') + with lock_path.open('w') as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + print('同一源码已有压测在运行', flush=True) + return 1 + signal.signal(signal.SIGINT, interrupted) + signal.signal(signal.SIGTERM, interrupted) + with tempfile.TemporaryDirectory(prefix='lbt-stress-') as temp: + raw = Path(temp) + suite = None + meta = dict(started_at=now(), quick=args.quick, errors=[]) + try: + for tool in ['cmake', 'c++', 'cc', 'git', 'ip', 'sudo', 'modprobe']: + if not shutil.which(tool): + raise RuntimeError(f'缺少依赖:{tool}') + if platform.system() != 'Linux' or 'Ubuntu' not in Path('/etc/os-release').read_text(): + raise RuntimeError('本工具仅覆盖 Ubuntu Linux') + if not (source / 'CMakeLists.txt').is_file(): + raise RuntimeError(f'无本地源码:{source}') + suite = Suite(source, raw, args.quick) + suite.setup() + for fd in [False, True]: + suite.mode(fd) + for backend in ['memory', 'vcan']: + suite.search(backend, fd) + suite.diagnostics(fd) + except BaseException as exc: + meta = suite.meta if suite else meta + meta['errors'].append(f'{type(exc).__name__}: {exc}') + print(f'FAILED {exc}', flush=True) + finally: + if suite: + try: + suite.cleanup() + except BaseException as exc: + suite.meta['errors'].append(f'清理或源码复核失败:{exc}') + meta, records, confirmed = suite.meta, suite.records, suite.confirmed + else: + records, confirmed = [], {} + meta['finished_at'] = now() + save(raw / 'metadata.json', meta) + save(raw / 'runs.json', records) + save(raw / 'confirmed.json', confirmed) + publish(raw, output, args.quick, meta, records, confirmed) + valid = len(confirmed) == 4 and meta.get('source_unchanged') and not meta['errors'] + return 0 if valid else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/benchmarks/stress/src/profile.cpp b/benchmarks/stress/src/profile.cpp new file mode 100644 index 0000000..06d9423 --- /dev/null +++ b/benchmarks/stress/src/profile.cpp @@ -0,0 +1,420 @@ +// External consumer of the local source tree selected by run.py. +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace can = linkerbot::can; +namespace tr = linkerbot::transport; +using Clock = std::chrono::steady_clock; +using namespace std::chrono_literals; + +struct Distribution { + std::vector buckets = std::vector(20001); + uint64_t count = 0, max_us = 0, sum_us = 0; + void add(uint64_t us) { + ++buckets[std::min(us / 10, 20000)]; + ++count; + sum_us += us; + max_us = std::max(max_us, us); + } + void merge(const Distribution &other) { + for (size_t i = 0; i < buckets.size(); ++i) + buckets[i] += other.buckets[i]; + count += other.count; + sum_us += other.sum_us; + max_us = std::max(max_us, other.max_us); + } + uint64_t quantile(unsigned permille) const { + if (!count) + return 0; + const auto target = (count * permille + 999) / 1000; + uint64_t n = 0; + for (size_t i = 0; i < buckets.size(); ++i) { + n += buckets[i]; + if (n >= target) + return i == 20000 ? max_us : i * 10 + 9; + } + return max_us; + } +}; +uint64_t rss_kib() { + std::ifstream input("/proc/self/statm"); + uint64_t total, resident; + input >> total >> resident; + return resident * static_cast(sysconf(_SC_PAGESIZE)) / 1024; +} +double time_us(const timeval &t) { + return static_cast(t.tv_sec) * 1e6 + static_cast(t.tv_usec); +} +struct RawSocket { + int fd = -1; + ~RawSocket() { + if (fd >= 0) + ::close(fd); + } +}; +int main(int argc, char **argv) { + try { + unsigned seconds = 15, threads = 8, batch_size = 8, window = 8, peer_batch = 1; + bool fd = false, raw_peer = false, latency = true; + std::string samples_path; + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + if (arg == "--fd") { + fd = true; + continue; + } + if (arg == "--raw-peer") { + raw_peer = true; + continue; + } + if (arg == "--no-latency") { + latency = false; + continue; + } + if (arg == "--samples" && i + 1 < argc) { + samples_path = argv[++i]; + continue; + } + if (i + 1 == argc) + throw std::runtime_error("missing option value"); + const auto value = std::stoul(argv[++i]); + if (value > 3600) + throw std::runtime_error("option value too large"); + if (arg == "--seconds") + seconds = value; + else if (arg == "--threads") + threads = value; + else if (arg == "--batch") + batch_size = value; + else if (arg == "--window") + window = value; + else if (arg == "--peer-batch") + peer_batch = value; + else + throw std::runtime_error("unknown option: " + arg); + } + if (!seconds || !threads || threads > 32 || !batch_size || batch_size > 128 || !window || + window > 32 || threads * batch_size * window > 4096 || !peer_batch || peer_batch > 32) + throw std::runtime_error("invalid workload bounds"); + + // First CAN socket = Session, second = simulated peer, for socket_probe.c. + auto session = tr::Session::create( + [&] { return std::make_unique("vcan0", fd); }); + std::vector> inboxes; + for (unsigned t = 0; t < threads; ++t) + inboxes.push_back(session->subscribe_routes({{0x500 + t, false}}, + std::max(128U, batch_size * window))); + std::unique_ptr peer; + RawSocket raw; + if (!raw_peer) + peer = std::make_unique("vcan0", fd); + else { + // Same second socket, no protocol parsing or transport bookkeeping at the simulated + // peer. + raw.fd = ::socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (raw.fd < 0) + throw std::runtime_error("raw peer socket failed"); + int enable = 1; + if (fd && ::setsockopt(raw.fd, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable, sizeof(enable))) + throw std::runtime_error("raw peer FD setup failed"); + timeval timeout{0, 10000}; + if (::setsockopt(raw.fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))) + throw std::runtime_error("raw peer timeout setup failed"); + ifreq ifr{}; + std::strcpy(ifr.ifr_name, "vcan0"); + if (::ioctl(raw.fd, SIOCGIFINDEX, &ifr)) + throw std::runtime_error("raw peer interface failed"); + sockaddr_can addr{}; + addr.can_family = AF_CAN; + addr.can_ifindex = ifr.ifr_ifindex; + if (::bind(raw.fd, reinterpret_cast(&addr), sizeof(addr))) + throw std::runtime_error("raw peer bind failed"); + } + std::vector roundtrips(threads), queues(threads), dispatches(threads); + std::ofstream samples(samples_path); + if (samples.is_open()) + samples << "elapsed_s,validated,rss_kib,pending_tx,tx_high_water,inbox_high_water\n"; + rusage usage_start{}, usage_end{}; + std::vector producer_usage(threads); + rusage peer_usage{}; + std::atomic failed{false}, go{false}, stop_peer{false}; + std::atomic peer_rx{0}, peer_tx{0}, validated{0}, submitted{0}; + std::mutex error_mutex; + std::string error; + const auto fail = [&](const std::string &message) { + std::lock_guard lock(error_mutex); + if (error.empty()) + error = message; + failed.store(true); + }; + std::thread echo([&] { + pthread_setname_np(pthread_self(), "echo-peer"); + try { + std::array frames{}; + std::array iovs{}; + std::array messages{}; + for (unsigned i = 0; i < peer_batch; ++i) { + iovs[i] = {&frames[i], sizeof(canfd_frame)}; + messages[i].msg_hdr.msg_iov = &iovs[i]; + messages[i].msg_hdr.msg_iovlen = 1; + } + while (!stop_peer.load()) { + if (raw_peer && peer_batch > 1) { + for (unsigned i = 0; i < peer_batch; ++i) + iovs[i].iov_len = sizeof(canfd_frame); + const int n = ::recvmmsg(raw.fd, messages.data(), peer_batch, + MSG_WAITFORONE, nullptr); + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) + continue; + if (n < 0) + throw std::runtime_error("recvmmsg failed"); + for (int i = 0; i < n; ++i) { + if (messages[i].msg_len != (fd ? CANFD_MTU : CAN_MTU) || + frames[i].can_id < 0x100 || frames[i].can_id >= 0x100 + threads) + throw std::runtime_error("batch peer unexpected frame"); + ++peer_rx; + frames[i].can_id += 0x400; + iovs[i].iov_len = messages[i].msg_len; + } + int sent = 0; + while (sent < n) { + const int k = ::sendmmsg(raw.fd, messages.data() + sent, n - sent, 0); + if (k <= 0) + throw std::runtime_error("sendmmsg failed"); + sent += k; + peer_tx.fetch_add(k); + } + continue; + } + if (raw_peer) { + canfd_frame f{}; + const ssize_t n = ::read(raw.fd, &f, sizeof(f)); + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) + continue; + if (n != static_cast(fd ? CANFD_MTU : CAN_MTU)) + throw std::runtime_error("raw peer read failed"); + if (f.can_id < 0x100 || f.can_id >= 0x100 + threads) + throw std::runtime_error("raw peer bad id"); + ++peer_rx; + f.can_id += 0x400; + if (::write(raw.fd, &f, n) != n) + throw std::runtime_error("raw peer write failed"); + ++peer_tx; + continue; + } + auto message = peer->read(); + if (!message) + continue; + if (message->id < 0x100 || message->id >= 0x100 + threads) + throw std::runtime_error("unexpected request ID"); + ++peer_rx; + message->id += 0x400; + peer->write(*message); + ++peer_tx; + } + } catch (const std::exception &e) { + fail(std::string("peer: ") + e.what()); + } + getrusage(RUSAGE_THREAD, &peer_usage); + }); + Clock::time_point start; + std::vector producers; + for (unsigned t = 0; t < threads; ++t) { + producers.emplace_back([&, t] { + const auto thread_name = "producer-" + std::to_string(t); + pthread_setname_np(pthread_self(), thread_name.c_str()); + while (!go.load(std::memory_order_acquire)) + std::this_thread::yield(); + try { + uint32_t next_send = 0, next_receive = 0; + while (!failed.load() && Clock::now() < start + std::chrono::seconds(seconds)) { + std::vector receipts; + receipts.reserve(window); + for (unsigned w = 0; w < window; ++w) { + tr::MessageBatch batch; + batch.frames.reserve(batch_size); + for (unsigned b = 0; b < batch_size; ++b) { + can::Message message; + message.id = 0x100 + t; + message.dlc = fd ? 64 : 8; + message.is_fd = message.is_brs = fd; + const uint32_t sequence = next_send++; + std::memcpy(message.data.data(), &sequence, sizeof(sequence)); + const uint32_t stamp = + latency + ? static_cast( + std::chrono::duration_cast( + Clock::now() - start) + .count()) + : 0; + std::memcpy(message.data.data() + 4, &stamp, 4); + for (unsigned k = 8; k < message.dlc; ++k) + message.data[k] = static_cast(sequence + k + t); + batch.frames.push_back(message); + } + receipts.push_back(session->submit(std::move(batch))); + submitted.fetch_add(batch_size, std::memory_order_relaxed); + } + for (const auto &receipt : receipts) { + const auto result = receipt.wait_until(Clock::now() + 5s); + if (result.outcome != tr::SendOutcome::dispatched || + result.sent_frames != batch_size) + throw std::runtime_error("incomplete send"); + if (latency && result.claimed_at && result.completed_at) { + queues[t].add(std::chrono::duration_cast( + *result.claimed_at - result.accepted_at) + .count()); + dispatches[t].add( + std::chrono::duration_cast( + *result.completed_at - *result.claimed_at) + .count()); + } + } + for (unsigned n = 0; n < window * batch_size; ++n) { + const auto reply = inboxes[t]->receive_until(Clock::now() + 5s); + if (!reply) + throw std::runtime_error("reply timeout"); + const auto &message = reply->message; + if (message.id != 0x500 + t || message.is_extended || + message.dlc != (fd ? 64 : 8) || message.is_fd != fd || + message.is_brs != fd) + throw std::runtime_error("reply metadata mismatch"); + uint32_t sequence; + std::memcpy(&sequence, message.data.data(), sizeof(sequence)); + if (sequence != next_receive) + throw std::runtime_error( + "sequence mismatch: expected=" + std::to_string(next_receive) + + ", received=" + std::to_string(sequence)); + ++next_receive; + uint32_t stamp; + std::memcpy(&stamp, message.data.data() + 4, 4); + if (latency) + roundtrips[t].add( + static_cast( + std::chrono::duration_cast( + Clock::now() - start) + .count()) - + stamp); + for (unsigned k = 8; k < message.dlc; ++k) + if (message.data[k] != static_cast(sequence + k + t)) + throw std::runtime_error("payload mismatch"); + validated.fetch_add(1, std::memory_order_relaxed); + } + } + } catch (const std::exception &e) { + fail("producer " + std::to_string(t) + ": " + e.what()); + } + getrusage(RUSAGE_THREAD, &producer_usage[t]); + }); + } + getrusage(RUSAGE_SELF, &usage_start); + start = Clock::now(); + go.store(true, std::memory_order_release); + for (unsigned second = 1; second <= seconds && !failed.load(); ++second) { + std::this_thread::sleep_until(start + std::chrono::seconds(second)); + const auto h = session->health(); + size_t inbox_high = 0; + for (const auto &inbox : inboxes) + inbox_high = std::max(inbox_high, inbox->health().high_water); + if (samples.is_open()) { + samples << second << ',' << validated.load() << ',' << rss_kib() << ',' + << h.pending_tx << ',' << h.queue_high_water << ',' << inbox_high << '\n'; + samples.flush(); + } + } + for (auto &producer : producers) + producer.join(); + getrusage(RUSAGE_SELF, &usage_end); + const auto elapsed = std::chrono::duration(Clock::now() - start).count(); + // Allow any remaining submitted frames to reach the kernel readers. + // This is shutdown only: receiving is never deliberately delayed under load. + std::this_thread::sleep_for(30ms); + stop_peer.store(true); + echo.join(); + if (peer) + peer->close(); + if (raw.fd >= 0) { + ::close(raw.fd); + raw.fd = -1; + } + Distribution rt, queue, dispatch; + for (unsigned t = 0; t < threads; ++t) { + rt.merge(roundtrips[t]); + queue.merge(queues[t]); + dispatch.merge(dispatches[t]); + } + const double user_us = time_us(usage_end.ru_utime) - time_us(usage_start.ru_utime); + const double system_us = time_us(usage_end.ru_stime) - time_us(usage_start.ru_stime); + double producer_cpu_us = 0; + for (const auto &u : producer_usage) + producer_cpu_us += time_us(u.ru_utime) + time_us(u.ru_stime); + const auto health = session->health(); + unsigned inbox_pending = 0; + for (const auto &inbox : inboxes) + inbox_pending += inbox->health().pending; + const bool complete = + !failed.load() && submitted == validated && submitted == health.tx_frames && + submitted == health.rx_frames && submitted == peer_rx && submitted == peer_tx && + health.pending_tx == 0 && health.overflows == 0 && health.route_misses == 0 && + health.invalid_frames == 0 && health.last_error.empty() && inbox_pending == 0; + session->close(); + tr::Session::drain_deferred_cleanup(); + std::cout << std::setprecision(12) << "{\"pass\":" << (complete ? "true" : "false") + << ",\"seconds\":" << elapsed << ",\"submitted\":" << submitted.load() + << ",\"tx_frames\":" << health.tx_frames + << ",\"peer_received\":" << peer_rx.load() << ",\"peer_sent\":" << peer_tx.load() + << ",\"rx_frames\":" << health.rx_frames << ",\"validated\":" << validated.load() + << ",\"inbox_pending\":" << inbox_pending << ",\"overflows\":" << health.overflows + << ",\"route_misses\":" << health.route_misses + << ",\"invalid_frames\":" << health.invalid_frames + << ",\"frames_per_second\":" << static_cast(validated.load()) / elapsed + << ",\"cpu_percent_one_core\":" << (user_us + system_us) / elapsed / 10000 + << ",\"user_cpu_percent\":" << user_us / elapsed / 10000 + << ",\"system_cpu_percent\":" << system_us / elapsed / 10000 + << ",\"peer_cpu_percent\":" + << (time_us(peer_usage.ru_utime) + time_us(peer_usage.ru_stime)) / elapsed / 10000 + << ",\"producers_cpu_percent\":" << producer_cpu_us / elapsed / 10000 + << ",\"voluntary_context_switches\":" << usage_end.ru_nvcsw - usage_start.ru_nvcsw + << ",\"involuntary_context_switches\":" + << usage_end.ru_nivcsw - usage_start.ru_nivcsw + << ",\"minor_faults\":" << usage_end.ru_minflt - usage_start.ru_minflt + << ",\"major_faults\":" << usage_end.ru_majflt - usage_start.ru_majflt + << ",\"rss_peak_kib\":" << usage_end.ru_maxrss + << ",\"rss_final_kib\":" << rss_kib() << ",\"roundtrip_count\":" << rt.count + << ",\"roundtrip_p50_us_upper\":" << rt.quantile(500) + << ",\"roundtrip_p95_us_upper\":" << rt.quantile(950) + << ",\"roundtrip_p99_us_upper\":" << rt.quantile(990) + << ",\"roundtrip_p999_us_upper\":" << rt.quantile(999) + << ",\"roundtrip_max_us\":" << rt.max_us + << ",\"batch_queue_p99_us_upper\":" << queue.quantile(990) + << ",\"batch_dispatch_p99_us_upper\":" << dispatch.quantile(990) + << ",\"queue_high_water\":" << health.queue_high_water + << ",\"raw_peer\":" << (raw_peer ? "true" : "false") + << ",\"peer_batch\":" << peer_batch + << ",\"latency_enabled\":" << (latency ? "true" : "false") << "}\n"; + if (!complete) + std::cerr << (error.empty() ? "frame accounting or health check failed" : error) + << '\n'; + return complete ? 0 : 1; + } catch (const std::exception &e) { + std::cerr << "ERROR: " << e.what() << '\n'; + return 2; + } +} diff --git a/benchmarks/stress/src/socket_probe.c b/benchmarks/stress/src/socket_probe.c new file mode 100644 index 0000000..ca33829 --- /dev/null +++ b/benchmarks/stress/src/socket_probe.c @@ -0,0 +1,78 @@ +// glibc requires this exact feature-test macro for the Linux socket extensions. +// NOLINTNEXTLINE(bugprone-reserved-identifier) +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* No per-frame hooks. Observe the original binary's sockets at open/close. + * Role numbering follows stress.cpp: first CAN socket Session, second peer. + * SO_RCVBUFFORCE changes only this socket; no global sysctl changes. */ +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static int roles[65536]; +static int next_role; +static void record(int fd, int role, const char *event, int tune_errno) { + int saved = errno; + uint32_t mem[SK_MEMINFO_VARS] = {0}; + socklen_t size = sizeof(mem); + int rc = getsockopt(fd, SOL_SOCKET, SO_MEMINFO, mem, &size); + int probe_errno = rc ? errno : 0; + const char *path = getenv("LBT_PROBE_LOG"); + if (path) { + char line[768]; + // Linux does not provide Annex K snprintf_s; bound and check this output. + // NOLINTBEGIN(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + int n = + snprintf(line, sizeof(line), + "{\"event\":\"%s\",\"role\":\"%s\",\"fd\":%d,\"rcvbuf\":%u,\"rmem_alloc\":%u," + "\"drops\":%u,\"probe_errno\":%d,\"tune_errno\":%d}\n", + event, role == 1 ? "session" : "peer", fd, mem[SK_MEMINFO_RCVBUF], + mem[SK_MEMINFO_RMEM_ALLOC], mem[SK_MEMINFO_DROPS], probe_errno, tune_errno); + // NOLINTEND(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + if (n > 0 && (size_t)n < sizeof(line)) { + int out = (int)syscall(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_APPEND, 0666); + if (out >= 0) { + syscall(SYS_write, out, line, (size_t)n); + syscall(SYS_close, out); + } + } + } + errno = saved; +} +int socket(int domain, int type, int protocol) { + int fd = (int)syscall(SYS_socket, domain, type, protocol); + if (fd >= 0 && fd < 65536 && domain == PF_CAN) { + pthread_mutex_lock(&lock); + int role = ++next_role; + roles[fd] = role; + const char *s = getenv(role == 1 ? "LBT_SESSION_RCVBUF" : "LBT_PEER_RCVBUF"); + int tune_errno = 0; + if (s) { + int bytes = atoi(s); + if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &bytes, sizeof(bytes))) + tune_errno = errno; + } + record(fd, role, "open", tune_errno); + pthread_mutex_unlock(&lock); + } + return fd; +} +int close(int fd) { + if (fd >= 0 && fd < 65536) { + pthread_mutex_lock(&lock); + if (roles[fd]) { + record(fd, roles[fd], "close", 0); + roles[fd] = 0; + } + pthread_mutex_unlock(&lock); + } + return (int)syscall(SYS_close, fd); +} diff --git a/benchmarks/stress/src/throughput.cpp b/benchmarks/stress/src/throughput.cpp new file mode 100644 index 0000000..d059d08 --- /dev/null +++ b/benchmarks/stress/src/throughput.cpp @@ -0,0 +1,478 @@ +// Linux-only offline load generator. The bounded echo transport deliberately +// keeps no send history, so the harness does not accumulate memory with runtime. +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std::chrono_literals; +namespace can = linkerbot::can; +namespace tr = linkerbot::transport; +using Clock = std::chrono::steady_clock; + +namespace { + void check(bool value, const char *message) { + if (!value) + throw std::runtime_error(message); + } + + class EchoTransport final : public can::CANTransport { + public: + explicit EchoTransport(bool native_batch) : native_batch_(native_batch) {} + std::optional read() override { + std::unique_lock lock(mutex_); + cv_.wait_for(lock, 10ms, [&] { return closed_ || count_ != 0; }); + if (closed_) + throw can::ClosedError("echo closed"); + if (count_ == 0) + return std::nullopt; + auto frame = ring_[head_]; + head_ = (head_ + 1) % ring_.size(); + --count_; + return frame; + } + void write(const can::Message &frame) override { + { + std::lock_guard lock(mutex_); + push(frame); + } + cv_.notify_one(); + } + void write_batch(const std::vector &frames) override { + { + std::lock_guard lock(mutex_); + for (const auto &frame : frames) + push(frame); + } + cv_.notify_one(); + } + bool prefers_write_batch() const override { + return native_batch_; + } + void close() override { + { + std::lock_guard lock(mutex_); + closed_ = true; + } + cv_.notify_all(); + } + + private: + void push(const can::Message &frame) { + if (closed_) + throw can::ClosedError("echo closed"); + if (count_ == ring_.size()) + throw can::QueueFullError("echo ring full"); + ring_[(head_ + count_) % ring_.size()] = frame; + ++count_; + } + std::array ring_{}; + size_t head_ = 0; + size_t count_ = 0; + bool closed_ = false; + bool native_batch_; + std::mutex mutex_; + std::condition_variable cv_; + }; + + uint64_t rss_kib() { + std::ifstream input("/proc/self/statm"); + uint64_t virtual_pages = 0, resident_pages = 0; + check(static_cast(input >> virtual_pages >> resident_pages), "cannot read RSS"); + return resident_pages * static_cast(sysconf(_SC_PAGESIZE)) / 1024; + } + + uint64_t cpu_ns() { + timespec time{}; + check(clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time) == 0, "cannot read CPU time"); + return static_cast(time.tv_sec) * 1000000000ULL + time.tv_nsec; + } + + struct Worker { + // 10 us histogram buckets, capped at 200 ms. Max is tracked separately. + std::vector histogram = std::vector(20001, 0); + std::atomic received{0}; + uint64_t sent = 0; + uint64_t max_us = 0; + }; + + can::Message plain_frame(uint32_t id) { + can::Message frame; + frame.id = id; + frame.dlc = 8; + return frame; + } + + void contracts() { + // Deterministic overload, rather than relying on scheduler timing. + can::FakeTransport *fake = nullptr; + auto session = tr::Session::create( + [&] { + auto transport = std::make_unique(); + fake = transport.get(); + return transport; + }, + 128); + fake->arm_tx_gate(); + auto active = session->submit({{plain_frame(0x100)}}); + if (!fake->wait_until_tx_entered(2s)) { + fake->release_tx_gate(); + throw std::runtime_error("writer did not enter gate"); + } + std::vector pending; + size_t rejected = 0; + try { + for (size_t i = 0; i < 1000; ++i) { + try { + pending.push_back(session->submit({{plain_frame(0x100)}})); + } catch (const can::QueueFullError &) { + ++rejected; + } + } + } catch (...) { + fake->release_tx_gate(); + throw; + } + fake->release_tx_gate(); + check(pending.size() == 128 && rejected == 872, "TX capacity accounting failed"); + check(active.wait_until(Clock::now() + 5s).sent_frames == 1, "active send failed"); + for (auto &receipt : pending) + check(receipt.wait_until(Clock::now() + 5s).sent_frames == 1, "queued send failed"); + check(session->health().pending_tx == 0, "TX did not drain"); + + auto inbox = session->subscribe_routes({{0x101, false}}, 16); + auto barrier = session->subscribe_routes({{0x102, false}}, 1); + for (size_t i = 0; i < 1000; ++i) + fake->inject(plain_frame(0x101)); + fake->inject(plain_frame(0x102)); + check(barrier->receive_until(Clock::now() + 5s).has_value(), "RX barrier timed out"); + check(inbox->health().overflow == 984 && inbox->health().pending == 16, + "RX overflow accounting failed"); + size_t drained = 0; + while (inbox->try_receive()) + ++drained; + check(drained == 16, "RX bounded inbox drain failed"); + session->close(); + + // Recreate transports after injected write failures. Raw pointer is used + // only while its generation is live; recover replaces it synchronously. + auto recoverable = tr::Session::create([&] { + auto transport = std::make_unique(); + transport->on_request( + 0x100, [](const can::Message &m) { return std::vector{m}; }); + fake = transport.get(); + return transport; + }); + for (size_t i = 0; i < 100; ++i) { + auto route = recoverable->subscribe_routes({{0x100, false}}); + auto good = recoverable->submit({{plain_frame(0x100)}}); + check(good.wait_until(Clock::now() + 2s).sent_frames == 1, "recovered send failed"); + check(route->receive_until(Clock::now() + 2s).has_value(), "recovered reply failed"); + const auto generation = recoverable->health().generation; + fake->fail_writes("offline stress injected write failure"); + auto bad = recoverable->submit({{plain_frame(0x100)}}); + bool failed = false; + try { + (void)bad.wait_until(Clock::now() + 2s); + } catch (const can::TransportIOError &) { + failed = true; + } + check(failed && bad.result().outcome == tr::SendOutcome::failed, + "write failure was not reported"); + check(recoverable->recover(generation) > generation, "generation did not advance"); + check(route->health().closed, "recovery did not close old route"); + } + check(recoverable->health().recoveries == 100, "recovery count mismatch"); + recoverable->close(); + tr::Session::drain_deferred_cleanup(); + std::cout << "{\"pass\":true,\"tx_accepted\":129,\"tx_rejected\":872," + "\"rx_kept\":16,\"rx_overflow\":984,\"recoveries\":100}\n"; + } +} // namespace + +int main(int argc, char **argv) { + try { + size_t threads = 8, batch_size = 8, window = 8; + int seconds = 30; + bool fd = false, native_batch = false; + std::string samples_path, vcan_interface; + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + if (arg == "--contracts") { + contracts(); + return 0; + } + if (arg == "--fd") { + fd = true; + continue; + } + if (arg == "--native-batch") { + native_batch = true; + continue; + } + check(i + 1 < argc, "missing argument value"); + const std::string value = argv[++i]; + if (arg == "--seconds") + seconds = std::stoi(value); + else if (arg == "--threads") + threads = std::stoul(value); + else if (arg == "--batch") + batch_size = std::stoul(value); + else if (arg == "--window") + window = std::stoul(value); + else if (arg == "--samples") + samples_path = value; + else if (arg == "--vcan") + vcan_interface = value; + else + throw std::runtime_error("unknown argument: " + arg); + } + check(seconds > 0 && seconds <= 3600, "seconds must be 1..3600"); + check(threads > 0 && threads <= 64, "threads must be 1..64"); + check(batch_size > 0 && batch_size <= 128 && window > 0 && window <= 32, + "batch must be 1..128 and window must be 1..32"); + check(threads * batch_size * window <= 4096 && threads * window <= 1024, + "outstanding traffic exceeds bounded test capacity"); + check(vcan_interface.empty() || vcan_interface == "vcan0", + "virtual mode permits only vcan0; use a dedicated network namespace"); + check(vcan_interface.empty() || !native_batch, + "SocketCAN uses individual frame writes; --native-batch is in-memory only"); + std::ofstream samples; + if (!samples_path.empty()) { + samples.open(samples_path); + check(samples.good(), "cannot open sample output"); + samples << "elapsed_s,received_frames,rss_kib,cpu_ns,pending_tx,queue_high_water\n"; + } + auto session = tr::Session::create([&] { + if (!vcan_interface.empty()) + return std::unique_ptr( + std::make_unique(vcan_interface, fd)); + return std::unique_ptr( + std::make_unique(native_batch)); + }); + std::vector> inboxes; + for (size_t t = 0; t < threads; ++t) + inboxes.push_back(session->subscribe_routes( + {{static_cast((vcan_interface.empty() ? 0x100 : 0x500) + t), false}}, + std::max(128, window * batch_size))); + std::vector workers(threads); + std::atomic go{false}, failed{false}; + Clock::time_point start; + std::string error; + std::mutex error_mutex; + std::atomic peer_stop{false}; + std::atomic peer_received{0}, peer_sent{0}; + std::unique_ptr peer; + std::thread peer_thread; + // The dedicated namespace contains just these two CAN sockets. Raw CAN + // defaults exclude a socket's own TX, so requests and replies do not loop. + if (!vcan_interface.empty()) { + peer = std::make_unique(vcan_interface, fd); + peer_thread = std::thread([&] { + try { + while (!peer_stop.load()) { + auto frame = peer->read(); + if (!frame) + continue; + check(frame->id >= 0x100 && frame->id < 0x100 + threads, + "unexpected frame on dedicated vcan interface"); + ++peer_received; + frame->id += 0x400; + peer->write(*frame); + ++peer_sent; + } + } catch (const std::exception &exception) { + failed.store(true); + std::lock_guard lock(error_mutex); + if (error.empty()) + error = exception.what(); + } + }); + } + std::vector senders; + for (size_t t = 0; t < threads; ++t) { + senders.emplace_back([&, t] { + while (!go.load(std::memory_order_acquire)) + std::this_thread::sleep_for(1ms); + try { + uint32_t next_send = 0, next_receive = 0; + std::vector receipts; + receipts.reserve(window); + while (!failed.load() && Clock::now() < start + std::chrono::seconds(seconds)) { + receipts.clear(); + for (size_t w = 0; w < window; ++w) { + tr::MessageBatch batch; + batch.frames.reserve(batch_size); + for (size_t b = 0; b < batch_size; ++b) { + auto frame = plain_frame(static_cast(0x100 + t)); + frame.is_fd = fd; + frame.is_brs = fd; + frame.dlc = fd ? 64 : 8; + const uint32_t sequence = next_send++; + const auto stamp = static_cast( + std::chrono::duration_cast( + Clock::now() - start) + .count()); + std::memcpy(frame.data.data(), &sequence, 4); + std::memcpy(frame.data.data() + 4, &stamp, 4); + for (size_t k = 8; k < frame.dlc; ++k) + frame.data[k] = static_cast(sequence + k + t); + batch.frames.push_back(frame); + } + receipts.push_back(session->submit(std::move(batch))); + workers[t].sent += batch_size; + } + for (auto &receipt : receipts) { + const auto result = receipt.wait_until(Clock::now() + 5s); + check(result.outcome == tr::SendOutcome::dispatched && + result.sent_frames == batch_size, + "incomplete send receipt"); + } + for (size_t n = 0; n < window * batch_size; ++n) { + auto routed = inboxes[t]->receive_until(Clock::now() + 5s); + check(routed.has_value(), "reply timeout"); + const auto &frame = routed->message; + check(frame.id == (vcan_interface.empty() ? 0x100 : 0x500) + t && + !frame.is_extended && frame.dlc == (fd ? 64 : 8) && + frame.is_fd == fd && frame.is_brs == fd, + "reply frame metadata corrupted"); + uint32_t sequence = 0, stamp = 0; + std::memcpy(&sequence, frame.data.data(), 4); + std::memcpy(&stamp, frame.data.data() + 4, 4); + check(sequence == next_receive++, "lost, duplicate or reordered reply"); + for (size_t k = 8; k < frame.dlc; ++k) + check(frame.data[k] == static_cast(sequence + k + t), + "reply payload corrupted"); + const auto now_us = static_cast( + std::chrono::duration_cast(Clock::now() - + start) + .count()); + check(now_us >= stamp, "reply timestamp invalid"); + const auto latency = now_us - stamp; + ++workers[t].histogram[std::min(latency / 10, 20000)]; + workers[t].max_us = std::max(workers[t].max_us, latency); + workers[t].received.fetch_add(1, std::memory_order_relaxed); + } + } + } catch (const std::exception &exception) { + failed.store(true); + std::lock_guard lock(error_mutex); + if (error.empty()) + error = exception.what(); + } + }); + } + const auto cpu_start = cpu_ns(); + start = Clock::now(); + go.store(true, std::memory_order_release); + for (int second = 1; second <= seconds && !failed.load(); ++second) { + std::this_thread::sleep_until(start + std::chrono::seconds(second)); + uint64_t received = 0; + for (const auto &worker : workers) + received += worker.received.load(); + const auto health = session->health(); + if (samples.is_open()) { + samples << second << ',' << received << ',' << rss_kib() << ',' + << cpu_ns() - cpu_start << ',' << health.pending_tx << ',' + << health.queue_high_water << '\n'; + samples.flush(); + } + if (second % 30 == 0) + std::cerr << "progress " << second << '/' << seconds << "s, replies=" << received + << '\n'; + } + for (auto &sender : senders) + sender.join(); + const auto elapsed = std::chrono::duration(Clock::now() - start).count(); + const auto cpu_elapsed = cpu_ns() - cpu_start; + peer_stop.store(true); + if (peer_thread.joinable()) + peer_thread.join(); + if (peer) + peer->close(); + uint64_t sent = 0, received = 0, max_us = 0; + std::vector histogram(20001, 0); + for (const auto &worker : workers) { + sent += worker.sent; + received += worker.received.load(); + max_us = std::max(max_us, worker.max_us); + for (size_t k = 0; k < histogram.size(); ++k) + histogram[k] += worker.histogram[k]; + } + const auto health = session->health(); + bool complete = !failed.load() && sent > 0 && sent == received && + sent == health.tx_frames && sent == health.rx_frames && + (vcan_interface.empty() || + (peer_received.load() == sent && peer_sent.load() == received)) && + health.overflows == 0 && health.route_misses == 0 && + health.invalid_frames == 0 && health.pending_tx == 0 && + health.last_error.empty(); + uint64_t inbox_pending = 0, inbox_overflows = 0; + for (const auto &inbox : inboxes) { + inbox_pending += inbox->health().pending; + inbox_overflows += inbox->health().overflow; + } + complete = complete && inbox_pending == 0 && inbox_overflows == 0; + if (!complete) + std::cerr << "FAIL: " << (error.empty() ? "frame accounting or health mismatch" : error) + << '\n'; + auto percentile = [&](uint64_t percent) { + const auto target = (received * percent + 99) / 100; + uint64_t count = 0; + for (size_t k = 0; k < histogram.size(); ++k) { + count += histogram[k]; + if (count >= target) + return k == 20000 ? max_us : static_cast(k * 10 + 9); + } + return max_us; + }; + const auto closing = Clock::now(); + session->close(); + tr::Session::drain_deferred_cleanup(); + const auto close_us = + std::chrono::duration_cast(Clock::now() - closing).count(); + std::cout << std::setprecision(12) << "{\"pass\":" << (complete ? "true" : "false") + << ",\"threads\":" << threads << ",\"batch\":" << batch_size + << ",\"window\":" << window << ",\"fd\":" << (fd ? "true" : "false") + << ",\"native_batch\":" << (native_batch ? "true" : "false") << ",\"backend\":\"" + << (vcan_interface.empty() ? "memory" : "vcan") << "\"" + << ",\"peer_received\":" << peer_received.load() + << ",\"peer_sent\":" << peer_sent.load() << ",\"seconds\":" << elapsed + << ",\"sent\":" << sent << ",\"received\":" << received + << ",\"frames_per_second\":" << static_cast(received) / elapsed + << ",\"cpu_percent_one_core\":" + << static_cast(cpu_elapsed) / (elapsed * 1e7) + << ",\"roundtrip_p50_us_upper\":" << percentile(50) + << ",\"roundtrip_p95_us_upper\":" << percentile(95) + << ",\"roundtrip_p99_us_upper\":" << percentile(99) + << ",\"roundtrip_max_us\":" << max_us + << ",\"queue_high_water\":" << health.queue_high_water + << ",\"overflows\":" << health.overflows << ",\"tx_frames\":" << health.tx_frames + << ",\"rx_frames\":" << health.rx_frames + << ",\"route_misses\":" << health.route_misses + << ",\"invalid_frames\":" << health.invalid_frames + << ",\"inbox_pending\":" << inbox_pending + << ",\"inbox_overflows\":" << inbox_overflows + << ",\"rss_final_kib\":" << rss_kib() << ",\"close_us\":" << close_us << "}\n"; + return complete ? 0 : 1; + } catch (const std::exception &error) { + std::cerr << "FAIL: " << error.what() << '\n'; + return 1; + } +} diff --git a/benchmarks/stress/tests/test_run.py b/benchmarks/stress/tests/test_run.py new file mode 100644 index 0000000..7b22aff --- /dev/null +++ b/benchmarks/stress/tests/test_run.py @@ -0,0 +1,134 @@ +"""Failure evidence, process cleanup and report/archive integrity regressions.""" +import copy +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import unittest +from unittest.mock import patch + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import run + + +def record(): + return dict(name='trial', backend='vcan', fd=False, phase='confirm', requested_seconds=60, + threads=2, batch=8, window=8, buffer='large', peer=None, + exit_code=0, timed_out=False, + result=dict(**{k: 100 for k in ['sent', 'received', 'tx_frames', 'rx_frames', 'peer_received', 'peer_sent']}, + **{k: 0 for k in ['overflows', 'route_misses', 'invalid_frames', 'inbox_pending']}, + **{'pass': True}, frames_per_second=100/60, seconds=60, + roundtrip_p99_us_upper=99, cpu_percent_one_core=100, rss_final_kib=4096), + probes=[dict(event=event, role=role, rcvbuf=8388608, drops=0, tune_errno=0, probe_errno=0) + for role in ['session', 'peer'] for event in ['open', 'close']], + rss_samples_kib=dict(min=4096, max=4096, first=4096, last=4096)) + + +class EvidenceTests(unittest.TestCase): + def test_default_output_is_unique_and_separates_quick_results(self): + with tempfile.TemporaryDirectory() as temp, patch.object(run, 'RESULTS', Path(temp)): + first = run.prepare_output(None, False) + second = run.prepare_output(None, False) + quick = run.prepare_output(None, True) + self.assertNotEqual(first, second) + self.assertTrue(first.name.startswith('stress-')) + self.assertTrue(quick.name.startswith('quick-')) + explicit = Path(temp) / 'custom' + self.assertEqual(run.prepare_output(explicit, True), explicit.resolve()) + + def test_archive_includes_nested_worker_and_test_sources(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + raw, out = root / 'raw', root / 'out' + raw.mkdir(); out.mkdir() + meta = dict(quick=True, errors=[], host={}) + for name, data in [('metadata.json', meta), ('runs.json', []), ('confirmed.json', {})]: + run.save(raw / name, data) + run.publish(raw, out, True, meta, [], {}) + with run.tarfile.open(out / '快速验证原始数据.tar.gz') as archive: + for name in ['src/throughput.cpp', 'src/profile.cpp', 'src/socket_probe.c', 'tests/test_run.py']: + self.assertEqual(archive.extractfile('tool-source/' + name).read(), (run.HERE / name).read_bytes()) + + def test_worker_success_cannot_hide_kernel_loss_or_missing_counter(self): + good = record() + self.assertEqual(run.assess(good), []) + bad = copy.deepcopy(good) + bad['probes'][1]['drops'] = 1 + self.assertTrue(any('内核丢帧' in e for e in run.assess(bad))) + bad = copy.deepcopy(good) + bad['probes'].pop() + self.assertTrue(any('计数缺失' in e for e in run.assess(bad))) + bad = copy.deepcopy(good) + bad['result']['received'] -= 1 + self.assertIn('完整收发计数不一致', run.assess(bad)) + + def test_timeout_exit_and_malformed_json_cannot_be_success(self): + for field, value in [('timed_out', True), ('exit_code', 1), ('result', None)]: + r = record() + r[field] = value + self.assertTrue(run.assess(r)) + + def test_source_dirty_content_and_reverted_commit_detection(self): + with tempfile.TemporaryDirectory() as temp: + p = Path(temp) + subprocess.run(['git', 'init', '-q', temp], check=True) + subprocess.run(['git', '-C', temp, 'config', 'user.name', 'test'], check=True) + subprocess.run(['git', '-C', temp, 'config', 'user.email', 'test@example.invalid'], check=True) + f = p / 'code.cpp' + f.write_text('before') + subprocess.run(['git', '-C', temp, 'add', '.'], check=True) + subprocess.run(['git', '-C', temp, 'commit', '-qm', 'fixture'], check=True) + a = run.snapshot(p) + f.write_text('after') + self.assertFalse(run.same_source(a, run.snapshot(p))) + f.write_text('before') + self.assertTrue(run.same_source(a, run.snapshot(p))) + (p / 'new.hpp').write_text('new') + self.assertFalse(run.same_source(a, run.snapshot(p))) + + def test_timeout_kills_descendant_before_it_can_write(self): + with tempfile.TemporaryDirectory() as temp: + p = Path(temp) + child = 'import time,pathlib;time.sleep(1);pathlib.Path(' + repr(str(p / 'orphan')) + ').touch()' + parent = 'import subprocess,sys,time;subprocess.Popen([sys.executable,"-c",' + repr(child) + ']);time.sleep(10)' + _, timed_out = run.execute([sys.executable, '-c', parent], p / 'out', p / 'err', .2) + self.assertTrue(timed_out) + time.sleep(1.1) + self.assertFalse((p / 'orphan').exists()) + + def test_report_and_archive_tampering_and_incomplete_results(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + raw, out = root / 'raw', root / 'out' + raw.mkdir(); out.mkdir() + meta = dict(quick=False, started_at='start', finished_at='end', source_unchanged=True, + errors=['injected failure'], host={}) + run.save(raw / 'metadata.json', meta) + run.save(raw / 'runs.json', []) + run.save(raw / 'confirmed.json', {}) + run.publish(raw, out, False, meta, [], {}) + report = (out / '压测报告.md').read_text() + self.assertIn('流程未完成或测试无效', report) + self.assertNotIn('四项无损确认有效', report) + self.assertEqual(run.verify_archive(out / '压测原始数据.tar.gz')['confirmed'], 0) + with self.assertRaisesRegex(RuntimeError, '报告与本次原始记录不一致'): + run.verify_archive(out / '压测原始数据.tar.gz', report + 'tampered') + + def test_missing_dependency_replaces_previous_success_with_failure(self): + with tempfile.TemporaryDirectory() as temp: + out = Path(temp) + (out / '压测报告.md').write_text('old successful report') + with patch.object(sys, 'argv', ['run.py', '--output', temp]), patch.object(run.shutil, 'which', return_value=None): + self.assertEqual(run.main(), 1) + report = (out / '压测报告.md').read_text() + self.assertIn('缺少依赖', report) + self.assertNotIn('old successful', report) + self.assertNotIn('四项无损确认有效', report) + + +if __name__ == '__main__': + unittest.main() diff --git a/docs/en/performance.md b/docs/en/performance.md index a15ace2..1310301 100644 --- a/docs/en/performance.md +++ b/docs/en/performance.md @@ -3,7 +3,7 @@ English · [简体中文](../zh/performance.md) [Documentation index](../README.md) · [Build guide](build.md) · -[Benchmark source and measurement rules](../../benchmarks/README.md) +[Benchmark source and measurement rules](../../benchmarks/micro/README.md) The ARM64 Linux measurements identified per-operation allocation in subscriber snapshots. Reusing immutable membership between subscription changes removed @@ -170,7 +170,7 @@ cmake --build build/perf-alloc --parallel 4 taskset -c 0-3 ./build/perf-alloc/linkerbot-perf \ --iterations 200000 --idle-ms 500 --repetitions 3 -python3 benchmarks/summarize.py benchmarks/results/arm64-linux-2026-11-03 +python3 benchmarks/micro/summarize.py benchmarks/results/arm64-linux-2026-11-03 ``` Keep each process's CSV output, tool versions, affinity and run order. The summary diff --git a/docs/zh/performance.md b/docs/zh/performance.md index 6a6a01a..3f1364f 100644 --- a/docs/zh/performance.md +++ b/docs/zh/performance.md @@ -3,7 +3,7 @@ [English](../en/performance.md) · 简体中文 [文档索引](../README.md) · [构建指南](build.md) · -[基准源码与测量规则](../../benchmarks/README.md) +[基准源码与测量规则](../../benchmarks/micro/README.md) ARM64 Linux 测量确认了订阅者快照每次操作的分配。在订阅关系不变时复用不可变成员快照, 消除了该分配;在这组样本中,1、8、64 个订阅者下的稳态快照/分发耗时中位数降低。 @@ -140,7 +140,7 @@ cmake --build build/perf-alloc --parallel 4 taskset -c 0-3 ./build/perf-alloc/linkerbot-perf \ --iterations 200000 --idle-ms 500 --repetitions 3 -python3 benchmarks/summarize.py benchmarks/results/arm64-linux-2026-11-03 +python3 benchmarks/micro/summarize.py benchmarks/results/arm64-linux-2026-11-03 ``` 保留每个进程的 CSV、工具版本、亲和性和运行顺序。汇总脚本校验回调/成员数量校验值,