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 4e77abfc0ed [fix](be) Fix crashes and shutdown races exposed by BE 
unit tests (#71322)
4e77abfc0ed is described below

commit 4e77abfc0ed8b55e24a9f47a2b35051c32cb17f3
Author: Mingyu Chen (Rayner) <[email protected]>
AuthorDate: Thu Dec 3 17:39:12 2026 +0800

    [fix](be) Fix crashes and shutdown races exposed by BE unit tests (#71322)
    
    ### Background
    
    BE pipeline operators queue and recycle data blocks, while the load and
    HTTP services coordinate worker shutdown. The backend also parses packed
    strings, serializes aggregate states for distributed queries, and tracks
    memory used by indexes and Python workers. Several of those paths rely
    on the C++ standard library or operating system for resource handling.
    
    ### What problem does this PR solve?
    
    Issue Number: #71314
    Related PR: #71315 (combined reference patch), #71292 (adjacent
    point-query changes)
    PR Type: Bugfix
    
    Problem Summary:
    
    Address crashes, shutdown hangs, and platform-dependent failures that
    surfaced when running BE unit tests on macOS with ASAN. The fixes keep
    owners alive during teardown, check point-query schema invariants before
    indexing, and pass the right string representation to each reader. The
    profiling, Python UDF memory, and certificate lookup paths now handle
    standard macOS facilities.
    
    ### Details
    
    - **Change map:** 107 additions and 33 deletions in BE code, plus 162
    additions and one deletion in tests.
    1. Capture the exchanger and release queued blocks while shared-state
    counters are live.
    2. Use the string set iterator’s `StringRef` for aggregate output and
    serialization. Add a round-trip test.
    3. Give `sscanf` a bounded, NUL-terminated copy of each accepted ISO
    date string.
    4. Add the hidden delete-sign column to the synthetic point-query
    schema.
      5. Count SNII heap buffers based on where each string stores its data.
      6. Read the current executable argument via `_NSGetArgv()` on macOS.
    7. Read Python worker RSS with `proc_pidinfo` on macOS and exercise
    valid and invalid PIDs.
      8. Append `/etc/ssl/cert.pem` to the backend’s default CA search list.
    9. Synchronize the load-stream count with stream erasure and
    destruction.
    10. Schedule libevent loop exit so it works before dispatch starts. Add
    a deterministically ordered test.
    11. Check the delete-sign index for both tuple shapes before indexing
    the schema.
    - **Frequency:** The memory and platform issues reproduce on the
    affected macOS paths. The load teardown abort and HTTP shutdown hang
    depend on thread timing. The new HTTP test forces shutdown to request
    exit before dispatch.
    - **Root cause:** Exchange teardown followed the owning pointer during
    destruction, and load teardown observed the count mid-erasure. Libevent
    clears a loop-break request at dispatch startup. The expression paths
    read iterator values or packed column strings with the wrong type or
    termination. The remaining paths assumed a valid schema index, libstdc++
    inline string capacity, or Linux filesystem conventions.
    - **Why existing tests missed it:** The affected aggregate, date,
    exchange, and SNII tests relied on Linux library behavior. SQL suites
    for the aggregate, date, and point-lookup paths exercise valid queries.
    They leave invalid synthetic schemas and service shutdown ordering to BE
    unit tests. The prior HTTP tests did not control stop-before-dispatch
    order.
    - **Fix:** Handle ownership and synchronization where the objects are
    destroyed. Use bounded input and explicit schema checks at the existing
    read sites. Select the process APIs by platform and add the CA path as a
    fallback.
    - **Other paths and branches:** The two string aggregate variants share
    the corrected implementation. Point-query checks cover initialization
    with and without a projected delete-sign slot. Release snapshots 3.1
    through 4.2 share the unchecked point-query, load count, pprof,
    loop-break, and CA-list patterns. The date path appears on 3.1 through
    4.2. The affected local exchanger and string aggregates appear on 4.0
    through 4.2. Python worker RSS affects 4.1 and 4.2. SNII heap charging
    affects 4.2. The standalone `CmdlineAction` and cloud service retain
    separate platform paths.
    - **Configs and defaults:** The runtime-mutable `ca_cert_file_paths`
    list appends `/etc/ssl/cert.pem` after the three existing candidates. A
    configured list still takes precedence.
    - **Behavior change:** An invalid point-query schema fails at the
    invariant check. macOS can retrieve the executable argument and worker
    RSS, and the BE can discover the added system CA bundle.
    
    ### Testing
    
    - The original macOS ASAN runs reproduced the aggregate and date parser
    overreads and the local exchange crash. For the point-query regression,
    both tuple shapes hit the out-of-bounds read before the guard. The HTTP
    shutdown test stalled at worker join with the old implementation.
    - The standalone macOS ASAN build passed. The same filter ran 261 tests
    in source order and with shuffle seed 48256. The runs passed 260 and 259
    cases, respectively. The aggregate round trip, shutdown interleaving,
    point-query guards, and platform checks for pprof, Python RSS, and CA
    lookup passed in both orders. The SNII memory accounting suite passed
    all 11 cases in each additional run.
    - Two known macOS test failures remain in the split. Both runs hit a
    fixture that symlinks to the missing `/bin/true` in
    `ProfilerCommandTest.BundledJeprofKeepsLocalProfile`. The shuffled run
    also hit the shared forced-timeout counter in
    
`PythonServerTest.ForkEnqueuesBackgroundReapWhenKilledStartFailureIsNotReaped`.
    Both fixes are tracked in #71314.
    - clang-format 16, the BE build hygiene gates, and clang-tidy passed.
---
 be/src/common/config.cpp                           |  5 +-
 be/src/exec/exchange/local_exchanger.h             | 16 ++++--
 be/src/exec/pipeline/dependency.cpp                |  5 +-
 .../aggregate_function_group_array_set_op.h        |  8 +--
 .../function/function_other_types_to_date.cpp      | 24 ++++++---
 be/src/load/channel/load_stream_mgr.h              | 10 +++-
 be/src/service/http/ev_http_server.cpp             | 15 +++++-
 be/src/service/point_query_executor.cpp            |  4 ++
 .../inverted/snii/format/sampled_term_index.h      | 18 ++++---
 be/src/udf/python/python_server.cpp                | 16 ++++++
 be/src/udf/python/python_server.h                  |  3 +-
 be/src/util/pprof_utils.cpp                        | 14 ++++-
 be/src/util/pprof_utils.h                          |  2 +-
 .../aggregate/agg_group_array_intersect_test.cpp   | 63 ++++++++++++++++++++++
 be/test/service/http/ev_http_server_test.cpp       | 50 +++++++++++++++++
 be/test/service/point_query_exector_test.cpp       | 43 +++++++++++++++
 be/test/udf/python/python_server_test.cpp          |  7 ++-
 17 files changed, 269 insertions(+), 34 deletions(-)

diff --git a/be/src/common/config.cpp b/be/src/common/config.cpp
index e55a398db2d..0e59ff6f9cb 100644
--- a/be/src/common/config.cpp
+++ b/be/src/common/config.cpp
@@ -1901,10 +1901,11 @@ DEFINE_String(jni_plugin_fs_dir, 
"${DORIS_HOME}/plugins/jni_fs");
 DEFINE_Bool(java_plugin_warmup, "false");
 
 // ca_cert_file is in this path by default, Normally no modification is 
required
-// ca cert default path is different from different OS
+// ca cert default path is different from different OS: RHEL/CentOS, 
Debian/Ubuntu, SUSE, then
+// macOS (also Alpine and the BSDs). The first existing file is used.
 DEFINE_mString(ca_cert_file_paths,
                
"/etc/pki/tls/certs/ca-bundle.crt;/etc/ssl/certs/ca-certificates.crt;"
-               "/etc/ssl/ca-bundle.pem");
+               "/etc/ssl/ca-bundle.pem;/etc/ssl/cert.pem");
 
 /** Table sink configurations(currently contains only external table types) **/
 // Minimum data processed to scale writers in exchange when non partition 
writing
diff --git a/be/src/exec/exchange/local_exchanger.h 
b/be/src/exec/exchange/local_exchanger.h
index f1bb9f11052..72cb9b25d44 100644
--- a/be/src/exec/exchange/local_exchanger.h
+++ b/be/src/exec/exchange/local_exchanger.h
@@ -80,8 +80,10 @@ public:
         BlockWrapper(Block&& data_block, LocalExchangeSharedState* 
shared_state, int channel_id)
                 : _data_block(std::move(data_block)),
                   _shared_state(shared_state),
+                  _exchanger(shared_state ? shared_state->exchanger.get() : 
nullptr),
                   _allocated_bytes(_data_block.allocated_bytes()) {
             if (_shared_state) {
+                DCHECK(_exchanger != nullptr);
                 _shared_state->add_total_mem_usage(_allocated_bytes);
             }
         }
@@ -91,14 +93,17 @@ public:
                 // `_channel_ids` may be empty if exchanger is shuffled 
exchanger and channel id is
                 // not used by `sub_total_mem_usage`. So we just pass -1 here.
                 _shared_state->sub_total_mem_usage(_allocated_bytes);
-                if (_shared_state->exchanger->_free_block_limit == 0 ||
-                    _shared_state->exchanger->_free_blocks.size_approx() <
-                            _shared_state->exchanger->_free_block_limit *
-                                    _shared_state->exchanger->_num_sources) {
+                // Blocks still queued when the exchanger is destroyed are 
released by its queues'
+                // destructors. By then `_shared_state->exchanger` may already 
be null (libc++'s
+                // unique_ptr clears itself before deleting), so use the 
exchanger captured at
+                // construction: the ExchangerBase members used here outlive 
the derived queues.
+                if (_exchanger->_free_block_limit == 0 ||
+                    _exchanger->_free_blocks.size_approx() <
+                            _exchanger->_free_block_limit * 
_exchanger->_num_sources) {
                     _data_block.clear_column_data();
                     // Free blocks is used to improve memory efficiency. 
Failure during pushing back
                     // free block will not incur any bad result so just ignore 
the return value.
-                    
_shared_state->exchanger->_free_blocks.enqueue(std::move(_data_block));
+                    _exchanger->_free_blocks.enqueue(std::move(_data_block));
                 }
             };
         }
@@ -121,6 +126,7 @@ public:
 
         Block _data_block;
         LocalExchangeSharedState* _shared_state;
+        ExchangerBase* _exchanger;
         std::vector<int> _channel_ids;
         const size_t _allocated_bytes;
     };
diff --git a/be/src/exec/pipeline/dependency.cpp 
b/be/src/exec/pipeline/dependency.cpp
index 2254fecced3..f17fcf9cfd9 100644
--- a/be/src/exec/pipeline/dependency.cpp
+++ b/be/src/exec/pipeline/dependency.cpp
@@ -519,7 +519,10 @@ void 
BucketedAggSharedState::_destroy_agg_status(AggregateDataPtr data) {
     }
 }
 
-LocalExchangeSharedState::~LocalExchangeSharedState() = default;
+LocalExchangeSharedState::~LocalExchangeSharedState() {
+    // Queued blocks can still update the shared state's memory counters 
during exchanger teardown.
+    exchanger.reset();
+}
 
 Status SetSharedState::update_build_not_ignore_null(const VExprContextSPtrs& 
ctxs) {
     if (ctxs.size() > build_not_ignore_null.size()) {
diff --git a/be/src/exprs/aggregate/aggregate_function_group_array_set_op.h 
b/be/src/exprs/aggregate/aggregate_function_group_array_set_op.h
index 380cb4f6d2e..2f84912881c 100644
--- a/be/src/exprs/aggregate/aggregate_function_group_array_set_op.h
+++ b/be/src/exprs/aggregate/aggregate_function_group_array_set_op.h
@@ -265,7 +265,9 @@ struct GroupArraySetOpStringBaseData {
 
         HybridSetBase::IteratorBase* it = this->set->begin();
         while (it->has_next()) {
-            const auto* value = reinterpret_cast<const 
std::string*>(it->get_value());
+            // StringSet's iterator yields a StringRef, not the stored 
std::string. Writing it
+            // produces the same bytes (var-uint length, then the data).
+            const auto* value = reinterpret_cast<const 
StringRef*>(it->get_value());
             buf.write_binary(*value);
             it->next();
         }
@@ -301,8 +303,8 @@ struct GroupArraySetOpStringBaseData {
         offsets_to.push_back(offsets_to.back() + res_size);
         HybridSetBase::IteratorBase* it = this->set->begin();
         while (it->has_next()) {
-            const auto* value = reinterpret_cast<const 
std::string*>(it->get_value());
-            data_to.insert_data(value->data(), value->size());
+            const auto* value = reinterpret_cast<const 
StringRef*>(it->get_value());
+            data_to.insert_data(value->data, value->size);
             it->next();
         }
     }
diff --git a/be/src/exprs/function/function_other_types_to_date.cpp 
b/be/src/exprs/function/function_other_types_to_date.cpp
index 2821954863d..96ab64ab5c5 100644
--- a/be/src/exprs/function/function_other_types_to_date.cpp
+++ b/be/src/exprs/function/function_other_types_to_date.cpp
@@ -1468,9 +1468,18 @@ struct FromIso8601DateV2 {
                 }
             }
 
+            // sscanf takes a NUL-terminated string, but column data is not 
terminated: rows are
+            // packed back to back, and macOS's sscanf runs strlen over its 
input first. A matched
+            // ISO form is at most 10 characters (checked above), so parse a 
terminated copy.
+            char src_cstr[11];
+            if (iso_string_format_value > 0) {
+                DCHECK_LT(src_string.size(), sizeof(src_cstr));
+                memcpy(src_cstr, src_string.data(), src_string.size());
+                src_cstr[src_string.size()] = '\0';
+            }
             auto& ts_value = 
*reinterpret_cast<DateV2Value<DateV2ValueType>*>(&result_data[i]);
             if (iso_string_format_value == 1) {
-                if (sscanf(src_string.data(), iso_format_string.data(), &year, 
&month, &day) != 3)
+                if (sscanf(src_cstr, iso_format_string.data(), &year, &month, 
&day) != 3)
                         [[unlikely]] {
                     result_null_map[i] = 1;
                 }
@@ -1481,8 +1490,7 @@ struct FromIso8601DateV2 {
                     result_null_map[i] = 1;
                 }
             } else if (iso_string_format_value == 2) {
-                if (sscanf(src_string.data(), iso_format_string.data(), &year, 
&month) != 2)
-                        [[unlikely]] {
+                if (sscanf(src_cstr, iso_format_string.data(), &year, &month) 
!= 2) [[unlikely]] {
                     result_null_map[i] = 1;
                 }
 
@@ -1492,7 +1500,7 @@ struct FromIso8601DateV2 {
                 }
                 ts_value.template unchecked_set_time_unit<DAY>(1);
             } else if (iso_string_format_value == 3) {
-                if (sscanf(src_string.data(), iso_format_string.data(), &year) 
!= 1) [[unlikely]] {
+                if (sscanf(src_cstr, iso_format_string.data(), &year) != 1) 
[[unlikely]] {
                     result_null_map[i] = 1;
                 }
 
@@ -1504,13 +1512,13 @@ struct FromIso8601DateV2 {
 
             } else if (iso_string_format_value == 5 || iso_string_format_value 
== 6) {
                 if (iso_string_format_value == 5) {
-                    if (sscanf(src_string.data(), iso_format_string.data(), 
&year, &week) != 2)
+                    if (sscanf(src_cstr, iso_format_string.data(), &year, 
&week) != 2)
                             [[unlikely]] {
                         result_null_map[i] = 1;
                     }
                 } else {
-                    if (sscanf(src_string.data(), iso_format_string.data(), 
&year, &week,
-                               &weekday) != 3) [[unlikely]] {
+                    if (sscanf(src_cstr, iso_format_string.data(), &year, 
&week, &weekday) != 3)
+                            [[unlikely]] {
                         result_null_map[i] = 1;
                     }
                 }
@@ -1531,7 +1539,7 @@ struct FromIso8601DateV2 {
                 TimeInterval interval(DAY, day_diff, false);
                 ts_value.date_add_interval<DAY>(interval);
             } else if (iso_string_format_value == 4) {
-                if (sscanf(src_string.data(), iso_format_string.data(), &year, 
&day_of_year) != 2)
+                if (sscanf(src_cstr, iso_format_string.data(), &year, 
&day_of_year) != 2)
                         [[unlikely]] {
                     result_null_map[i] = 1;
                 }
diff --git a/be/src/load/channel/load_stream_mgr.h 
b/be/src/load/channel/load_stream_mgr.h
index 20dfe3d2e5e..46b3201c462 100644
--- a/be/src/load/channel/load_stream_mgr.h
+++ b/be/src/load/channel/load_stream_mgr.h
@@ -53,8 +53,14 @@ public:
         return result;
     }
 
-    // only used by ut
-    size_t get_load_stream_num() { return _load_streams_map.size(); }
+    // only used by ut. Under the lock, because clear_load() destroys the 
LoadStream inside
+    // erase(), and the size drops before the destruction is over: a test that 
waits for 0 and then
+    // destroys the storage engine would otherwise destroy it while a rowset 
builder of the stream
+    // still holds a token of the engine's calc delete bitmap thread pool.
+    size_t get_load_stream_num() {
+        std::lock_guard<std::mutex> lock(_lock);
+        return _load_streams_map.size();
+    }
 
     FifoThreadPool* heavy_work_pool() { return _heavy_work_pool; }
 
diff --git a/be/src/service/http/ev_http_server.cpp 
b/be/src/service/http/ev_http_server.cpp
index 9aeea94c28d..6a57e5375a3 100644
--- a/be/src/service/http/ev_http_server.cpp
+++ b/be/src/service/http/ev_http_server.cpp
@@ -36,6 +36,7 @@
 #include <sstream>
 
 #include "common/logging.h"
+#include "cpp/sync_point.h"
 #include "service/backend_options.h"
 #include "service/http/http_channel.h"
 #include "service/http/http_handler.h"
@@ -146,6 +147,7 @@ void EvHttpServer::start() {
                 std::lock_guard lock(_event_bases_lock);
                 base = _event_bases[i];
             }
+            TEST_SYNC_POINT("EvHttpServer::start:before_dispatch");
             event_base_dispatch(base.get());
         });
         CHECK(status.ok());
@@ -157,15 +159,24 @@ void EvHttpServer::stop() {
     close(_server_fd);
     _server_fd = -1;
 
-    // 2. Break all event loops to make dispatch return
+    // 2. Ask every event loop to exit, so that dispatch returns. A worker may 
not have entered
+    // its loop yet: start() -> stop() asks the loops to exit -> the pool runs 
the worker's task,
+    // which only then calls event_base_dispatch(), e.g. when a test stops the 
server it has just
+    // started. event_base_loopbreak() would be lost in that order, because 
event_base_loop()
+    // clears the break flag when it starts; the worker would wait for events 
forever, and
+    // _workers->shutdown() below for the worker. event_base_loopexit() 
activates an event
+    // instead, which ends the loop the next time the loop runs, whether it is 
running already
+    // or starts later.
     {
         std::lock_guard<std::mutex> lock(_event_bases_lock);
         for (int i = 0; i < _num_workers; ++i) {
             if (_event_bases[i]) {
-                event_base_loopbreak(_event_bases[i].get());
+                CHECK_EQ(event_base_loopexit(_event_bases[i].get(), nullptr), 
0)
+                        << "Couldn't ask an event loop to exit.";
             }
         }
     }
+    TEST_SYNC_POINT("EvHttpServer::stop:loops_told_to_exit");
 
     // 3. Wait for all worker threads to finish event_base_dispatch
     _workers->shutdown();
diff --git a/be/src/service/point_query_executor.cpp 
b/be/src/service/point_query_executor.cpp
index e25dd6402fd..41407d35661 100644
--- a/be/src/service/point_query_executor.cpp
+++ b/be/src/service/point_query_executor.cpp
@@ -97,6 +97,9 @@ static void get_missing_and_include_cids(const TabletSchema& 
schema,
         missing_cids.insert(slot->col_unique_id());
     }
     // insert delete sign column id
+    // Point queries only run on merge-on-write unique key tables, whose 
tablet schema always has
+    // the hidden delete sign column.
+    DORIS_CHECK_GE(schema.delete_sign_idx(), 0);
     
missing_cids.insert(schema.columns()[schema.delete_sign_idx()]->unique_id());
     if (target_rs_column_id == -1) {
         // no row store columns
@@ -188,6 +191,7 @@ Status Reusable::init(const TDescriptorTable& t_desc_tbl, 
const std::vector<TExp
 
     // get the delete sign idx in block
     if (has_delete_sign) {
+        DORIS_CHECK_GE(schema.delete_sign_idx(), 0);
         _delete_sign_idx = 
_col_uid_to_idx[schema.columns()[schema.delete_sign_idx()]->unique_id()];
     }
 
diff --git a/be/src/storage/index/inverted/snii/format/sampled_term_index.h 
b/be/src/storage/index/inverted/snii/format/sampled_term_index.h
index b749c0aa8a0..9726679af11 100644
--- a/be/src/storage/index/inverted/snii/format/sampled_term_index.h
+++ b/be/src/storage/index/inverted/snii/format/sampled_term_index.h
@@ -31,15 +31,19 @@
 // Stores the first term of each DICT block in a framed, front-coded array. 
The reader keeps these samples resident to locate a candidate block; terms use 
unsigned byte order.
 namespace doris::snii::format {
 
-// SSO-aware heap-byte accounting for a std::string. libstdc++ keeps up to 15
-// chars inline (SSO), so only capacity() > 15 implies a separate heap buffer 
of
-// capacity()+1 bytes (the +1 is the NUL terminator); an SSO string owns no 
heap
-// and contributes 0. Shared by the resident format readers' heap_bytes() 
charge
+// SSO-aware heap-byte accounting for a std::string. A short string is kept
+// inline (SSO), in a buffer inside the string object itself, and owns no heap;
+// otherwise the characters live in a separate heap buffer of capacity()+1 
bytes
+// (the +1 is the NUL terminator). Where data() points tells the two apart for
+// every standard library, whose inline capacities differ (15 chars in 
libstdc++,
+// 22 in libc++). Shared by the resident format readers' heap_bytes() charge
 // helpers, which back LogicalIndexReader::memory_usage() (the searcher-cache
-// charge). NOTE: the threshold 15 is libstdc++-specific; a different standard
-// library needs a different SSO bound here.
+// charge).
 inline size_t std_string_heap_bytes(const std::string& s) {
-    return s.capacity() > 15 ? s.capacity() + 1 : 0;
+    const auto object = reinterpret_cast<uintptr_t>(&s);
+    const auto data = reinterpret_cast<uintptr_t>(s.data());
+    const bool inline_buffer = data >= object && data < object + sizeof(s);
+    return inline_buffer ? 0 : s.capacity() + 1;
 }
 
 // Builder: appends the first_term of each DICT block in block ordinal order 
(must be strictly ascending),
diff --git a/be/src/udf/python/python_server.cpp 
b/be/src/udf/python/python_server.cpp
index 2d06caa3110..f100992cf79 100644
--- a/be/src/udf/python/python_server.cpp
+++ b/be/src/udf/python/python_server.cpp
@@ -25,11 +25,16 @@
 #include <sys/poll.h>
 #include <sys/stat.h>
 #include <unistd.h>
+#ifdef __APPLE__
+#include <libproc.h>
+#endif
 
 #include <algorithm>
 #include <boost/asio.hpp>
 #include <boost/process.hpp>
+#include <cerrno>
 #include <chrono>
+#include <cstring>
 #include <fstream>
 #include <thread>
 
@@ -665,6 +670,16 @@ void PythonServerManager::shutdown() {
 }
 
 Status PythonServerManager::_read_process_memory(pid_t pid, size_t* rss_bytes) 
{
+#ifdef __APPLE__
+    // macOS has no /proc. The kernel reports the resident size in bytes.
+    struct proc_taskinfo info {};
+    if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info)) != 
sizeof(info)) {
+        return Status::InternalError("Cannot read the task info of pid {}: 
{}", pid,
+                                     std::strerror(errno));
+    }
+    *rss_bytes = info.pti_resident_size;
+    return Status::OK();
+#else
     // Read from /proc/{pid}/statm
     // Format: size resident shared text lib data dt
     std::string statm_path = fmt::format("/proc/{}/statm", pid);
@@ -687,6 +702,7 @@ Status PythonServerManager::_read_process_memory(pid_t pid, 
size_t* rss_bytes) {
     *rss_bytes = rss_pages * page_size;
 
     return Status::OK();
+#endif
 }
 
 void PythonServerManager::_refresh_memory_stats() {
diff --git a/be/src/udf/python/python_server.h 
b/be/src/udf/python/python_server.h
index d331f60ea27..1de0b2c5c07 100644
--- a/be/src/udf/python/python_server.h
+++ b/be/src/udf/python/python_server.h
@@ -148,7 +148,8 @@ private:
                                     const 
std::shared_ptr<VersionedProcessPool>& versioned_pool);
 
     /**
-     * Read resident set size (RSS) for a single process from /proc/{pid}/statm
+     * Read resident set size (RSS) for a single process from 
/proc/{pid}/statm (on macOS, from
+     * proc_pidinfo())
      */
     Status _read_process_memory(pid_t pid, size_t* rss_bytes);
 
diff --git a/be/src/util/pprof_utils.cpp b/be/src/util/pprof_utils.cpp
index eadf07192d5..fb9bacb2350 100644
--- a/be/src/util/pprof_utils.cpp
+++ b/be/src/util/pprof_utils.cpp
@@ -19,6 +19,9 @@
 
 #include <stdio.h>
 #include <unistd.h>
+#ifdef __APPLE__
+#include <crt_externs.h>
+#endif
 
 #include <cstdlib>
 #include <fstream> // IWYU pragma: keep
@@ -70,7 +73,15 @@ Status PprofUtils::get_perf_cmd(std::string* cmd) {
 }
 
 Status PprofUtils::get_self_cmdline(std::string* cmd) {
-    // get cmdline
+#ifdef __APPLE__
+    // macOS has no /proc. argv[0] is what the Linux branch reads: 
/proc/self/cmdline starts with it.
+    // A process can be started with an empty argv, as the empty cmdline file 
on Linux.
+    if (*_NSGetArgc() < 1) {
+        return Status::InternalError("get_self_cmdline: the process has no 
argv[0]");
+    }
+    *cmd = (*_NSGetArgv())[0];
+    return Status::OK();
+#else
     FILE* fp = fopen("/proc/self/cmdline", "r");
     if (fp == nullptr) {
         return Status::InternalError("Unable to open file: 
/proc/self/cmdline");
@@ -85,6 +96,7 @@ Status PprofUtils::get_self_cmdline(std::string* cmd) {
     fclose(fp);
     *cmd = buf;
     return res;
+#endif
 }
 
 Status PprofUtils::get_readable_profile(const std::string& file_or_content, 
bool is_file,
diff --git a/be/src/util/pprof_utils.h b/be/src/util/pprof_utils.h
index 461ec56280a..03ff8f40b38 100644
--- a/be/src/util/pprof_utils.h
+++ b/be/src/util/pprof_utils.h
@@ -31,7 +31,7 @@ public:
     /// check and get "perf" cmd
     static Status get_perf_cmd(std::string* cmd);
 
-    /// get current BE process cmdline from '/proc/self/cmdline'
+    /// get the current BE process's argv[0] (the start of 
'/proc/self/cmdline' on Linux)
     static Status get_self_cmdline(std::string* cmd);
 
     /// check and get "pprof" command, return the cmd abs path via "cmd".
diff --git a/be/test/exprs/aggregate/agg_group_array_intersect_test.cpp 
b/be/test/exprs/aggregate/agg_group_array_intersect_test.cpp
index 00bcd45cc0a..9d930ca55af 100644
--- a/be/test/exprs/aggregate/agg_group_array_intersect_test.cpp
+++ b/be/test/exprs/aggregate/agg_group_array_intersect_test.cpp
@@ -32,6 +32,7 @@
 #include "core/data_type/data_type_number.h"
 #include "core/data_type/data_type_string.h"
 #include "core/field.h"
+#include "core/string_buffer.hpp"
 #include "core/types.h"
 #include "exprs/aggregate/aggregate_function.h"
 #include "exprs/aggregate/aggregate_function_simple_factory.h"
@@ -458,6 +459,68 @@ TEST(AggGroupArrayIntersectTest, string_test) {
     agg_function->destroy(place);
 }
 
+TEST(AggGroupArrayIntersectTest, string_serialize_round_trip) {
+    // ["a", "b", "c"] and ["aaaa", "b", "c"] intersect to {"b", "c"}.
+    auto nested_column = ColumnString::create();
+    for (const std::string& s : {"a", "b", "c", "aaaa", "b", "c"}) {
+        nested_column->insert_data(s.data(), s.size());
+    }
+    auto null_map_column = ColumnUInt8::create();
+    null_map_column->get_data().resize_fill(nested_column->size(), 0);
+    auto offsets_column = ColumnArray::ColumnOffsets::create();
+    offsets_column->insert(Field::create_field<TYPE_UINT64>(3));
+    offsets_column->insert(Field::create_field<TYPE_UINT64>(6));
+    auto column_array_string = ColumnArray::create(
+            ColumnNullable::create(std::move(nested_column), 
std::move(null_map_column)),
+            std::move(offsets_column));
+
+    AggregateFunctionSimpleFactory factory;
+    register_aggregate_function_group_array_set_op(factory);
+    DataTypes data_types = 
{std::make_shared<DataTypeArray>(std::make_shared<DataTypeString>())};
+    auto agg_function = factory.get("group_array_intersect", data_types, 
nullptr, false, -1);
+    std::unique_ptr<char[]> memory(new char[agg_function->size_of_data()]);
+    AggregateDataPtr place = memory.get();
+    agg_function->create(place);
+    Arena arena;
+    const IColumn* column[1] = {column_array_string.get()};
+    for (int i = 0; i < agg_test_batch_size; i++) {
+        agg_function->add(place, column, i, arena);
+    }
+
+    // The set hands out StringRefs. The state still serializes the strings 
themselves:
+    // contain_null, init, the element count, then each element's length and 
bytes. A var-uint
+    // is a byte count followed by the value bytes. The set's iteration order 
is unspecified.
+    ColumnString buf;
+    VectorBufferWriter buf_writer(buf);
+    agg_function->serialize(place, buf_writer);
+    buf_writer.commit();
+    const std::string bytes = buf.get_data_at(0).to_string();
+    const std::string head {'\x00', '\x01', '\x01', '\x02'};
+    const std::string b {'\x01', '\x01', 'b'};
+    const std::string c {'\x01', '\x01', 'c'};
+    EXPECT_TRUE(bytes == head + b + c || bytes == head + c + b) << 
bytes.size() << " bytes";
+
+    std::unique_ptr<char[]> memory2(new char[agg_function->size_of_data()]);
+    AggregateDataPtr place2 = memory2.get();
+    agg_function->create(place2);
+    VectorBufferReader buf_reader(buf.get_data_at(0));
+    agg_function->deserialize(place2, buf_reader, arena);
+
+    ColumnArray ans(ColumnNullable::create(ColumnString::create(), 
ColumnUInt8::create()),
+                    ColumnArray::ColumnOffsets::create());
+    agg_function->insert_result_into(place2, ans);
+    Field actual_field;
+    ans.get(0, actual_field);
+    Array actual_result = actual_field.get<TYPE_ARRAY>();
+    sort_string_array(actual_result);
+    ASSERT_EQ(actual_result.size(), 2);
+    EXPECT_EQ(actual_result[0], Field::create_field<TYPE_STRING>("b"));
+    EXPECT_EQ(actual_result[1], Field::create_field<TYPE_STRING>("c"));
+
+    agg_function->destroy(place);
+    agg_function->destroy(place2);
+}
+
 TEST(AggGroupArrayIntersectTest, string_nullable_test) {
     // Prepare test data.
     auto nested_column = ColumnString::create();
diff --git a/be/test/service/http/ev_http_server_test.cpp 
b/be/test/service/http/ev_http_server_test.cpp
new file mode 100644
index 00000000000..23062e30f64
--- /dev/null
+++ b/be/test/service/http/ev_http_server_test.cpp
@@ -0,0 +1,50 @@
+// 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.
+
+#include "service/http/ev_http_server.h"
+
+#include <gtest/gtest.h>
+
+#include "cpp/sync_point.h"
+#include "util/defer_op.h"
+
+namespace doris {
+
+// A worker thread that reaches its event loop only after stop() has asked the 
loops to exit
+// must still exit. That is the order a stop() right after start() can take, 
for example when a
+// test fixture starts a server and its case sends no request, as in
+// AIRequestExecutorTest.AuthenticationSetupFailureDoesNotReadResponseOrRetry 
under parallel
+// load. The dependency makes every worker wait before event_base_dispatch() 
until stop() has
+// asked the loops to exit. If the request is lost, the worker waits for 
events forever and
+// stop() waits for the worker, so this case does not return.
+TEST(EvHttpServerTest, StopEndsWorkersThatReachTheirLoopLate) {
+    auto* sync_point = SyncPoint::get_instance();
+    sync_point->load_dependency({{.predecessor = 
"EvHttpServer::stop:loops_told_to_exit",
+                                  .successor = 
"EvHttpServer::start:before_dispatch"}});
+    sync_point->enable_processing();
+    Defer reset_sync_point {[sync_point] {
+        sync_point->disable_processing();
+        sync_point->load_dependency({});
+        sync_point->clear_all_call_backs();
+    }};
+
+    EvHttpServer server(0, 2);
+    server.start();
+    server.stop();
+}
+
+} // namespace doris
diff --git a/be/test/service/point_query_exector_test.cpp 
b/be/test/service/point_query_exector_test.cpp
index 9099f8bc5cb..274d9d197a4 100644
--- a/be/test/service/point_query_exector_test.cpp
+++ b/be/test/service/point_query_exector_test.cpp
@@ -55,6 +55,7 @@
 #include "storage/segment/segment_loader.h"
 #include "storage/storage_engine.h"
 #include "storage/tablet/tablet_schema.h"
+#include "storage/utils.h"
 #include "util/thrift_util.h"
 
 namespace doris {
@@ -297,9 +298,51 @@ std::shared_ptr<TabletSchema> 
ReusableTestHelper::tablet_schema = []() {
         
schema->append_column(TabletColumn(FieldAggregationMethod::OLAP_FIELD_AGGREGATION_NONE,
                                            FieldType::OLAP_FIELD_TYPE_BIGINT));
     }
+    // Point queries only run on unique key tables, which always have the 
hidden delete sign
+    // column; Reusable::init() looks it up.
+    TabletColumn 
delete_sign(FieldAggregationMethod::OLAP_FIELD_AGGREGATION_REPLACE,
+                             FieldType::OLAP_FIELD_TYPE_TINYINT);
+    delete_sign.set_name(DELETE_SIGN);
+    schema->append_column(delete_sign);
     return schema;
 }();
 
+// Point queries only run on merge-on-write unique key tables, whose tablet 
schema always has the
+// hidden delete sign column. Reusable::init() looks that column up: for the 
block layout when the
+// tuple has the delete sign slot, and for the columns to read. A tablet 
schema without it must
+// fail the check rather than index the schema's columns with -1.
+TEST(ReusableTest, InitChecksTheTabletSchemaHasADeleteSignColumn) {
+    TabletSchema schema;
+    
schema.append_column(TabletColumn(FieldAggregationMethod::OLAP_FIELD_AGGREGATION_NONE,
+                                      FieldType::OLAP_FIELD_TYPE_BIGINT));
+    ASSERT_EQ(schema.delete_sign_idx(), -1);
+
+    auto init = [&schema](bool with_delete_sign_slot) {
+        TDescriptorTableBuilder dtb;
+        TTupleDescriptorBuilder tuple_builder;
+        tuple_builder.add_slot(
+                
TSlotDescriptorBuilder().type(TYPE_BIGINT).column_name("k1").column_pos(0).build());
+        if (with_delete_sign_slot) {
+            tuple_builder.add_slot(TSlotDescriptorBuilder()
+                                           .type(TYPE_TINYINT)
+                                           .column_name(DELETE_SIGN)
+                                           .column_pos(1)
+                                           .build());
+        }
+        tuple_builder.build(&dtb);
+        Reusable reusable;
+        static_cast<void>(
+                reusable.init(dtb.desc_tbl(), {}, TQueryOptions(), "+08:00", 
"", schema, 1));
+    };
+#ifndef NDEBUG
+    EXPECT_DEATH(init(false), "Check failed: schema.delete_sign_idx\\(\\) >= 
0");
+    EXPECT_DEATH(init(true), "Check failed: schema.delete_sign_idx\\(\\) >= 
0");
+#else
+    EXPECT_THROW(init(false), Exception);
+    EXPECT_THROW(init(true), Exception);
+#endif
+}
+
 // RowCache test class
 class RowCacheTest : public testing::Test {
 protected:
diff --git a/be/test/udf/python/python_server_test.cpp 
b/be/test/udf/python/python_server_test.cpp
index 83fc19d9dad..48b8ada02c7 100644
--- a/be/test/udf/python/python_server_test.cpp
+++ b/be/test/udf/python/python_server_test.cpp
@@ -1127,7 +1127,12 @@ TEST_F(PythonServerTest, 
ReadProcessMemoryInvalidPidFails) {
     Status status = mgr._read_process_memory(-1, &rss_bytes);
 
     EXPECT_FALSE(status.ok());
-    EXPECT_NE(status.to_string().find("/proc/-1/statm"), std::string::npos);
+    // The message names where the memory is read from on each platform.
+#ifdef __APPLE__
+    EXPECT_NE(status.to_string().find("task info of pid -1"), 
std::string::npos) << status;
+#else
+    EXPECT_NE(status.to_string().find("/proc/-1/statm"), std::string::npos) << 
status;
+#endif
 }
 
 } // namespace doris


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

Reply via email to