Skip to content

Give Poco::Net::SocketAddress a noexcept move constructor - #115030

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/poco-socketaddress-noexcept-move
Aug 17, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/poco-socketaddress-noexcept-move

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Appending to a system log queue no longer deep-copies the whole queue when it grows. Poco::Net::SocketAddress had no move constructor, which made QueryLogElement and three other element types not nothrow-move-constructible, so a std::vector reallocation copied every element (allocating per address) while the queue mutex was held, blocking every query that writes to system.query_log.

Description

Found while investigating a server that accepted and planned queries but executed none for 3.5 minutes on Stateless tests (amd_tsan, flaky check): CI report. The sampling profiler shows one thread inside SystemLogQueue<QueryLogElement>::push for 177 of 181 seconds, in vector::__emplace_back_slow_path, with 31 threads blocked on std::mutex::lock() in the same call.

push() appends under mutex, so a std::vector reallocation happens in the critical section. libc++ relocates with std::move_if_noexcept, which falls back to copying every element when the type is not nothrow-move-constructible. QueryLogElement was not, for one reason: Poco::Net::SocketAddress declared copy operations only, and its copy heap-allocates a new SocketAddressImpl. ClientInfo holds three of those.

The fix belongs in Poco because that is where the cause is: a refcounted-pointer wrapper whose move is nothing but a pointer transfer. The moves of ClientInfo and the log elements stay implicit, so their trait is derived. AutoPtr::swap is used because AutoPtr also declares no move, so assignment would bump the refcount and leave the source non-null.

Measured over one reallocation of 8192 elements: 32769 allocations before, 1 after. Four element types were affected (QueryLog, QueryThreadLog, SessionLog, ZooKeeperLog); a static_assert in SystemLogQueue now enumerates every element type at build time (30 here, 32 in a cloud build) and fails on the unpatched tree.

A moved-from SocketAddress has a null _pImpl; all seven accessors already route through pImpl(), which throws NullPointerException, so that state stays defined.

Left out deliberately: the slow query_log flush that triggered the reallocation is a separate question, and a move on Poco::AutoPtr would be the broader fix. This is one mechanism proven on one artifact, not a claim about every Server died report. No SQL test, because a C++ relocation trait is not observable from SQL.

SystemLogQueue::push() appends to a std::vector<LogElement> while holding
the queue mutex, so crossing capacity reallocates inside the critical
section. libc++ relocates with std::move_if_noexcept, which yields a const
lvalue reference (and therefore copies) for a type that is not
nothrow-move-constructible.

QueryLogElement was not nothrow-move-constructible for exactly one reason:
Poco::Net::SocketAddress declared copy operations only, so its implicit
move fell back to the copy, and that copy heap-allocates a new
SocketAddressImpl via newIPv4/newIPv6/newLocal. ClientInfo carries three
such addresses. One push() therefore deep-copied the whole queue with
several allocations per element, under the mutex. On a
Stateless tests (amd_tsan, flaky check) run this held the query_log mutex
for 177 of 181 seconds with 31 threads blocked in the same push, including
every hung-check liveness probe, so the job was reported as Server died:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110479&sha=038667a9c024695126415fe5f37b76f7a06662fa&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29

Add a genuine noexcept move constructor and move assignment that transfer
_pImpl. The moves of ClientInfo and of the log elements stay implicit, so
their nothrow-move trait is derived from the members rather than asserted
into existence; an explicit noexcept on the wrappers would have satisfied
the assertion while still copying, and would have converted a throw into
terminate().

The transfer uses AutoPtr::swap rather than assignment because
Poco::AutoPtr declares no move operations either: assigning it binds to
assign(const AutoPtr &), which calls duplicate() and leaves the source
non-null. AutoPtr::swap is std::swap on the raw pointer, so it is
genuinely noexcept and allocation-free.

Four SystemLog element types were affected: QueryLog, QueryThreadLog and
SessionLog through ClientInfo, and ZooKeeperLog through a bare
SocketAddress member. All 29 element types pass the trait after this
change. Measured over one reallocation of 8192 elements carrying three
optional<SocketAddress> members: 32769 allocations before, 1 after.

Two static_asserts guard the property: one beside QueryLogElement, and a
generic one in SystemLogQueue that enumerates every element type at build
time. Both fail the build on the unpatched tree.

A moved-from SocketAddress has a null _pImpl. That state was already
supported: pImpl() null-checks and throws Poco::NullPointerException, and
all seven accessors route through it, so reading a moved-from address is
defined rather than undefined behaviour.

Not addressed here: the slow query_log flush that triggered the
reallocation is a separate performance question, and adding a move to
Poco::AutoPtr would be the broader fix.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two independent reviews of this diff: a cold read of the resulting code, then a second model
re-reviewing the full scope against the PR contract. Findings and verdicts:

# Finding Verdict
💡 Move-assignment uses swap() then reset() rather than a bare swap. Disagree, no defect. The pair is what makes it correct: swap moves the old target impl into the source and reset() releases it, so the old target is destroyed exactly once, and the source is left empty as the header documents. AutoPtr::swap is std::swap on a raw pointer and release() is noexcept, so the noexcept specification is honest. Self-move-assignment is a no-op via the &socketAddress != this guard.
⚠️ "All 29 element types" is an undercount. Agree. Re-derived from the macro lists: SYSTEM_LOG_ELEMENTS 26 + SYSTEM_PERIODIC_LOG_ELEMENTS 4 = 30 in this build, 32 with SYSTEM_LOG_ELEMENTS_CLOUD. The property claimed is unaffected (every element type passes the trait, none fail); only the number was wrong. Corrected in the description. The commit message still says 29.

Checked and clean, with the reasoning recorded rather than asserted:

  • Behaviour change on existing callers. Before this change std::move on a SocketAddress
    silently copied, leaving the source valid; it now genuinely empties the source. Any existing
    move-then-reuse site was therefore correct by accident and would now throw
    NullPointerException. Swept src/, programs/ and base/ for moves of a SocketAddress and
    of every type that transitively holds one (ClientInfo, ShuffleHost, ZooKeeperLogElement,
    ConnectionParameters, Connection's three optionals). No such site exists: the two whole
    ClientInfo moves (GRPCServer.cpp:920, DistributedAsyncInsertDirectoryQueue.cpp:653) never
    read the source afterwards, and base/poco contains no move of an address at all.
  • The guard is not self-fulfilling. The copy constructor is not noexcept, so
    is_nothrow_move_constructible_v cannot be satisfied through the copy path. The moves of
    ClientInfo and of the log elements are left implicit, so the trait is derived from the members.
  • Test liveness, measured rather than argued. Reverting only the two base/poco files and
    recompiling makes both static_asserts fail; restoring them makes it pass.
  • Carriers enumerated independently before comparing against the plan: four element types
    (QueryLog, QueryThreadLog, SessionLog via ClientInfo, and ZooKeeperLog via a bare
    member). No fifth. The generic static_assert covers every type the queue is instantiated for.
  • The moved-from state is defined. All seven accessors route through pImpl(), which throws on
    null, and no raw _pImpl dereference was added. ZooKeeperLogElement::address.host() is called
    unconditionally at flush time, but elements are never read after being moved: the producer moves
    once into the queue and the consumer takes the whole buffer with swap.

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6004c1f]

Summary: ✅


AI Review

Summary

This PR makes Poco::Net::SocketAddress genuinely noexcept-movable so SystemLogQueue reallocation stops deep-copying log elements that carry socket addresses under the queue mutex. I did not find actionable correctness, safety, or compatibility issues in the current diff; the new move operations match the class's existing ownership model, and the SystemLogQueue static_assert is an appropriate compile-time guard for the queue invariant.

Final Verdict

✅ No actionable findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 0/0 (nothing coverable) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for the mechanism, which is what this changes. Compiling a static_assert on std::is_nothrow_move_constructible_v<DB::QueryLogElement> against the unpatched tree fails; an allocation counter over one std::vector reallocation of 8192 elements carrying three std::optional<SocketAddress> members reports 32769 allocations. Both are exact and repeatable. The CI timing coincidence (a 149 s flush overlapping a reallocation) is not reproducible locally; the 177 s lock hold is measured from the job's own trace_log.tsv (914163 samples, symbolized against the exact CI binary).
b Root cause explained? SystemLogQueue::push appends to a std::vector<LogElement> while holding mutex (SystemLogBase.h:182, SystemLogBase.cpp:118, :147). Crossing capacity relocates via std::move_if_noexcept, which returns a const lvalue reference (so copies) for a type that is not nothrow-move-constructible. QueryLogElement was not, because Poco::Net::SocketAddress declared copy operations only (SocketAddress.h:140,:149) and its copy heap-allocates a SocketAddressImpl (SocketAddress.cpp:136-147 into SocketAddress.h:235-274). ClientInfo carries three such addresses.
c Fix matches root cause? Yes. The missing move is the cause, and it is added where it is missing rather than worked around. Rejected: raising reserved_size_rows (moves the threshold, keeps the O(N) copy), growing outside the lock (producer starvation the 2aba36cd comment warns about), std::deque (much wider blast radius, leaves the expensive copy for other callers), and noexcept on the wrapper types (would make the assertion self-fulfilling while still copying, and turn a throw into terminate()).
d Test intent preserved / new tests added? No existing test weakened. The regression guard is two static_asserts: one on QueryLogElement, one generic inside SystemLogQueue that enumerates every element type at build time (30 in this build, 32 in a cloud build). Deliberately no timing assertion and no gtest: the property being fixed is a compile-time trait, so a compile-time assertion is an exact, zero-flake oracle.
e Both directions demonstrated? Yes, three ways. Build: fails on the unpatched tree with both assertions firing, clean with the change. Allocations: 32769 to 1 over one reallocation of 8192 elements. Carriers: 4 element types fail the trait on base, 0 with the change.
f Fix is general across code paths? Yes. Fixed at the source in SocketAddress, not at the four call sites, so every SystemLog element type (30 here, 32 in a cloud build) and every other SocketAddress relocation are covered. The carrier list was produced mechanically (grep -rhoE "SystemLog(Queue)?<[A-Za-z_]+>" src/, then one probe per translation unit), which is how ZooKeeperLogElement turned up: it holds a bare SocketAddress rather than a ClientInfo. Poco::AutoPtr deliberately left alone.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. IPv4, IPv6 and UNIX_LOCAL all go through the same _pImpl, which the move transfers without inspecting. Boundaries covered: default-constructed (wildcard IPv4), moved-from (null), self-move-assignment, and std::optional in both engaged and disengaged states. SQL type wrappers are not applicable: this is a C++ container trait, not SQL type dispatch.
h Backward compatible? (maintainer-approved exception only) Yes, fully. In-memory move semantics only: no setting, no default change, no serialization format, no wire protocol, so no SettingsChangesHistory.cpp entry. Adding a move constructor does not remove the copy operations, so existing callers compile and behave as before.
i Invariants and contracts preserved? Two invariants. First, an element stored in a SystemLogQueue must be nothrow-move-constructible, now enforced at compile time by the guard in SystemLogQueue. Second, a SocketAddress with a null _pImpl must stay safe: pImpl() (SocketAddress.h:227-229) null-checks and throws NullPointerException, all seven accessors route through it, no raw _pImpl-> was added, and a probe confirms 7 of 7 accessors throw on a moved-from object. The noexcept is honest because AutoPtr::swap is std::swap on a raw pointer, so nothing is ever converted into terminate(). The early-return paths in push() return before the append and are untouched, as is pop()'s swap and reserve contract.

Session id: cron:clickhouse-impl-slot-5:20260816-150400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able @pamarcos, could you review this? Poco::Net::SocketAddress declared copy operations only, so QueryLogElement was not nothrow-move-constructible and libc++ relocated the whole system.query_log queue by deep-copying every element (allocating per address) while SystemLogQueue::push held the queue mutex; adding a real move constructor takes one reallocation of 8192 elements from 32769 allocations to 1.

@thevar1able thevar1able self-assigned this Aug 16, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6004c1f78 with master ce6df4653 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 694.64 MiB 691.61 MiB -3.03 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

31 object files changed (-69.57 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/SystemLogBase.cpp.o 1.29 MiB 1.24 MiB -53.00 KiB (-4.00%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1614 translation units recompiled, 9256 s compile time in total, 1614 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 14 query(s) improved out of 35 analysed

This PR gives Poco's SocketAddress a noexcept move constructor/assignment, which makes QueryLogElement nothrow-move-constructible; the SystemLogQueue then relocates entries by move instead of deep-copying them while holding its mutex, shrinking a critical section that was O(queue size). Because every query writes to query_log, that overhead reduction shows up as a broad, consistent speedup: roughly 6-25% across most ClickBench queries, with the largest relative gains on the fastest queries where fixed overhead dominates. We kept all improvement verdicts — the uniform, operator-agnostic pattern is exactly what this fix predicts. The two very large outliers (TPC-H Q7 at ×8.2 faster, ClickBench Q23 at ×2.2 with noisy history) are directionally trustworthy but their exact magnitude likely also reflects co-location/measurement effects, so read the scale there with some caution.

clickbench

🟢 12 improved

Flagged queries (12 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 12 improvement 277 242 -12.6% <0.0001 cpu: Consistent -12.6% with a low, matched spread and both tests agreeing. Fits this PR making QueryLogElement nothrow-move-constructible, which shortens the query_log queue critical section every query pays.
🟢 13 improvement 426 332 -22.2% <0.0001 cpu: Clean -22.2% improvement. Reduced query_log queue lock contention affects all queries, so a broad shift like this is exactly what the diff predicts.
🟢 14 improvement 362 304 -16.0% <0.0001 cpu: -16.0% with tight, matched variance. Attributable to the shared logging hot-path overhead reduction rather than anything query-14 specific.
🟢 15 improvement 193 159 -17.6% <0.0001 cpu: -17.6% with very low spread on both sides. In line with the fleet-wide per-query overhead drop from the nothrow-move fix.
🟢 16 improvement 793 611 -23.0% <0.0001 cpu: -23.0% improvement, confirmed by both tests. Matches the shared query_log queue contention fix; base spread was a bit higher but the delta is large and clear.
🟢 17 improvement 556 452 -18.8% <0.0001 cpu: -18.8% clear shift. The broad, consistent direction across ClickBench points to the shared logging-path overhead reduction, not a query-17 planner or operator change.
🟢 18 improvement 1298 1070 -17.6% <0.0001 cpu: -17.6% on a heavier query with noisier baseline, but the delta is large and consistent. Same shared-hot-path mechanism as the rest of the suite.
🟢 23 improvement 167 77 ×2.2 faster <0.0001 cpu: ×2.2 faster. Source spread is high and history is noisy, but a fast query benefits proportionally more from a fixed per-query overhead cut, consistent with the logging fix.
🟢 30 improvement 279 217 -22.2% <0.0001 cpu: -22.2% improvement, both tests agree. Fits the shared query_log queue contention reduction.
🟢 31 improvement 395 297 -24.8% <0.0001 cpu: -24.8% clear shift, consistent with the fleet-wide overhead drop from making the log element nothrow-move-constructible.
🟢 33 improvement 1254 1180 -5.9% <0.0001 cpu: Smaller -5.9% on a long-running query, which is expected: a fixed logging-path overhead saving is a smaller fraction of a 1.2s query. Direction is consistent with the rest.
🟢 34 improvement 1256 1172 -6.6% <0.0001 cpu: -6.6%, same modest-but-consistent pattern as query 33 for a heavy query. Attributable to the shared logging overhead reduction.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 574 70 ×8.2 faster <0.0001 cpu: ×8.2 faster with a large CPU drop. Magnitude exceeds what the logging fix alone explains, so co-location or measurement effects likely contribute; direction is trustworthy but treat the exact scale cautiously.
🟢 8 improvement 175 81 ×2.2 faster <0.0001 cpu: ×2.2 faster on a fast query, where fixed per-query overhead is a larger share. Consistent with the shared query_log queue contention reduction.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: a2779294-392a-4891-ada9-0e49943b893f
  • MIRAI run: fb7d7364-3094-47b3-a36b-113d5986561b
  • PR check IDs:
    • clickbench_1666230_1786924216
    • clickbench_1666243_1786924216
    • clickbench_1666250_1786924216
    • tpch_adapted_1_official_1666260_1786924216
    • tpch_adapted_1_official_1666683_1786924246
    • tpch_adapted_1_official_1666785_1786924253

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6004c1f

CI has fully finished on this head and there are no failures to own: 158 OK, 20 skipped, 0 failed.

Check / test Reason Owner / fixing PR
(none) no failed checks on this head n/a

The two Config Workflow / can_be_tested reds recorded against this SHA are from the two run
attempts at 19:26Z and 19:50Z, before the can be tested label was applied at 21:18Z. The attempt
that followed the label is green end to end, so those rows are superseded rather than outstanding.

Corroborated from two independent sources at this SHA: CIDB (344,608 success rows, 0 FAIL/ERROR rows
with a test name) and the S3 report walked recursively to every leaf (top level OK, 158 OK /
20 SKIPPED, 0 non-OK nodes). Mergeable Check, PR and CH Inc sync are all green.

Session id: cron:our-pr-ci-monitor:20260817-030000

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trivial. LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 0dcf023 Aug 17, 2026
531 of 535 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants