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

morningman pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 6cd570c06b0 [chore](build) Add --compile-bench to run-be-ut.sh (#71389)
6cd570c06b0 is described below

commit 6cd570c06b09e3121804ec6139f0ecdb577c874a
Author: Mingyu Chen (Rayner) <[email protected]>
AuthorDate: Fri Dec 4 09:47:45 2026 +0800

    [chore](build) Add --compile-bench to run-be-ut.sh (#71389)
    
    ### Background
    
    `build.sh --compile-bench` times a cold BE build and records individual
    compiler and linker invocations. Contributors build the BE unit-test
    executable through `run-be-ut.sh`, which compiles the test sources
    alongside the BE sources. On macOS arm64, CMake runs `dsymutil` and
    `llvm-strip` after linking the test executable.
    
    ### What problem does this PR solve?
    
    Issue Number: #71314
    Related PR: #66616 (adds BE compile timing), #61291 (switches macOS ANN
    tests to `-force_load`), #66615 (adds target ordering for that archive)
    PR Type: Build/CI/Chore
    
    Problem Summary:
    
    Contributors need to measure a cold BE unit-test build without reusing
    ccache entries or deleting their incremental build. `run-be-ut.sh
    --compile-bench` reuses the BE timing tools and reports compile time by
    source area and time spent after linking. On macOS, rebuilding only an
    ANN test can also leave `doris_be_test` stale. The executable link now
    tracks the ANN archive as an input.
    
    ### Details
    
    - **Change map:**
    - Compile-bench entry point and reporting, +439/-35. Includes 183 lines
    of shell and Python self-tests and 30 changed lines of documentation.
    - macOS incremental relinking, +5. Adds the ANN archive to the
    executable's link dependencies.
    - **Affected:** Local BE and BE unit-test tooling on Linux and macOS.
    The reporting tools use Python 3. The link dependency correction applies
    to macOS. CI uses the ordinary unit-test invocation.
    - **Developer and release impact:** `./run-be-ut.sh --compile-bench -j
    6` recreates `be/ut_build_<type>_compile_bench`, builds the executable,
    and writes text and JSON reports. Budget about one additional unit-test
    build directory of disk space. No release process changes.
    - **License and third-party:** None.
    - **Rollback:** Revert the commits. The generated benchmark directory
    and reports can be removed separately.
    
    ### Testing
    
    - Both compile-bench self-tests pass on macOS. The new self-test rejects
    the baseline helpers and verifies source grouping, compatibility of the
    BE caller, and post-link reporting.
    - The CLI rejects `--compile-bench --run` and `--compile-bench
    --jemalloc-hook` with exit code 1.
    - A complete macOS arm64 ASAN run of `./run-be-ut.sh --compile-bench -j
    6` recreated its dedicated directory and produced text and JSON reports
    with `be/src`, `be/test`, and post-link entries. The ordinary build
    artifacts kept their timestamps and sizes. The comparison command
    accepted a summary generated by the baseline reporter.
    - The baseline Ninja graph lists the ANN archive as order-only. After
    the fix, touching only `faiss_vector_index_test.cpp` rebuilt the object
    and archive, then relinked `doris_be_test` with the ordinary unit-test
    command.
    - The same 247 cases across the ANN suites and `CodingTest` passed on
    macOS arm64 ASAN in registration order and with shuffle seed 48256.
    Linux CI is pending.
    - Shell syntax, ShellCheck on the entry point and self-test, and BE
    build hygiene pass. The shared helper has the same ShellCheck
    diagnostics as the baseline.
---
 be/test/CMakeLists.txt                       |   5 +
 build-support/compile-bench/README.md        |  30 ++++-
 build-support/compile-bench/bench-lib.sh     |  28 ++--
 build-support/compile-bench/report.py        | 153 ++++++++++++++++++++--
 build-support/tests/test-compile-bench-ut.sh | 183 +++++++++++++++++++++++++++
 run-be-ut.sh                                 |  80 ++++++++++--
 6 files changed, 444 insertions(+), 35 deletions(-)

diff --git a/be/test/CMakeLists.txt b/be/test/CMakeLists.txt
index 6fcc3cbaf67..d6e6ddb4861 100644
--- a/be/test/CMakeLists.txt
+++ b/be/test/CMakeLists.txt
@@ -168,6 +168,11 @@ if (APPLE)
     # dependency, so parallel ninja could link doris_be_test before the
     # archive exists.
     add_dependencies(doris_be_test vector_search_test)
+    # Nor does it make the archive an input of the link: when only a test in
+    # storage/index/ann/ changes, the archive is rebuilt and doris_be_test is
+    # not relinked, so the tests run the old code.
+    set_property(TARGET doris_be_test APPEND PROPERTY
+        LINK_DEPENDS $<TARGET_FILE:vector_search_test>)
 else()
     target_link_libraries(doris_be_test ${TEST_LINK_LIBS}
         -Wl,--whole-archive vector_search_test -Wl,--no-whole-archive)
diff --git a/build-support/compile-bench/README.md 
b/build-support/compile-bench/README.md
index c1bdc8d38e6..47b743b8936 100644
--- a/build-support/compile-bench/README.md
+++ b/build-support/compile-bench/README.md
@@ -38,6 +38,17 @@ COMPILE_BENCH_TRACE=ON ./build.sh --compile-bench
 BUILD_TYPE=Release ./build.sh --compile-bench -j 16
 ```
 
+The BE unit tests have the same mode. It builds `doris_be_test` (all of 
`be/src`
+with `-DBE_TEST`, plus `be/test`) in its own always-cold
+`be/ut_build_<Type>_compile_bench` dir, with the `run-be-ut.sh` defaults
+(`BUILD_TYPE_UT`, `ENABLE_PCH`, `DORIS_DEV_DEBUG_INFO`, ...), and does not run
+the tests:
+
+```bash
+./run-be-ut.sh --compile-bench -j 6
+COMPILE_BENCH_TRACE=ON ./run-be-ut.sh --compile-bench -j 6
+```
+
 Results are stored per run in `be/compile-bench-results/<UTC timestamp>/`:
 
 | file               | content                                                 
       |
@@ -71,9 +82,10 @@ Benchmark numbers are only comparable when every run does 
the same cold work:
 - **ccache is fully disabled**: the timing wrapper replaces ccache as
   `CMAKE_<LANG>_COMPILER_LAUNCHER`, and `CCACHE_DISABLE=1` is exported as a
   belt-and-braces measure for anything else that might call ccache.
-- **A dedicated build dir** `be/build_<Type>_compile_bench` is deleted and
-  recreated on every run: no incremental objects, no CMake cache, no stale
-  ninja state. Your normal `be/build_<Type>` dir is left untouched, so 
day-to-day
+- **A dedicated build dir** `be/build_<Type>_compile_bench` (unit tests:
+  `be/ut_build_<Type>_compile_bench`) is deleted and recreated on every run: no
+  incremental objects, no CMake cache, no stale ninja state. Your normal
+  `be/build_<Type>` / `be/ut_build_<Type>` dir is left untouched, so day-to-day
   incremental builds are not harmed by benchmarking.
 - **BE-only scope**: FE, cloud, java extensions, cdc client, UI and output
   packaging are forcibly skipped; the run ends right after the C++ build and
@@ -89,9 +101,17 @@ Benchmark numbers are only comparable when every run does 
the same cold work:
   configure, build — with durations and share of total wall time.
 - **Build summary**: TU count, sum of per-TU wall/cpu time, effective
   parallelism, slowest TU, most memory-hungry TU, link times with peak RSS.
+  When a link edge also runs POST_BUILD commands (on macOS `doris_be_test` is
+  followed by `dsymutil` and `llvm-strip`), their time is shown as "post-link
+  steps": the edge's `.ninja_log` duration minus the timed link.
+- **Compile time by area**: TU count and wall/cpu sums for `be/src` (unity
+  batches included), `be/test`, `common` (the C++ shared with cloud),
+  `contrib` (including the sources it generates in the build tree, such as
+  openblas' kernels) and `gensrc`, so a unit-test build shows how the tests
+  compare with the BE sources they rebuild.
 - **Top N slowest translation units** with wall/user/sys/maxrss per file.
-- **Wall time by directory** (top-level and second-level under `be/src`) —
-  tells you which module to attack first.
+- **Wall time by directory** (top-level and second-level under `be/src` and
+  `be/test`) — tells you which module to attack first.
 - **Last finishers** from `.ninja_log` — the critical-path tail the whole
   build waits on (typically the monster TUs and the final link).
 - With `COMPILE_BENCH_TRACE=ON` (clang only): **top headers by inclusive parse
diff --git a/build-support/compile-bench/bench-lib.sh 
b/build-support/compile-bench/bench-lib.sh
index eca2e03b1e4..f528cb32f68 100644
--- a/build-support/compile-bench/bench-lib.sh
+++ b/build-support/compile-bench/bench-lib.sh
@@ -17,8 +17,9 @@
 # under the License.
 
 ##############################################################
-# Helper library for `build.sh --compile-bench`.
-# This file is sourced by build.sh, not executed.
+# Helper library for `build.sh --compile-bench` and
+# `run-be-ut.sh --compile-bench`.
+# This file is sourced by those scripts, not executed.
 #
 # One benchmark run collects everything under
 #   be/compile-bench-results/<run_id>/
@@ -37,15 +38,20 @@ _compile_bench_now_ms() {
     python3 -c 'import time; print(int(time.time() * 1000))'
 }
 
-# compile_bench_init <doris_home>
+# compile_bench_init <doris_home> [<build_type> <build_dir> <flavor>]
 # Prepares the run directory, disables every compile cache and installs the
-# timing wrapper as the compiler launcher. Mutates:
+# timing wrapper as the compiler launcher. build.sh passes <doris_home> only:
+# the build type comes from BUILD_TYPE and the flavor is "be". run-be-ut.sh
+# passes its CMake build type, its own always-cold build dir and "be-ut".
+# Mutates:
 #   CMAKE_USE_CCACHE_CXX / CMAKE_USE_CCACHE_C  (launcher slot: ccache -> 
wrapper)
 #   COMPILE_BENCH_CMAKE_ARGS                   (extra -D args for the BE cmake 
call)
 #   COMPILE_BENCH_BUILD_DIR                    (dedicated always-cold build 
dir)
 #   EXTRA_CXX_FLAGS                            (+ -ftime-trace when requested)
 compile_bench_init() {
     local doris_home="$1"
+    local cmake_build_type="${2:-${BUILD_TYPE:-Release}}"
+    local flavor="${4:-be}"
 
     if ! command -v python3 &>/dev/null; then
         echo "ERROR: --compile-bench requires python3 (timing wrapper and 
report generator)."
@@ -56,8 +62,7 @@ compile_bench_init() {
     
COMPILE_BENCH_RUN_DIR="${doris_home}/be/compile-bench-results/${COMPILE_BENCH_RUN_ID}"
     mkdir -p "${COMPILE_BENCH_RUN_DIR}"
 
-    local cmake_build_type="${BUILD_TYPE:-Release}"
-    
COMPILE_BENCH_BUILD_DIR="${doris_home}/be/build_${cmake_build_type}_compile_bench"
+    
COMPILE_BENCH_BUILD_DIR="${3:-${doris_home}/be/build_${cmake_build_type}_compile_bench}"
 
     # Consumed by cc-timing-wrapper.py in every compiler process.
     export DORIS_COMPILE_BENCH_DIR="${COMPILE_BENCH_RUN_DIR}"
@@ -95,6 +100,7 @@ compile_bench_init() {
 
     {
         printf 'run_id\t%s\n' "${COMPILE_BENCH_RUN_ID}"
+        printf 'flavor\t%s\n' "${flavor}"
         printf 'doris_home\t%s\n' "${doris_home}"
         printf 'build_dir\t%s\n' "${COMPILE_BENCH_BUILD_DIR}"
         printf 'date_utc\t%s\n' "$(date -u '+%Y-%m-%d %H:%M:%S')"
@@ -108,6 +114,8 @@ compile_bench_init() {
         printf 'cxx\t%s\n' "${CXX}"
         printf 'cxx_version\t%s\n' "${cxx_version}"
         printf 'enable_pch\t%s\n' "${ENABLE_PCH}"
+        printf 'enable_unity_build\t%s\n' "${ENABLE_UNITY_BUILD:-ON}"
+        printf 'dev_debug_info\t%s\n' "${DORIS_DEV_DEBUG_INFO:-full}"
         printf 'use_avx2\t%s\n' "${USE_AVX2}"
         printf 'time_trace\t%s\n' "${COMPILE_BENCH_TIME_TRACE}"
         printf 'git_commit\t%s\n' "${git_commit}"
@@ -117,12 +125,16 @@ compile_bench_init() {
     COMPILE_BENCH_T0="$(_compile_bench_now_ms)"
 
     echo "***************************************"
-    echo "* BE compile benchmark mode (--compile-bench)"
+    echo "* BE compile benchmark mode (--compile-bench, ${flavor})"
     echo "*   run dir     : ${COMPILE_BENCH_RUN_DIR}"
     echo "*   build dir   : ${COMPILE_BENCH_BUILD_DIR} (recreated from 
scratch)"
     echo "*   ccache      : DISABLED (timing wrapper installed as launcher)"
     echo "*   -ftime-trace: ${COMPILE_BENCH_TIME_TRACE}"
-    echo "*   BE-only build: FE/cloud/java-extensions/packaging are skipped"
+    if [[ "${flavor}" == "be-ut" ]]; then
+        echo "*   UT build only: doris_be_test is built, no test is run"
+    else
+        echo "*   BE-only build: FE/cloud/java-extensions/packaging are 
skipped"
+    fi
     echo "***************************************"
 }
 
diff --git a/build-support/compile-bench/report.py 
b/build-support/compile-bench/report.py
index e8f95e414a5..e01b0136c19 100755
--- a/build-support/compile-bench/report.py
+++ b/build-support/compile-bench/report.py
@@ -16,7 +16,7 @@
 # specific language governing permissions and limitations
 # under the License.
 
-"""Report generator for `build.sh --compile-bench` runs.
+"""Report generator for `build.sh --compile-bench` and `run-be-ut.sh 
--compile-bench` runs.
 
 Generate a report for one run (done automatically at the end of a bench build,
 can be re-run manually at any time):
@@ -49,8 +49,21 @@ TOP_TAIL = 10
 WIDTH = 78
 
 # be/<build dir>/<mirrored source 
dir>/CMakeFiles/<target>.dir/Unity/unity_<n>_cxx.cxx
+# The build dir is be/build_<type>[_compile_bench] or, for the unit tests,
+# be/ut_build_<type>[_compile_bench].
 UNITY_SOURCE_RE = re.compile(
-    
r"^be/build[^/]*/(.+?)/CMakeFiles/[^/]+\.dir/Unity/unity_\d+_c(?:xx)?\.c(?:xx)?$")
+    
r"^be/(?:ut_)?build[^/]*/(.+?)/CMakeFiles/[^/]+\.dir/Unity/unity_\d+_c(?:xx)?\.c(?:xx)?$")
+
+# Source roots whose sub-directories are the interesting grouping level.
+SOURCE_ROOTS = ("be/src", "be/test")
+
+# Coarse areas for the "Compile time by area" section, first match wins.
+# common/ is the C++ code the BE shares with cloud.
+AREAS = ("be/src", "be/test", "common", "contrib", "gensrc")
+
+# A source inside the BE build tree itself: generated code, e.g. the openblas
+# kernels that contrib's own CMake writes under be/<build dir>/openblas/.
+BUILD_TREE_RE = re.compile(r"^be/(?:ut_)?build[^/]*/(.+)$")
 
 
 def section(title):
@@ -187,19 +200,73 @@ def unity_source_dir(rel_src):
     return "be/" + match.group(1) if match else None
 
 
+def source_root(rel_dir):
+    """The SOURCE_ROOTS entry rel_dir lives under, or "" for anything else."""
+    for root in SOURCE_ROOTS:
+        if rel_dir == root or rel_dir.startswith(root + "/"):
+            return root
+    return ""
+
+
 def group_keys(rel_src):
     """Return (level1, level2) directory grouping keys for a 
doris_home-relative source."""
     rel_dir = unity_source_dir(rel_src) or os.path.dirname(rel_src)
-    if rel_dir.startswith("be/src"):
-        prefix, rest = "be/src", rel_dir[len("be/src"):].strip("/")
-    else:
-        prefix, rest = "", rel_dir
+    prefix = source_root(rel_dir)
+    rest = rel_dir[len(prefix):].strip("/") if prefix else rel_dir
     parts = [p for p in rest.split("/") if p]
     level1 = "/".join([prefix] + parts[:1]) if prefix else 
("/".join(parts[:1]) or ".")
     level2 = "/".join([prefix] + parts[:2]) if prefix else 
("/".join(parts[:2]) or ".")
     return level1 or ".", level2 or "."
 
 
+def area_of(rel_src):
+    """Coarse area of a doris_home-relative source: an AREAS entry or "other".
+
+    A generated unity TU counts for the module it batches, so the be/src
+    total includes the unity batches that live in the build tree. Any other
+    source generated in the build tree outside its src/ and test/ mirrors
+    belongs to a bundled third-party project (contrib's openblas generates
+    some two thousand kernel sources there).
+    """
+    rel = unity_source_dir(rel_src) or rel_src
+    for area in AREAS:
+        if rel == area or rel.startswith(area + "/"):
+            return area
+    match = BUILD_TREE_RE.match(rel_src)
+    if match and not match.group(1).startswith(("src/", "test/")):
+        return "contrib"
+    return "other"
+
+
+def post_link_seconds(links, ninja_edges, build_dir):
+    """Map each link record's output to the time its ninja edge spent after 
the link.
+
+    CMake chains POST_BUILD commands onto the link edge (for doris_be_test on
+    macOS: dsymutil + llvm-strip), but the linker launcher only times the link
+    itself. The difference between the edge's duration in .ninja_log and the
+    timed link is what those steps cost. Links without a matching edge (no
+    ninja log, or an interrupted build) are left out.
+    """
+    by_basename = defaultdict(list)
+    for output in ninja_edges:
+        by_basename[os.path.basename(output)].append(output)
+    result = {}
+    for record in links:
+        out = record.get("out")
+        if not out:
+            continue
+        path = out if os.path.isabs(out) else os.path.join(record.get("cwd") 
or "", out)
+        key = os.path.relpath(path, build_dir) if build_dir else out
+        if key not in ninja_edges:
+            candidates = by_basename.get(os.path.basename(out), [])
+            if len(candidates) != 1:
+                continue
+            key = candidates[0]
+        start_ms, end_ms = ninja_edges[key]
+        result[out] = max(0.0, (end_ms - start_ms) / 1000.0 - record["wall_s"])
+    return result
+
+
 def load_time_traces(compiles, meta, build_dir):
     """Aggregate clang -ftime-trace JSONs written next to the object files.
 
@@ -288,9 +355,9 @@ def build_report(run_dir, build_dir, top_n, build_status):
         meta.get("run_id", os.path.basename(run_dir.rstrip("/")))))
     out("=" * 78)
     out(" build status : {}".format(build_status))
-    for key in ("date_utc", "git_branch", "git_commit", "uname", "ncpu", 
"parallel",
+    for key in ("flavor", "date_utc", "git_branch", "git_commit", "uname", 
"ncpu", "parallel",
                 "build_type", "generator", "toolchain", "cxx_version", 
"enable_pch",
-                "time_trace", "build_dir"):
+                "enable_unity_build", "dev_debug_info", "time_trace", 
"build_dir"):
         if key in meta:
             out(" {:<13}: {}".format(key, meta[key]))
 
@@ -334,16 +401,36 @@ def build_report(run_dir, build_dir, top_n, build_status):
         hungriest = max(compiles, key=lambda r: r.get("maxrss_mb", 0))
         out(" largest TU peak rss           : {:.0f} MB  ({})".format(
             hungriest.get("maxrss_mb", 0), rel_path(hungriest.get("src"), 
meta)))
+    post_link = post_link_seconds(links, ninja_edges, build_dir)
     for link in sorted(links, key=lambda r: r["wall_s"], reverse=True)[:5]:
-        out(" link {:<24} : {}  peak rss {:.0f} MB".format(
+        post_s = post_link.get(link.get("out"))
+        out(" link {:<24} : {}  peak rss {:.0f} MB{}".format(
             os.path.basename(link.get("out") or "?"),
-            fmt_dur(link["wall_s"]), link.get("maxrss_mb", 0)))
+            fmt_dur(link["wall_s"]), link.get("maxrss_mb", 0),
+            "  + post-link steps {}".format(fmt_dur(post_s)) if post_s else 
""))
     if failed:
         out(" FAILED commands               : {}".format(len(failed)))
         for record in failed[:10]:
             out("   rc={:<4} {}".format(
                 record.get("rc"), rel_path(record.get("src") or 
record.get("out"), meta)))
 
+    # ---- Areas: be/src vs be/test vs bundled third-party ------------------
+    areas = defaultdict(lambda: [0, 0.0, 0.0])
+    for record in compiles:
+        entry = areas[area_of(rel_path(record.get("src") or record.get("out") 
or "?", meta))]
+        entry[0] += 1
+        entry[1] += record["wall_s"]
+        entry[2] += record["user_s"] + record["sys_s"]
+    if compiles:
+        out("")
+        out(section("Compile time by area"))
+        out(" {:>6} {:>9} {:>9} {:>7}  {}".format("count", "wall-sum", 
"cpu-sum", "wall%", "area"))
+        for area, (count, wall, cpu) in sorted(areas.items(), key=lambda kv: 
kv[1][1],
+                                               reverse=True):
+            out(" {:>6} {:>9} {:>9} {:>6.1f}%  {}".format(
+                count, fmt_dur(wall), fmt_dur(cpu),
+                100.0 * wall / sum_wall if sum_wall else 0.0, area))
+
     # ---- Top slow TUs -------------------------------------------------------
     out("")
     out(section("Top {} slowest translation units (wall)".format(top_n)))
@@ -435,6 +522,20 @@ def build_report(run_dir, build_dir, top_n, build_status):
             "sum_tu_cpu_s": round(sum_cpu, 1),
             "build_phase_s": round(build_phase_s, 1) if build_phase_s else 
None,
         },
+        "areas": {
+            area: {"compile_units": count, "sum_tu_wall_s": round(wall, 1),
+                   "sum_tu_cpu_s": round(cpu, 1)}
+            for area, (count, wall, cpu) in areas.items()
+        },
+        "links": {
+            os.path.basename(r.get("out") or "?"): {
+                "wall_s": r["wall_s"],
+                "maxrss_mb": r.get("maxrss_mb", 0),
+                "post_link_s": round(post_link[r.get("out")], 1)
+                if r.get("out") in post_link else None,
+            }
+            for r in links
+        },
         "files": {
             rel_path(r.get("src") or r.get("out"), meta): {
                 "wall_s": r["wall_s"],
@@ -502,6 +603,38 @@ def cmd_compare(args):
             fmt_dur(new_s) if new_s is not None else "-",
             delta))
 
+    # Summaries written before these sections existed simply lack the keys.
+    old_areas, new_areas = old.get("areas", {}), new.get("areas", {})
+    if old_areas or new_areas:
+        print("")
+        print(section("Compile time by area (sum of TU wall)"))
+        print(" {:<24} {:>9} {:>9} {:>9}".format("area", "old", "new", 
"delta"))
+        for name in sorted(set(old_areas) | set(new_areas)):
+            old_s = old_areas.get(name, {}).get("sum_tu_wall_s")
+            new_s = new_areas.get(name, {}).get("sum_tu_wall_s")
+            delta = "" if old_s is None or new_s is None else 
"{:+.1f}s".format(new_s - old_s)
+            print(" {:<24} {:>9} {:>9} {:>9}".format(
+                name,
+                fmt_dur(old_s) if old_s is not None else "-",
+                fmt_dur(new_s) if new_s is not None else "-",
+                delta))
+    old_links, new_links = old.get("links", {}), new.get("links", {})
+    if old_links or new_links:
+        print("")
+        print(section("Links (link wall + post-link steps)"))
+        print(" {:<24} {:>19} {:>19}".format("output", "old", "new"))
+        for name in sorted(set(old_links) | set(new_links)):
+            cells = []
+            for links in (old_links, new_links):
+                link = links.get(name)
+                if link is None:
+                    cells.append("-")
+                else:
+                    post = link.get("post_link_s")
+                    cells.append(fmt_dur(link["wall_s"]) +
+                                 (" + " + fmt_dur(post) if post is not None 
else ""))
+            print(" {:<24} {:>19} {:>19}".format(name, cells[0], cells[1]))
+
     old_files, new_files = old.get("files", {}), new.get("files", {})
     both = set(old_files) & set(new_files)
     deltas = sorted(
diff --git a/build-support/tests/test-compile-bench-ut.sh 
b/build-support/tests/test-compile-bench-ut.sh
new file mode 100755
index 00000000000..1531fcecc4d
--- /dev/null
+++ b/build-support/tests/test-compile-bench-ut.sh
@@ -0,0 +1,183 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# Self-test for the unit-test flavor of the compile benchmark
+# (run-be-ut.sh --compile-bench): bench-lib.sh's build-dir/flavor arguments and
+# report.py's handling of a UT build tree (unity TUs under be/ut_build_*,
+# be/test grouping, the per-area totals and the post-link steps of a link 
edge).
+#
+# Usage:  bash build-support/tests/test-compile-bench-ut.sh   # exit 0 = pass
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+TMP="$(mktemp -d)"
+trap 'rm -rf "${TMP}"' EXIT
+
+failures=0
+check() {
+    if [[ "$2" == "$3" ]]; then
+        echo "  ok   $1"
+    else
+        echo "  FAIL $1: expected '$3', got '$2'"
+        failures=$((failures + 1))
+    fi
+}
+
+meta_value() {
+    awk -F '\t' -v key="$2" '$1 == key { print $2 }' "$1/meta.tsv"
+}
+
+echo "bench-lib.sh compile_bench_init"
+
+# build.sh calls it with <doris_home> only: build dir from BUILD_TYPE, flavor 
"be".
+default_dir="$(
+    # bench-lib.sh is written for build.sh / run-be-ut.sh, which do not use 
set -u.
+    set +u
+    cd "${TMP}"
+    BUILD_TYPE=Release
+    # shellcheck source=build-support/compile-bench/bench-lib.sh
+    . "${ROOT}/compile-bench/bench-lib.sh" >/dev/null
+    compile_bench_init "${TMP}/home_default" >/dev/null
+    echo "${COMPILE_BENCH_RUN_DIR}"
+    echo "${COMPILE_BENCH_BUILD_DIR}"
+)"
+run_dir="$(echo "${default_dir}" | sed -n 1p)"
+check "default build dir" "$(echo "${default_dir}" | sed -n 2p)" 
"${TMP}/home_default/be/build_Release_compile_bench"
+check "default flavor" "$(meta_value "${run_dir}" flavor)" "be"
+check "default build type" "$(meta_value "${run_dir}" build_type)" "Release"
+
+# run-be-ut.sh passes its build type, its own build dir and flavor "be-ut".
+ut_state="$(
+    set +u
+    cd "${TMP}"
+    BUILD_TYPE=Release
+    ENABLE_UNITY_BUILD=ON
+    DORIS_DEV_DEBUG_INFO=line-tables
+    CMAKE_USE_CCACHE_CXX="-DCMAKE_CXX_COMPILER_LAUNCHER=ccache"
+    # shellcheck source=build-support/compile-bench/bench-lib.sh
+    . "${ROOT}/compile-bench/bench-lib.sh" >/dev/null
+    compile_bench_init "${TMP}/home_ut" ASAN 
"${TMP}/home_ut/be/ut_build_ASAN_compile_bench" be-ut >/dev/null
+    echo "${COMPILE_BENCH_RUN_DIR}"
+    echo "${COMPILE_BENCH_BUILD_DIR}"
+    echo "${CMAKE_USE_CCACHE_CXX}"
+    echo "${CCACHE_DISABLE}"
+)"
+run_dir="$(echo "${ut_state}" | sed -n 1p)"
+check "ut build dir" "$(echo "${ut_state}" | sed -n 2p)" 
"${TMP}/home_ut/be/ut_build_ASAN_compile_bench"
+check "ut launcher is the timing wrapper" "$(echo "${ut_state}" | sed -n 3p)" \
+    "-DCMAKE_CXX_COMPILER_LAUNCHER=${ROOT}/compile-bench/cc-timing-wrapper.py"
+check "ut ccache disabled" "$(echo "${ut_state}" | sed -n 4p)" "1"
+check "ut flavor" "$(meta_value "${run_dir}" flavor)" "be-ut"
+check "ut build type" "$(meta_value "${run_dir}" build_type)" "ASAN"
+check "ut build_dir in meta" "$(meta_value "${run_dir}" build_dir)" 
"${TMP}/home_ut/be/ut_build_ASAN_compile_bench"
+check "ut unity setting in meta" "$(meta_value "${run_dir}" 
enable_unity_build)" "ON"
+check "ut debug info in meta" "$(meta_value "${run_dir}" dev_debug_info)" 
"line-tables"
+
+python3 - "${ROOT}/compile-bench" "${TMP}" <<'PY' || failures=$((failures + 1))
+import importlib.util
+import json
+import os
+import sys
+
+bench_dir, tmp = sys.argv[1], sys.argv[2]
+spec = importlib.util.spec_from_file_location("report", 
os.path.join(bench_dir, "report.py"))
+report = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(report)
+failures = []
+
+
+def check(label, got, expected):
+    ok = got == expected
+    print(("  ok   " if ok else "  FAIL ") + label + ("" if ok else ": got 
{!r}".format(got)))
+    if not ok:
+        failures.append(label)
+
+
+print("report.group_keys / area_of on a UT build tree")
+ut_unity = 
"be/ut_build_ASAN_compile_bench/src/storage/CMakeFiles/Storage.dir/Unity/unity_3_cxx.cxx"
+check("UT unity TU groups under its module", report.group_keys(ut_unity),
+      ("be/src/storage", "be/src/storage"))
+check("UT unity TU counts as be/src", report.area_of(ut_unity), "be/src")
+test_tu = "be/test/storage/segment/column_reader_test.cpp"
+check("be/test TU groups under its test dir", report.group_keys(test_tu),
+      ("be/test/storage", "be/test/storage/segment"))
+check("be/test TU counts as be/test", report.area_of(test_tu), "be/test")
+check("unity tests batch counts as be/test",
+      
report.area_of("be/ut_build_ASAN/test/CMakeFiles/doris_be_test.dir/Unity/unity_0_cxx.cxx"),
+      "be/test")
+check("contrib TU", 
report.area_of("contrib/apache-orc/c++/test/TestReader.cc"), "contrib")
+check("contrib source generated in the build tree",
+      
report.area_of("be/ut_build_ASAN_compile_bench/openblas/interface/CMakeFiles/scopy.c"),
 "contrib")
+check("shared common/cpp TU", report.area_of("common/cpp/aws_sdk.cpp"), 
"common")
+check("generated non-unity source under the src mirror stays other",
+      report.area_of("be/ut_build_ASAN/src/gen_cpp/foo.cpp"), "other")
+check("generated thrift TU", 
report.area_of("gensrc/build/gen_cpp/Types_types.cpp"), "gensrc")
+check("a look-alike root is not be/test", 
report.group_keys("be/testdata/x.cpp")[0], "be")
+check("BE build tree unity is unchanged",
+      
report.group_keys("be/build_Release_compile_bench/src/exec/CMakeFiles/Exec.dir/Unity/unity_1_cxx.cxx"),
+      ("be/src/exec", "be/src/exec"))
+
+print("report.post_link_seconds")
+build_dir = os.path.join(tmp, "be/ut_build_ASAN_compile_bench")
+link = {"kind": "link", "out": "test/doris_be_test", "cwd": build_dir, 
"wall_s": 100.0}
+edges = {"test/doris_be_test": (5000, 280000), "src/util/libUtil.a": (1000, 
2000)}
+check("edge minus link wall", report.post_link_seconds([link], edges, 
build_dir),
+      {"test/doris_be_test": 175.0})
+moved = dict(link, cwd="/elsewhere")
+check("falls back to a unique basename", report.post_link_seconds([moved], 
edges, build_dir),
+      {"test/doris_be_test": 175.0})
+check("no edge, no entry", report.post_link_seconds([link], {}, build_dir), {})
+
+print("report.build_report on a UT run")
+run_dir = os.path.join(tmp, "run")
+os.makedirs(run_dir)
+with open(os.path.join(run_dir, "meta.tsv"), "w") as fh:
+    
fh.write("run_id\tt\nflavor\tbe-ut\ndoris_home\t{}\nbuild_dir\t{}\n".format(tmp,
 build_dir))
+with open(os.path.join(run_dir, "phases.tsv"), "w") as fh:
+    fh.write("build\t0\t300000\ntotal\t0\t310000\n")
+records = [
+    {"kind": "compile", "src": os.path.join(build_dir, ut_unity.split("/", 
2)[2]),
+     "wall_s": 40.0, "user_s": 38.0, "sys_s": 2.0, "maxrss_mb": 900, "rc": 0},
+    {"kind": "compile", "src": os.path.join(tmp, test_tu),
+     "wall_s": 20.0, "user_s": 19.0, "sys_s": 1.0, "maxrss_mb": 700, "rc": 0},
+    dict(link, maxrss_mb=9000, rc=0, user_s=90.0, sys_s=10.0),
+]
+with open(os.path.join(run_dir, "compile_log.jsonl"), "w") as fh:
+    for record in records:
+        fh.write(json.dumps(record) + "\n")
+with open(os.path.join(run_dir, "ninja_log.txt"), "w") as fh:
+    fh.write("# ninja log v6\n5000\t280000\t0\ttest/doris_be_test\t0\n")
+lines, summary = report.build_report(run_dir, None, 10, "ok")
+text = "\n".join(lines)
+check("flavor is printed", " flavor       : be-ut" in text, True)
+check("area section is printed", "Compile time by area" in text, True)
+check("post-link steps are printed", "+ post-link steps 2m55s" in text, True)
+check("areas in summary", sorted(summary["areas"]), ["be/src", "be/test"])
+check("be/test wall in summary", summary["areas"]["be/test"]["sum_tu_wall_s"], 
20.0)
+check("post-link in summary", 
summary["links"]["doris_be_test"]["post_link_s"], 175.0)
+
+if failures:
+    sys.exit("{} check(s) failed".format(len(failures)))
+PY
+
+if [[ "${failures}" -ne 0 ]]; then
+    echo "${failures} check group(s) failed"
+    exit 1
+fi
+echo "all checks passed"
diff --git a/run-be-ut.sh b/run-be-ut.sh
index 78e24ef9bdc..73e8acceca6 100755
--- a/run-be-ut.sh
+++ b/run-be-ut.sh
@@ -26,6 +26,8 @@
 #     --run --filter=xx  build and run specified ut
 #     --gdb              debug with gdb, does not take effect if --run is not 
specified
 #     --coverage         generate coverage report, does not take effect if 
--gdb is specified
+#     --compile-bench    time a cold, cache-free build of the unit tests (see
+#                        build-support/compile-bench/README.md); does not run 
the tests
 #     -j                 build parallel
 #     -h                 print this help message
 #
@@ -124,6 +126,8 @@ Usage: $0 <options>
      --run --gen_regression_case    generate regression test cases 
corrresponding to ut cases for ut cases that support it
      --gdb              debug with gdb, DOES NOT take effect if --run is not 
specified
      --coverage         generage coverage after run ut, DOES NOT take effect 
if --gdb is specified
+     --compile-bench    time a cold, cache-free build of the unit tests in 
be/ut_build_<type>_compile_bench
+                        and write a report to be/compile-bench-results/; DOES 
NOT run the tests
      -j                 build parallel
      -h                 print this help message
 
@@ -143,11 +147,12 @@ Usage: $0 <options>
     $0 --clean --run                                                clean, 
build and run all tests
     $0 --clean --run --coverage                                     clean, 
build, run all tests and generate coverage report
     $0 --clean --run --gdb --filter=FooTest.*-FooTest.Bar           clean, 
build, run all tests and debug FooTest with gdb
+    $0 --compile-bench -j 6                                         benchmark 
a cold build of the tests and report the slowest files
   "
     exit 1
 }
 
-if ! OPTS="$(getopt -n "$0" -o vhj:f: -l 
gen_out,gen_regression_case,coverage,benchmark,run,gdb,clean,jemalloc-hook,filter:
 -- "$@")"; then
+if ! OPTS="$(getopt -n "$0" -o vhj:f: -l 
gen_out,gen_regression_case,coverage,benchmark,run,gdb,clean,jemalloc-hook,compile-bench,filter:
 -- "$@")"; then
     usage
 fi
 
@@ -156,6 +161,7 @@ eval set -- "${OPTS}"
 CLEAN=0
 RUN=0
 JEMALLOC_HOOK=0
+COMPILE_BENCH=0
 GDB=0
 DENABLE_CLANG_COVERAGE='OFF'
 BUILD_AZURE='ON'
@@ -177,6 +183,10 @@ if [[ "$#" != 1 ]]; then
             JEMALLOC_HOOK=1
             shift
             ;;
+        --compile-bench)
+            COMPILE_BENCH=1
+            shift
+            ;;
         --gdb)
             GDB=1
             shift
@@ -221,7 +231,7 @@ fi
 # unrelated submodules or configuring the sanitizer build.
 if [[ "${JEMALLOC_HOOK}" -eq 1 ]]; then
     # These modes belong to the sanitizer BE UT, not the native allocator test.
-    if [[ "${GDB}" -eq 1 || "${DENABLE_CLANG_COVERAGE}" == 'ON' || -n 
"${GEN_OUT}${GEN_REGRESSION_CASE}" ]]; then
+    if [[ "${GDB}" -eq 1 || "${DENABLE_CLANG_COVERAGE}" == 'ON' || -n 
"${GEN_OUT}${GEN_REGRESSION_CASE}" || "${COMPILE_BENCH}" -eq 1 ]]; then
         echo "--jemalloc-hook supports --run, --filter, --clean and -j"
         exit 1
     fi
@@ -242,6 +252,31 @@ fi
 CMAKE_BUILD_TYPE="${BUILD_TYPE_UT:-ASAN}"
 CMAKE_BUILD_TYPE="$(echo "${CMAKE_BUILD_TYPE}" | awk '{ print(toupper($0)) }')"
 
+# The UT build is a compile-and-run loop, not a debugger session: line tables
+# keep stack traces, perf and addr2line working, and drop the variable-level
+# DWARF that dominates the object files (sampled be/test TUs: -6% compile cpu,
+# objects -91%). Ask for the full DWARF back with DORIS_DEV_DEBUG_INFO=full.
+# Only default it in under clang -- gcc has no -gline-tables-only.
+# Settled before the benchmark starts so that its record carries the real 
value.
+if [[ -z "${DORIS_DEV_DEBUG_INFO}" ]] && [[ "${DORIS_TOOLCHAIN}" == 'clang' 
]]; then
+    DORIS_DEV_DEBUG_INFO='line-tables'
+fi
+
+COMPILE_BENCH_CMAKE_ARGS=()
+if [[ "${COMPILE_BENCH}" -eq 1 ]]; then
+    # Running the tests would mix their run time into a build benchmark.
+    if [[ "${RUN}" -eq 1 ]]; then
+        echo "--compile-bench times the build only; run the tests in a 
separate invocation"
+        exit 1
+    fi
+    # Same benchmark as build.sh --compile-bench: ccache off, the timing
+    # wrapper as compiler and linker launcher, an always-cold build dir.
+    # shellcheck source=build-support/compile-bench/bench-lib.sh
+    . "${DORIS_HOME}/build-support/compile-bench/bench-lib.sh"
+    compile_bench_init "${DORIS_HOME}" "${CMAKE_BUILD_TYPE}" \
+        "${DORIS_HOME}/be/ut_build_${CMAKE_BUILD_TYPE}_compile_bench" "be-ut"
+fi
+
 EXTRA_BE_MODULES="${EXTRA_BE_MODULES:-}"
 parse_extra_be_modules "${EXTRA_BE_MODULES}"
 
@@ -288,12 +323,18 @@ update_submodule() {
 # unconditionally, and its cmake-protect target add_subdirectory()s both faiss 
and openblas,
 # so the configure step fails outright when either is missing. The H3 wrapper 
also
 # requires its submodule to be initialized before configuring BE.
+if [[ "${COMPILE_BENCH}" -eq 1 ]]; then
+    compile_bench_phase_begin "contrib_submodules"
+fi
 update_submodule "contrib/datasketches-cpp" "datasketches-cpp" 
"https://github.com/apache/datasketches-cpp/archive/refs/heads/master.tar.gz";
 update_submodule "contrib/apache-orc" "apache-orc" 
"https://github.com/apache/doris-thirdparty/archive/refs/heads/orc.tar.gz";
 update_submodule "contrib/clucene" "clucene" 
"https://github.com/apache/doris-thirdparty/archive/refs/heads/clucene.tar.gz";
 update_submodule "contrib/openblas" "openblas" 
"https://github.com/apache/doris-thirdparty/archive/refs/heads/openblas.tar.gz";
 update_submodule "contrib/faiss" "faiss" 
"https://github.com/apache/doris-thirdparty/archive/refs/heads/faiss.tar.gz";
 update_submodule "contrib/h3" "h3" 
"https://github.com/uber/h3/archive/refs/tags/v4.5.0.tar.gz";
+if [[ "${COMPILE_BENCH}" -eq 1 ]]; then
+    compile_bench_phase_end
+fi
 
 if [[ "_${DENABLE_CLANG_COVERAGE}" == "_ON" ]]; then
     echo "export DORIS_TOOLCHAIN=clang" >>custom_env.sh
@@ -303,7 +344,13 @@ if [[ "$(echo "${DISABLE_BUILD_AZURE}" | tr '[:lower:]' 
'[:upper:]')" == "ON" ]]
     BUILD_AZURE='OFF'
 fi
 
-if [[ -z ${CMAKE_BUILD_DIR} ]]; then
+if [[ "${COMPILE_BENCH}" -eq 1 ]]; then
+    # Dedicated always-cold build dir: no reused objects, no reused CMake
+    # cache, and the developer's normal build dir stays untouched.
+    CMAKE_BUILD_DIR="${COMPILE_BENCH_BUILD_DIR}"
+    echo "Compile-bench: recreating build dir ${CMAKE_BUILD_DIR} from scratch"
+    rm -rf "${CMAKE_BUILD_DIR}"
+elif [[ -z ${CMAKE_BUILD_DIR} ]]; then
     CMAKE_BUILD_DIR="${DORIS_HOME}/be/ut_build_${CMAKE_BUILD_TYPE}"
 fi
 if [[ "${CLEAN}" -eq 1 ]]; then
@@ -347,15 +394,6 @@ if [[ -z "${ENABLE_INJECTION_POINT}" ]]; then
     ENABLE_INJECTION_POINT='ON'
 fi
 
-# The UT build is a compile-and-run loop, not a debugger session: line tables
-# keep stack traces, perf and addr2line working, and drop the variable-level
-# DWARF that dominates the object files (sampled be/test TUs: -6% compile cpu,
-# objects -91%). Ask for the full DWARF back with DORIS_DEV_DEBUG_INFO=full.
-# Only default it in under clang -- gcc has no -gline-tables-only.
-if [[ -z "${DORIS_DEV_DEBUG_INFO}" ]] && [[ "${DORIS_TOOLCHAIN}" == 'clang' 
]]; then
-    DORIS_DEV_DEBUG_INFO='line-tables'
-fi
-
 MAKE_PROGRAM="$(command -v "${BUILD_SYSTEM}")"
 echo "-- Make program: ${MAKE_PROGRAM}"
 echo "-- Use ccache: ${CMAKE_USE_CCACHE_CXX} and ${CMAKE_USE_CCACHE_C}"
@@ -369,6 +407,9 @@ else
 fi
 
 cd "${CMAKE_BUILD_DIR}"
+if [[ "${COMPILE_BENCH}" -eq 1 ]]; then
+    compile_bench_phase_begin "cmake_configure"
+fi
 "${CMAKE_CMD}" -G "${GENERATOR}" \
     -DCMAKE_MAKE_PROGRAM="${MAKE_PROGRAM}" \
     -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \
@@ -391,7 +432,22 @@ cd "${CMAKE_BUILD_DIR}"
     -DDORIS_JAVA_HOME="${JAVA_HOME}" \
     -DBUILD_AZURE="${BUILD_AZURE}" \
     "${BE_EXTRA_CMAKE_ARGS[@]}" \
+    "${COMPILE_BENCH_CMAKE_ARGS[@]}" \
     "${DORIS_HOME}/be"
+if [[ "${COMPILE_BENCH}" -eq 1 ]]; then
+    compile_bench_phase_end
+
+    compile_bench_phase_begin "build"
+    set +e
+    "${BUILD_SYSTEM}" -j "${PARALLEL}"
+    compile_bench_build_rc=$?
+    set -e
+    compile_bench_phase_end
+
+    # Report even a failed build, then stop: --compile-bench never runs tests.
+    compile_bench_finish "${CMAKE_BUILD_DIR}" "${compile_bench_build_rc}"
+    exit "${compile_bench_build_rc}"
+fi
 "${BUILD_SYSTEM}" -j "${PARALLEL}"
 
 if [[ "${RUN}" -ne 1 ]]; then


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to