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 899812a2119 [test](be) Stabilize timing, disk usage, and child waits 
in BE unit tests (#71332)
899812a2119 is described below

commit 899812a211970f3dc68343efefb4c3526d95f03c
Author: Mingyu Chen (Rayner) <[email protected]>
AuthorDate: Thu Dec 3 18:18:45 2026 +0800

    [test](be) Stabilize timing, disk usage, and child waits in BE unit tests 
(#71332)
    
    ### Background
    
    The BE unit tests check profiling counters for prefetch, segment
    read-ahead, and file cache writeback. File cache tests also exercise
    admission under disk pressure, and Python UDF tests force child-exit
    timeouts to verify handoff to a background reaper.
    
    ### What problem does this PR solve?
    
    Issue Number: #71314
    Related PR: #71315 (integration branch), #71322 (macOS Python memory
    test fix), #71328 (file-reader cache capacity fix)
    PR Type: Test
    
    Problem Summary:
    
    On macOS, small copies and planning steps can finish within one clock
    tick and report zero elapsed time. The host's disk usage can push cache
    tests into disk-pressure mode, and a background reaper can consume a
    timeout a Python UDF test reserved for its own child. Scoped callbacks
    make the timed work measurable, the BE test binary supplies simulated
    disk usage, and each thread owns its forced child-exit timeouts.
    
    ### Details
    
    - **Change map:** Six commits add 126 lines and remove 12 lines under
    `be/src`. The tests add 135 lines and remove four.
    
      | Commit | Purpose |
      | --- | --- |
    | JSON prefetch | Count an injected pause in the buffered-copy timer. |
    | Column read-ahead | Count pauses in both window discard and
    current-batch planning. |
    | Partial block writeback | Count an injected pause in the
    merged-fragment copy trace. |
    | File cache disk usage | Supply 50% space and inode usage in the test
    binary and scope explicit pressure levels to the tests that need them. |
    | Python UDF child waits | Give the forcing thread its own countdown and
    test it while the reaper handles another child. |
    | Write-limiter fixtures | Wait for a new cache to finish opening before
    writing blocks so the loader sees an empty directory. |
    
    - **Failure:** On the integration branch, the original JSON `CopyTime`
    assertion failed in 402 of 600 runs. In 200 runs each, the read-ahead
    discard and planning assertions failed 180 and 86 times, respectively,
    and the partial writeback copy assertion failed 157 times. The full-disk
    condition failed 10 of 13 TTL cache tests. The Python reaper regression
    failed in all three runs with a shared countdown.
    - **Cause:** Doris's macOS timer has 1 µs resolution. File cache
    admission uses space and inode usage from the filesystem. The reaper and
    the test thread previously drew from the same timeout countdown.
    - **Stability evidence:** The integration branch passed all 1,000 timing
    checks after the injected pauses. Simulating 95% usage reproduced the
    same 10 TTL failures and the 50% default let all 13 tests pass. The
    Python regression passed three times with a thread-local countdown and
    failed three times after reverting to a shared countdown.
    
    ### Testing
    
    - Registration order on standalone macOS arm64 ASAN ran 331 tests from
    nine suites. All tests changed here passed. There were 326 passes, three
    existing skips and two macOS failures.
    `PythonServerTest.ReadProcessMemoryCurrentProcessSucceeds` reads Linux
    `/proc` and is addressed in #71322.
    `PythonUDFRuntimeTest.WaitChildExitReturnsAlreadyReapedForReapedChild`
    invokes `/bin/true` and is assigned to the later test isolation PR in
    #71314.
    - Shuffle seed 48256 ran the same 331 tests. There were 324 passes, the
    same three skips and four failures. The two additional failures were
    `BlockFileCacheTest.fd_cache_remove` and
    `BlockFileCacheTest.fd_cache_evict`. Their assertions saw file readers
    retained from prior tests. The cache capacity fix is in #71328, and
    clearing the cache between tests is assigned to the later test isolation
    PR.
    - The timing, disk usage, Python timeout and fixture-startup checks
    passed in both orders, including all 12 TTL cases.
    
    ### Notes for Reviewers
    
    - The timer assertions require at least 1 ms of the injected 2 ms pause
    to show up in the specific counter. This leaves room for differences
    between the clock used to sleep and the clock used to measure.
    - The disk override applies to both admission and proactive eviction.
    `statfs()` still detects invalid paths, and the existing disk usage sync
    point can override the simulated value. Default builds compile out the
    new sync points and both simulation hooks.
    - The standalone run exposed a fixture race. A cache loader can see
    test-written blocks before it has recorded the cache version and
    recursively count inodes on the host volume. The three write-limiter
    fixtures now wait for the loader before writing the blocks their
    assertions use.
---
 be/src/io/cache/block_file_cache.cpp               | 38 +++++++++++++
 be/src/io/cache/file_cache_disk_usage.h            | 65 ++++++++++++++++++++++
 .../io/cache/partial_block_writeback_manager.cpp   |  3 +
 be/src/io/fs/buffered_reader.cpp                   |  4 ++
 be/src/storage/segment/column_read_ahead.cpp       |  5 ++
 be/src/udf/python/python_udf_runtime.cpp           | 22 ++++----
 be/src/udf/python/python_udf_runtime.h             |  1 +
 be/test/format_v2/json/json_reader_test.cpp        | 18 ++++++
 be/test/io/cache/block_file_cache_test.cpp         | 31 +++++++++++
 be/test/io/cache/block_file_cache_test_common.h    |  2 +-
 .../cache/partial_block_writeback_manager_test.cpp | 15 ++++-
 .../snii/bench/snii_vs_v3_benchmark_test.cpp       |  2 +
 be/test/storage/segment/column_read_ahead_test.cpp | 27 ++++++++-
 be/test/testutil/run_all_tests.cpp                 |  6 ++
 be/test/udf/python/python_udf_runtime_test.cpp     | 38 +++++++++++++
 15 files changed, 261 insertions(+), 16 deletions(-)

diff --git a/be/src/io/cache/block_file_cache.cpp 
b/be/src/io/cache/block_file_cache.cpp
index bb1653adc3b..3fb960c6c0d 100644
--- a/be/src/io/cache/block_file_cache.cpp
+++ b/be/src/io/cache/block_file_cache.cpp
@@ -51,6 +51,7 @@
 #include "io/cache/block_file_cache_ttl_mgr.h"
 #include "io/cache/file_block.h"
 #include "io/cache/file_cache_common.h"
+#include "io/cache/file_cache_disk_usage.h"
 #include "io/cache/file_cache_io_adaptor.h"
 #include "io/cache/fs_file_cache_storage.h"
 #include "io/cache/inflight_write_buffer_index.h"
@@ -2299,6 +2300,36 @@ void BlockFileCache::change_cache_type(const 
UInt128Wrapper& hash, size_t offset
     }
 }
 
+#ifdef BE_TEST
+namespace {
+// (space << 32 | inode) while a usage is simulated, kRealDiskUsage otherwise. 
One lock-free word
+// rather than an optional behind a mutex: the monitor threads of caches that 
outlive main() (a
+// factory a test leaves in ExecEnv, or a static one destroyed during exit) 
still read it while the
+// process exits, after a static mutex may already have been destroyed.
+constexpr int64_t kRealDiskUsage = -1;
+std::atomic<int64_t> g_simulated_disk_usage {kRealDiskUsage};
+} // namespace
+
+void set_simulated_disk_usage(std::optional<std::pair<int, int>> usage) {
+    if (!usage.has_value()) {
+        g_simulated_disk_usage.store(kRealDiskUsage);
+        return;
+    }
+    const auto [space, inode] = *usage;
+    DORIS_CHECK(space >= 0 && space <= 100) << "simulated space usage " << 
space << "%";
+    DORIS_CHECK(inode >= 0 && inode <= 100) << "simulated inode usage " << 
inode << "%";
+    g_simulated_disk_usage.store((static_cast<int64_t>(space) << 32) | inode);
+}
+
+std::optional<std::pair<int, int>> simulated_disk_usage() {
+    const int64_t packed = g_simulated_disk_usage.load();
+    if (packed == kRealDiskUsage) {
+        return std::nullopt;
+    }
+    return std::pair {static_cast<int>(packed >> 32), static_cast<int>(packed 
& 0xFFFFFFFF)};
+}
+#endif
+
 // @brief: get a path's disk capacity used percent, inode used percent
 // @param: path
 // @param: percent.first disk used percent, percent.second inode used percent
@@ -2320,6 +2351,13 @@ int disk_used_percentage(const std::string& path, 
std::pair<int, int>* percent)
     int inode_percentage = cast_set<int>(inode_free * 100 / inode_total);
     percent->first = capacity_percentage;
     percent->second = 100 - inode_percentage;
+#ifdef BE_TEST
+    // Without this a unit test would see how full the machine's disk is, and 
at 90% every cache
+    // refuses new blocks (file_cache_disk_usage.h). The sync point below 
still overrides it.
+    if (auto usage = simulated_disk_usage(); usage.has_value()) {
+        *percent = *usage;
+    }
+#endif
 
     // Add sync point for testing
     TEST_SYNC_POINT_CALLBACK("BlockFileCache::disk_used_percentage:1", 
percent);
diff --git a/be/src/io/cache/file_cache_disk_usage.h 
b/be/src/io/cache/file_cache_disk_usage.h
new file mode 100644
index 00000000000..c1891d00f3a
--- /dev/null
+++ b/be/src/io/cache/file_cache_disk_usage.h
@@ -0,0 +1,65 @@
+// 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.
+
+#pragma once
+
+#include <optional>
+#include <string>
+#include <utility>
+
+namespace doris::io {
+
+// How full the filesystem holding `path` is: (space used %, inodes used %), 
both rounded up as
+// df(1) rounds them. Returns statfs()'s result and fills `percent` only when 
that is 0.
+// BlockFileCache::check_disk_resource_limit() and 
check_need_evict_cache_in_advance() decide
+// from these two numbers whether the cache must stop growing and evict ahead 
of demand.
+int disk_used_percentage(const std::string& path, std::pair<int, int>* 
percent);
+
+#ifdef BE_TEST
+// Unit tests must not depend on how full the disk of the machine running them 
is. Left to
+// statfs(), a cache whose directory sits on a 90% full disk enters disk 
resource limit mode, where
+// a block is admitted only after five times its size has been evicted. An 
empty cache has nothing
+// to evict, so every block it is asked for comes back SKIP_CACHE, and a test 
of anything that
+// caches passes on one machine and fails on another for a reason it never set 
up.
+//
+// While a usage is simulated, disk_used_percentage() reports it for every 
path instead of the
+// statfs() numbers. statfs() still runs, so a path that does not exist still 
fails. doris_be_test
+// simulates a disk with room to spare for the whole process 
(run_all_tests.cpp); a test that needs
+// another level, such as one past a threshold, sets it with 
ScopedSimulatedDiskUsage.
+// std::nullopt reports the real numbers again.
+void set_simulated_disk_usage(std::optional<std::pair<int, int>> usage);
+std::optional<std::pair<int, int>> simulated_disk_usage();
+
+// Simulates `usage` until it goes out of scope, then restores what was 
simulated before, so a test
+// hands the next one the disk it found.
+class ScopedSimulatedDiskUsage {
+public:
+    explicit ScopedSimulatedDiskUsage(std::optional<std::pair<int, int>> usage)
+            : _previous(simulated_disk_usage()) {
+        set_simulated_disk_usage(usage);
+    }
+    ~ScopedSimulatedDiskUsage() { set_simulated_disk_usage(_previous); }
+
+    ScopedSimulatedDiskUsage(const ScopedSimulatedDiskUsage&) = delete;
+    ScopedSimulatedDiskUsage& operator=(const ScopedSimulatedDiskUsage&) = 
delete;
+
+private:
+    const std::optional<std::pair<int, int>> _previous;
+};
+#endif
+
+} // namespace doris::io
diff --git a/be/src/io/cache/partial_block_writeback_manager.cpp 
b/be/src/io/cache/partial_block_writeback_manager.cpp
index 8d40c6f7471..a1647bfb17a 100644
--- a/be/src/io/cache/partial_block_writeback_manager.cpp
+++ b/be/src/io/cache/partial_block_writeback_manager.cpp
@@ -166,6 +166,9 @@ struct PartialBlockWritebackManager::Task {
 
         
TEST_SYNC_POINT("PartialBlockWritebackManager::try_submit:before_merge_copy");
         const auto copy_start = trace.now();
+        // A small copy can take less than one tick of the clock (1 us on 
macOS); tests pause here
+        // to check that its time is counted.
+        TEST_SYNC_POINT("PartialBlockWritebackManager::try_submit:merge_copy");
         std::memcpy(buffer->data() + fragment_offset, data.data, data.size);
         trace.copy_ns += trace.now() - copy_start;
         trace.copied_bytes += data.size;
diff --git a/be/src/io/fs/buffered_reader.cpp b/be/src/io/fs/buffered_reader.cpp
index 1c784794d5f..37637e09965 100644
--- a/be/src/io/fs/buffered_reader.cpp
+++ b/be/src/io/fs/buffered_reader.cpp
@@ -31,6 +31,7 @@
 #include "common/config.h"
 #include "common/status.h"
 #include "core/custom_allocator.h"
+#include "cpp/sync_point.h"
 #include "runtime/exec_env.h"
 #include "runtime/file_scan_profile.h"
 #include "runtime/runtime_profile.h"
@@ -609,6 +610,9 @@ Status PrefetchBuffer::read_buffer(size_t off, const char* 
out, size_t buf_len,
         size_t read_len = std::min({buf_len, _offset + _size - off, _offset + 
_len - off});
         {
             SCOPED_RAW_TIMER(&_statis.copy_time);
+            // A copy can take less than one tick of the clock (1 us on 
macOS); tests pause here to
+            // check that its time is counted.
+            TEST_SYNC_POINT("PrefetchBuffer::read_buffer:copy");
             memcpy((void*)out, _buf.data() + (off - _offset), read_len);
         }
         *bytes_read = read_len;
diff --git a/be/src/storage/segment/column_read_ahead.cpp 
b/be/src/storage/segment/column_read_ahead.cpp
index 2aa34adb6ac..970d2c05ecf 100644
--- a/be/src/storage/segment/column_read_ahead.cpp
+++ b/be/src/storage/segment/column_read_ahead.cpp
@@ -23,6 +23,7 @@
 
 #include "common/cast_set.h"
 #include "common/logging.h"
+#include "cpp/sync_point.h"
 #include "io/fs/read_ahead_metrics.h"
 #include "runtime/runtime_profile.h"
 
@@ -91,6 +92,9 @@ void ColumnReadAhead::plan(const rowid_t* current_rowids, 
size_t count,
     _discard_passed_pages(_page_for_ordinal(current_rowids[_reverse ? count - 
1 : 0]).page_index,
                           output);
     SCOPED_RAW_TIMER(&output->current_batch_plan_ns);
+    // This and the discard below can take less than one tick of the clock (1 
us on macOS); tests
+    // pause in them to check that their time is counted.
+    TEST_SYNC_POINT("ColumnReadAhead::plan:current_batch");
     const rowid_t* begin = current_rowids;
     const rowid_t* end = current_rowids + count;
     while (begin != end) {
@@ -181,6 +185,7 @@ void ColumnReadAhead::_add_page(const ColumnReadAheadPage& 
page, ColumnReadAhead
 
 void ColumnReadAhead::_discard_passed_pages(int32_t page_index, 
ColumnReadAheadPlan* output) {
     SCOPED_RAW_TIMER(&output->window_discard_ns);
+    TEST_SYNC_POINT("ColumnReadAhead::_discard_passed_pages");
     // Only the prefix/suffix behind the reader can retire; the rest of the 
window stays intact.
     auto entry = _reverse ? _window.upper_bound(page_index) : _window.begin();
     while (entry != _window.end() && (_reverse || entry->first < page_index)) {
diff --git a/be/src/udf/python/python_udf_runtime.cpp 
b/be/src/udf/python/python_udf_runtime.cpp
index aa87360cbc3..fc96a021e8f 100644
--- a/be/src/udf/python/python_udf_runtime.cpp
+++ b/be/src/udf/python/python_udf_runtime.cpp
@@ -31,9 +31,6 @@
 #include <deque>
 #include <mutex>
 #include <thread>
-#ifdef BE_TEST
-#include <atomic>
-#endif
 
 #include "common/logging.h"
 #include "runtime/thread_context.h"
@@ -48,17 +45,18 @@ static constexpr std::chrono::milliseconds 
PROCESS_TERMINATE_TIMEOUT {1000};
 static constexpr std::chrono::milliseconds BACKGROUND_REAP_INTERVAL {1000};
 
 #ifdef BE_TEST
-static std::atomic<int> FORCED_CHILD_EXIT_TIMEOUTS {0};
+// The waits that force_child_exit_timeouts_for_test() turns into timeouts are 
the calling
+// thread's. The background reaper waits on a thread of its own for the pids 
it owns: with one
+// count for the whole process, a pid an earlier test had left to the reaper 
made the reaper take
+// a timeout forced for a test's own shutdown() or fork(), whose child then 
really exited.
+static thread_local int forced_child_exit_timeouts = 0;
 
 static bool consume_forced_child_exit_timeout() {
-    int remaining = FORCED_CHILD_EXIT_TIMEOUTS.load(std::memory_order_relaxed);
-    while (remaining > 0) {
-        if (FORCED_CHILD_EXIT_TIMEOUTS.compare_exchange_weak(remaining, 
remaining - 1,
-                                                             
std::memory_order_relaxed)) {
-            return true;
-        }
+    if (forced_child_exit_timeouts == 0) {
+        return false;
     }
-    return false;
+    --forced_child_exit_timeouts;
+    return true;
 }
 #endif
 
@@ -153,7 +151,7 @@ bool 
PythonUDFProcess::wait_background_reaped_for_test(pid_t pid,
 }
 
 void PythonUDFProcess::force_child_exit_timeouts_for_test(int count) {
-    FORCED_CHILD_EXIT_TIMEOUTS.store(count, std::memory_order_relaxed);
+    forced_child_exit_timeouts = count;
 }
 #endif
 
diff --git a/be/src/udf/python/python_udf_runtime.h 
b/be/src/udf/python/python_udf_runtime.h
index 2d635dc11a1..2587f35321f 100644
--- a/be/src/udf/python/python_udf_runtime.h
+++ b/be/src/udf/python/python_udf_runtime.h
@@ -98,6 +98,7 @@ public:
 
     static bool wait_background_reaped_for_test(pid_t pid, 
std::chrono::milliseconds timeout);
 
+    // The calling thread's next `count` waits for a child report a timeout 
without waiting.
     static void force_child_exit_timeouts_for_test(int count);
 #endif
 
diff --git a/be/test/format_v2/json/json_reader_test.cpp 
b/be/test/format_v2/json/json_reader_test.cpp
index e072f690118..9dc0def0216 100644
--- a/be/test/format_v2/json/json_reader_test.cpp
+++ b/be/test/format_v2/json/json_reader_test.cpp
@@ -21,6 +21,7 @@
 
 #include <algorithm>
 #include <atomic>
+#include <chrono>
 #include <cstring>
 #include <filesystem>
 #include <fstream>
@@ -48,6 +49,7 @@
 #include "core/data_type/data_type_struct.h"
 #include "core/value/jsonb_value.h"
 #include "cpp/obj-storage/client/obj_storage_client_factory.h"
+#include "cpp/sync_point.h"
 #include "exec/scan/scanner.h"
 #include "exprs/vexpr.h"
 #include "exprs/vexpr_context.h"
@@ -561,6 +563,13 @@ TEST_F(JsonReaderSplitTest, FourRangesPreserveEveryRecord) 
{
 // Cover line scans, whole-document scans, and schema probes through the same 
S3 reader lifecycle.
 class JsonReaderPrefetchTest : public testing::TestWithParam<int> {
 protected:
+    // Each copy out of the prefetch buffer pauses this long. A copy of this 
small fixture takes
+    // less than one tick of the clock on some platforms (1 us on macOS) and 
would count as 0.
+    static constexpr auto kCopyPause = std::chrono::milliseconds(2);
+    // At least half of it must show in CopyTime: the pause and the timer use 
different clocks.
+    static constexpr int64_t kMinCopyTimeNs =
+            
std::chrono::duration_cast<std::chrono::nanoseconds>(kCopyPause).count() / 2;
+
     static void read_rows(JsonReader& reader, RuntimeState& state) {
         ASSERT_TRUE(reader.init(&state).ok());
         std::vector<ColumnDefinition> schema;
@@ -599,6 +608,7 @@ protected:
             EXPECT_GT(counter->value(), 0) << name;
             snapshots.emplace_back(counter, counter->value());
         }
+        EXPECT_GE(profile.get_counter("CopyTime")->value(), kMinCopyTimeNs);
         ASSERT_TRUE(reader.close().ok());
         for (const auto& [counter, collected] : snapshots) {
             EXPECT_EQ(counter->value(), collected);
@@ -610,7 +620,15 @@ TEST_P(JsonReaderPrefetchTest, 
ClosePublishesReadStatisticsOnce) {
     auto* env = ExecEnv::GetInstance();
     auto saved_pool = std::move(env->_buffered_reader_prefetch_thread_pool);
     const auto saved_in_memory_size = config::in_memory_file_size;
+    auto* sync_point = SyncPoint::get_instance();
+    SyncPoint::CallbackGuard copy_guard;
+    sync_point->set_call_back(
+            "PrefetchBuffer::read_buffer:copy",
+            [](auto&&) { std::this_thread::sleep_for(kCopyPause); }, 
&copy_guard);
+    sync_point->enable_processing();
     Defer restore([&] {
+        sync_point->disable_processing();
+        sync_point->clear_all_call_backs();
         env->_buffered_reader_prefetch_thread_pool.reset();
         env->_buffered_reader_prefetch_thread_pool = std::move(saved_pool);
         config::in_memory_file_size = saved_in_memory_size;
diff --git a/be/test/io/cache/block_file_cache_test.cpp 
b/be/test/io/cache/block_file_cache_test.cpp
index 4976fa7020e..ede9bedec02 100644
--- a/be/test/io/cache/block_file_cache_test.cpp
+++ b/be/test/io/cache/block_file_cache_test.cpp
@@ -666,6 +666,9 @@ TEST_F(BlockFileCacheTest, 
get_or_set_remote_scan_cache_write_limiter_admission)
 
     io::BlockFileCache mgr(local_cache_path, 
remote_only_on_miss_test_settings());
     ASSERT_TRUE(mgr.initialize().ok());
+    // Let the loader see an empty cache before writing blocks. A nonempty 
cache without a
+    // version file can make the loader walk the host filesystem to estimate 
its file count.
+    ASSERT_NO_FATAL_FAILURE(wait_until_cache_ready(mgr));
 
     TUniqueId query_id;
     query_id.hi = 5;
@@ -708,6 +711,7 @@ TEST_F(BlockFileCacheTest, 
get_or_set_remote_scan_cache_write_limiter_is_query_w
 
     io::BlockFileCache mgr(local_cache_path, 
remote_only_on_miss_test_settings());
     ASSERT_TRUE(mgr.initialize().ok());
+    ASSERT_NO_FATAL_FAILURE(wait_until_cache_ready(mgr));
 
     TUniqueId query_id;
     query_id.hi = 15;
@@ -771,6 +775,7 @@ TEST_F(BlockFileCacheTest, 
get_or_set_remote_scan_cache_write_limiter_segment_me
 
     io::BlockFileCache mgr(local_cache_path, 
remote_only_on_miss_test_settings());
     ASSERT_TRUE(mgr.initialize().ok());
+    ASSERT_NO_FATAL_FAILURE(wait_until_cache_ready(mgr));
 
     TUniqueId query_id;
     query_id.hi = 25;
@@ -6583,6 +6588,9 @@ TEST_F(BlockFileCacheTest, 
test_check_disk_reource_limit_2) {
         fs::remove_all(cache_base_path);
     }
     fs::create_directories(cache_base_path);
+    // Above the 2% enter threshold below. Declared before the cache so that 
it outlives the
+    // cache's monitor thread.
+    io::ScopedSimulatedDiskUsage disk_usage(std::pair {10, 1});
     io::FileCacheSettings settings;
     settings.index_queue_size = 30;
     settings.index_queue_elements = 5;
@@ -6614,6 +6622,9 @@ TEST_F(BlockFileCacheTest, 
test_check_disk_reource_limit_3) {
         fs::remove_all(cache_base_path);
     }
     fs::create_directories(cache_base_path);
+    // Both just below the 98% exit threshold below. Declared before the cache 
so that it outlives
+    // the cache's monitor thread.
+    io::ScopedSimulatedDiskUsage disk_usage(std::pair {97, 97});
     io::FileCacheSettings settings;
     settings.index_queue_size = 30;
     settings.index_queue_elements = 5;
@@ -6638,6 +6649,26 @@ TEST_F(BlockFileCacheTest, 
test_check_disk_reource_limit_3) {
     }
 }
 
+// doris_be_test never lets a cache see how full this machine's disk is 
(run_all_tests.cpp).
+TEST_F(BlockFileCacheTest, simulated_disk_usage_replaces_the_statfs_numbers) {
+    const auto found = io::simulated_disk_usage();
+    ASSERT_TRUE(found.has_value());
+    {
+        io::ScopedSimulatedDiskUsage full(std::pair {95, 3});
+        std::pair<int, int> percent {-1, -1};
+        ASSERT_EQ(0, disk_used_percentage(caches_dir.string(), &percent));
+        EXPECT_EQ(std::pair(95, 3), percent);
+        // statfs() still runs, so a missing directory is still an error.
+        EXPECT_NE(0, disk_used_percentage("/non/existent/path/OOXXOO", 
&percent));
+        {
+            io::ScopedSimulatedDiskUsage real(std::nullopt);
+            EXPECT_FALSE(io::simulated_disk_usage().has_value());
+        }
+        EXPECT_EQ(std::optional(std::pair(95, 3)), io::simulated_disk_usage());
+    }
+    EXPECT_EQ(found, io::simulated_disk_usage());
+}
+
 TEST_F(BlockFileCacheTest, test_check_disk_resource_limit_hysteresis) {
     if (fs::exists(cache_base_path)) {
         fs::remove_all(cache_base_path);
diff --git a/be/test/io/cache/block_file_cache_test_common.h 
b/be/test/io/cache/block_file_cache_test_common.h
index a8311e52e18..c176a24f8b6 100644
--- a/be/test/io/cache/block_file_cache_test_common.h
+++ b/be/test/io/cache/block_file_cache_test_common.h
@@ -59,6 +59,7 @@
 #include "io/cache/cached_remote_file_reader.h"
 #include "io/cache/file_block.h"
 #include "io/cache/file_cache_common.h"
+#include "io/cache/file_cache_disk_usage.h"
 #include "io/cache/fs_file_cache_storage.h"
 #include "io/fs/path.h"
 #include "runtime/exec_env.h"
@@ -69,7 +70,6 @@
 namespace doris::io {
 namespace fs = std::filesystem;
 
-extern int disk_used_percentage(const std::string& path, std::pair<int, int>* 
percent);
 extern fs::path caches_dir;
 extern std::string cache_base_path;
 extern std::string tmp_file;
diff --git a/be/test/io/cache/partial_block_writeback_manager_test.cpp 
b/be/test/io/cache/partial_block_writeback_manager_test.cpp
index 64590d2739d..4f3437fe064 100644
--- a/be/test/io/cache/partial_block_writeback_manager_test.cpp
+++ b/be/test/io/cache/partial_block_writeback_manager_test.cpp
@@ -1062,6 +1062,19 @@ TEST_F(PartialBlockWritebackManagerTest, 
UsesReadWorkersConcurrentlyAndDeduplica
 }
 
 TEST_F(PartialBlockWritebackManagerTest, TracesDelayedScansAndMergedFragments) 
{
+    // Copying a 3 KB fragment takes less than one tick of the clock on some 
platforms (1 us on
+    // macOS) and would count as 0: the copy pauses for 2 ms, and at least 
half of that must show
+    // (the pause and the timer use different clocks).
+    auto* sync_point = SyncPoint::get_instance();
+    SyncPoint::CallbackGuard merge_copy_guard;
+    sync_point->set_call_back(
+            "PartialBlockWritebackManager::try_submit:merge_copy",
+            [](auto&&) { std::this_thread::sleep_for(2ms); }, 
&merge_copy_guard);
+    sync_point->enable_processing();
+    Defer clear_sync_point {[&]() {
+        sync_point->disable_processing();
+        sync_point->clear_all_call_backs();
+    }};
     ReadIOTraceCapture trace;
     auto cache = create_cache("partial_block_trace_delay");
     auto* writer = cache->async_write_manager();
@@ -1108,7 +1121,7 @@ TEST_F(PartialBlockWritebackManagerTest, 
TracesDelayedScansAndMergedFragments) {
     EXPECT_EQ(submissions[1]["id"].GetUint64(), 
submissions[0]["id"].GetUint64());
     EXPECT_EQ(submissions[1]["details"]["allocation_ns"].GetInt64(), 0);
     EXPECT_EQ(submissions[1]["details"]["copied_bytes"].GetInt64(), 3072);
-    EXPECT_GT(submissions[1]["details"]["copy_ns"].GetInt64(), 0);
+    EXPECT_GE(submissions[1]["details"]["copy_ns"].GetInt64(), 1'000'000);
     EXPECT_GT(submissions[1]["details"]["lifecycle_trace_ns"].GetInt64(), 0);
     for (const auto& scan : trace.events("hole_queue_scan")) {
         EXPECT_STREQ(scan["query"].GetString(), "unknown");
diff --git 
a/be/test/storage/index/inverted/snii/bench/snii_vs_v3_benchmark_test.cpp 
b/be/test/storage/index/inverted/snii/bench/snii_vs_v3_benchmark_test.cpp
index bed22380699..fcb6367dee2 100644
--- a/be/test/storage/index/inverted/snii/bench/snii_vs_v3_benchmark_test.cpp
+++ b/be/test/storage/index/inverted/snii/bench/snii_vs_v3_benchmark_test.cpp
@@ -876,6 +876,8 @@ protected:
         // enters disk resource limit mode: its background thread then evicts 
everything as fast as
         // the write path caches it, so the cache stays empty no matter what 
write_file_cache says.
         // The repo checkout sits on a 98%-full disk, which is what silently 
disabled caching here.
+        // doris_be_test now simulates a half-full disk for every cache 
(run_all_tests.cpp), so the
+        // mode no longer kicks in, but the cache files still need that space.
         const char* cache_root = std::getenv("SNII_BENCH_CACHE_DIR");
         _file_cache_dir = (cache_root != nullptr && *cache_root != '\0')
                                   ? std::string(cache_root) + "/" + 
kCacheDirPrefix +
diff --git a/be/test/storage/segment/column_read_ahead_test.cpp 
b/be/test/storage/segment/column_read_ahead_test.cpp
index 52d68839aa8..ae54e1a7179 100644
--- a/be/test/storage/segment/column_read_ahead_test.cpp
+++ b/be/test/storage/segment/column_read_ahead_test.cpp
@@ -19,13 +19,17 @@
 
 #include <gtest/gtest.h>
 
+#include <chrono>
 #include <limits>
 #include <memory>
 #include <numeric>
+#include <thread>
 #include <vector>
 
 #include "common/cast_set.h"
+#include "cpp/sync_point.h"
 #include "io/fs/read_ahead_metrics.h"
+#include "util/defer_op.h"
 
 namespace doris::segment_v2 {
 namespace {
@@ -185,6 +189,25 @@ TEST(ColumnReadAheadTest, 
SparsePredictionUsesOnlySelectedRows) {
 }
 
 TEST(ColumnReadAheadTest, ConsumedPageIsNotPlannedAgainWithinSamePage) {
+    // The discard and the current batch planning of the second call take less 
than one tick of
+    // the clock on some platforms (1 us on macOS) and would count as 0: each 
pauses for 2 ms, and
+    // at least half of that must show (the pause and the timer use different 
clocks).
+    constexpr auto pause = std::chrono::milliseconds(2);
+    constexpr int64_t min_counted_ns = 1000 * 1000;
+    auto* sync_point = SyncPoint::get_instance();
+    SyncPoint::CallbackGuard discard_guard;
+    SyncPoint::CallbackGuard current_batch_guard;
+    sync_point->set_call_back(
+            "ColumnReadAhead::_discard_passed_pages",
+            [&](auto&&) { std::this_thread::sleep_for(pause); }, 
&discard_guard);
+    sync_point->set_call_back(
+            "ColumnReadAhead::plan:current_batch",
+            [&](auto&&) { std::this_thread::sleep_for(pause); }, 
&current_batch_guard);
+    sync_point->enable_processing();
+    Defer clear_sync_point {[&]() {
+        sync_point->disable_processing();
+        sync_point->clear_all_call_backs();
+    }};
     auto window = create_window({30, 30, 30}, {.window_bytes = 30});
     const auto rows = all_rows(300);
     ColumnReadAheadPlan plan;
@@ -201,8 +224,8 @@ TEST(ColumnReadAheadTest, 
ConsumedPageIsNotPlannedAgainWithinSamePage) {
     EXPECT_TRUE(plan.new_pages.empty());
     EXPECT_EQ(window->pending_bytes(), 30);
     EXPECT_FALSE(window->pending(0));
-    EXPECT_GT(plan.current_batch_plan_ns, 0);
-    EXPECT_GT(plan.window_discard_ns, 0);
+    EXPECT_GE(plan.current_batch_plan_ns, min_counted_ns);
+    EXPECT_GE(plan.window_discard_ns, min_counted_ns);
     // The reused output records this call only, including calls that produce 
no new pages.
     EXPECT_EQ(plan.window_extend_ns, 0);
 }
diff --git a/be/test/testutil/run_all_tests.cpp 
b/be/test/testutil/run_all_tests.cpp
index b79cf2beaf1..fe1b766fa4a 100644
--- a/be/test/testutil/run_all_tests.cpp
+++ b/be/test/testutil/run_all_tests.cpp
@@ -25,6 +25,7 @@
 #include "cpp/aws_sdk.h"
 #include "format/orc/orc_memory_pool.h"
 #include "gtest/gtest.h"
+#include "io/cache/file_cache_disk_usage.h"
 #include "runtime/exec_env.h"
 #include "runtime/memory/cache_manager.h"
 #include "runtime/memory/thread_mem_tracker_mgr.h"
@@ -104,6 +105,11 @@ int main(int argc, char** argv) {
     doris::BackendOptions::init();
     doris::TimezoneUtils::load_timezones_to_cache();
     doris::ExecEnv::GetInstance()->init_fluss_union_tail_cache();
+    // A file cache decides from statfs() of its directory whether the disk is 
too full to keep
+    // caching, so every test that caches would otherwise follow how full this 
machine's disk is:
+    // at 90% each cache refuses every block. 50% is clear of all the enter 
and exit thresholds
+    // (85-90% by default); a test that needs pressure uses 
io::ScopedSimulatedDiskUsage.
+    doris::io::set_simulated_disk_usage(std::pair {50, 50});
 
     auto service = 
std::make_unique<doris::HttpService>(doris::ExecEnv::GetInstance(), 0, 1);
     auto status = service->start();
diff --git a/be/test/udf/python/python_udf_runtime_test.cpp 
b/be/test/udf/python/python_udf_runtime_test.cpp
index 4b07b0b7fb8..f3ead55c85f 100644
--- a/be/test/udf/python/python_udf_runtime_test.cpp
+++ b/be/test/udf/python/python_udf_runtime_test.cpp
@@ -260,6 +260,44 @@ TEST_F(PythonUDFRuntimeTest, 
ShutdownEnqueuesBackgroundReapWhenSigkillWaitTimesO
                                                                   
std::chrono::milliseconds(5000)));
 }
 
+// The background reaper waits for its pids on a thread of its own. It must 
not take the forced
+// wait results that a test asks for on its own thread: when an earlier test 
had left a pid to the
+// reaper, 
PythonServerTest.ForkEnqueuesBackgroundReapWhenKilledStartFailureIsNotReaped 
lost one of
+// its two forced timeouts to the reaper's wait and saw its child really exit 
after SIGKILL.
+TEST_F(PythonUDFRuntimeTest, ForcedChildExitTimeoutsBelongToTheCallingThread) {
+    // Two children that exit at once and that nobody reaps yet: one for the 
reaper, one for this
+    // thread.
+    const pid_t reaper_child = fork();
+    if (reaper_child == 0) {
+        _exit(0);
+    }
+    const pid_t own_child = fork();
+    if (own_child == 0) {
+        _exit(0);
+    }
+    ASSERT_GT(reaper_child, 0);
+    ASSERT_GT(own_child, 0);
+    // Without reaping it (WNOWAIT), wait until the reaper's child has exited, 
so the reaper reaps
+    // it in its first wait: a reaper that took this thread's forced timeout 
there reaps it a round
+    // (1 s) later instead.
+    siginfo_t exited {};
+    ASSERT_EQ(0, waitid(P_PID, reaper_child, &exited, WEXITED | WNOWAIT));
+
+    PythonUDFProcess::force_child_exit_timeouts_for_test(1);
+    PythonUDFProcess::enqueue_child_for_reap(reaper_child);
+    EXPECT_TRUE(PythonUDFProcess::wait_background_reaped_for_test(reaper_child,
+                                                                  
std::chrono::milliseconds(5000)));
+    // The reaper has waited for its child, and this thread's forced timeout 
is still there.
+    int exit_status = 0;
+    EXPECT_EQ(PythonUDFProcess::ChildExitWaitResult::TIMEOUT,
+              PythonUDFProcess::wait_child_exit(own_child, 
std::chrono::milliseconds(5000),
+                                                &exit_status));
+    PythonUDFProcess::force_child_exit_timeouts_for_test(0);
+    EXPECT_EQ(PythonUDFProcess::ChildExitWaitResult::EXITED,
+              PythonUDFProcess::wait_child_exit(own_child, 
std::chrono::milliseconds(5000),
+                                                &exit_status));
+}
+
 // ============================================================================
 // PythonUDFProcess remove_unix_socket() tests
 // ============================================================================


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

Reply via email to