Skip to content

Fix SYSTEM DROP DNS CACHE leaving entries in the cache when it overlaps the DNS cache update - #123699

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-dns-drop-cache-during-update
Oct 13, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-dns-drop-cache-during-update

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #71030 (comment)

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed SYSTEM DROP DNS CACHE leaving entries in the DNS cache when it ran at the same time as the periodic DNS cache update.

Description

On 26.8 (and every release since 2019), SYSTEM DROP DNS CACHE that runs while the periodic DNS cache update is in progress can return with entries still in the cache (system.dns_cache is not empty), including addresses looked up before the drop, so the next connection or host-based access check uses them instead of resolving again.

This is the cause of the flaky test_host_regexp_multiple_ptr_records/test.py::test_reverse_dns_profile_events (assert 7 > 7 on DNSReverseRequests), failed in PR 71030 and PR 119499. In both server logs SYSTEM CLEAR DNS CACHE lands between Updating DNS cache and Updated DNS cache, and the following reverse lookup is a cache hit.

Root cause: DNSResolver::dropCache cleared cache_host and cache_address before taking update_mutex. The update holds update_mutex while it refreshes every known host and address and ends each refresh with CacheBase::set, so it put the entries back into the just-cleared cache; the drop then waited for it and cleared only the known host lists.

Change: clear both caches inside the existing std::scoped_lock(update_mutex, drop_mutex). The drop already waited on update_mutex, so its latency does not change.

Validation: new DNSResolver.DropCacheDuringUpdate gtest (an updater thread runs updateCache while the main thread drops the cache and checks it is empty). Without the fix it fails in every repetition (500/500 debug, 300/300 ASan); with the fix 500/500 and 300/300 pass.


Workflow [PR]
Sync PR [sync-upstream/pr/123699]

Version info

  • Merged into: 26.10.1.2256-master (included in 26.10 and later)

…che update

`DNSResolver::dropCache` cleared `cache_host` and `cache_address` before
taking `update_mutex`. The periodic `updateCache` holds `update_mutex` while
it refreshes every known host and address, and `updateHost`/`updateAddress`
end with an unconditional `CacheBase::set`, so a drop that landed during an
update had its cleared entries put back; it then waited for the update,
cleared only `known_*`/`new_*`, and returned with a non-empty cache.

This made `test_host_regexp_multiple_ptr_records::test_reverse_dns_profile_events`
flaky (`assert 7 > 7` on `DNSReverseRequests`): `SYSTEM CLEAR DNS CACHE`
ran inside an update cycle, the PTR answer for the client was re-inserted
before the statement returned, and the following access check was a
cache hit.

Clear both caches inside the existing `scoped_lock(update_mutex, drop_mutex)`.
The drop already waited on `update_mutex`, so its latency is unchanged.

The new gtest runs `updateCache` in a single updater thread (the server has
exactly one, `DNSCacheUpdater`; two concurrent `updateCache` callers would
race on `known_hosts`), waits until the updater has refreshed the entry, then
drops the cache and checks it is empty. Without the fix it fails in every
repetition.

Requested in ClickHouse#71030 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

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

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The gtest does not force the drop to overlap an update, so reverted code could pass DISAGREE Pre-fix binary at the shipped 200 iterations: debug 500/500 and ASan 300/300 repetitions fail, median failing iteration 0-1, max 51. A failpoint would add a symbol the Bugfix validation (unit tests) merge-base overlay cannot compile.
2 💡 The gtest observes only the host cache; the PTR cache (the one the CI failure hits) is covered by the same critical section and the integration test AGREE, not blocking No public accessor for the PTR cache; an oracle would need real c-ares lookups. Both clears are adjacent lines under one lock.
3 💡 The wait loop on cached_at has no bound DISAGREE updateCache(0) never drops a known host and an address literal never fails to resolve, so the updater always refreshes it.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-11:20261003-143900

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='DNSResolver.*' --gtest_repeat=500 fails in every repetition without the fix (debug 500/500, ASan 300/300).
b Root cause explained? dropCache cleared both caches before taking update_mutex; a concurrent updateCache refreshes known hosts under update_mutex and ends with CacheBase::set, refilling the cleared cache before the drop returns.
c Fix matches root cause? Yes. The clears move inside the existing scoped_lock(update_mutex, drop_mutex); no test or timing change.
d Test intent preserved / new tests added? Integration test untouched; new gtest DNSResolver.DropCacheDuringUpdate.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: fails 500/500 without the fix, passes 500/500 with it (debug), 300/300 each way on ASan.
f Fix is general across code paths? Yes. Every writer that refills the caches runs under update_mutex; in-flight getOrSet loads were already discarded by clear(); removeHostFromCache and HostResolversPool::dropCache have no background refiller.
g Fix generalizes across inputs (params/datatypes/wrappers)? Host and PTR caches are cleared in the same critical section; no type or setting involved.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; the drop already waited on update_mutex.
i Invariants and contracts preserved? Lock acquisition sequence unchanged; only CacheBase::clear() (own mutex, no logging) added inside it; the cache is empty when the drop returns.

Session id: cron:clickhouse-impl-slot-4:20261003-134300

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a5d5c1f]

Summary: ✅


AI Review

Summary

This PR moves the DNSResolver::dropCache cache clears under update_mutex so an in-flight updateCache pass cannot repopulate entries before SYSTEM DROP DNS CACHE returns, and it makes the new gtest self-contained by restoring the process-wide disable_cache flag after Common.ReverseDNS. The locking change matches the stated root cause, the previously reported test-order dependency is fixed in the current code, and I do not see any remaining correctness or contract issues in the diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a5d5c1fe7 with master 6149a2354 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8097b6c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, targeted) / test_http_failover/test.py (all 6 tests) infra, not from this PR: the module never started a container. It waited the full 10 minutes for /tmp/docker_net.lock (cluster.py, acquire(timeout=60*10)) while two other fixed-IP modules of the same targeted batch (test_dns_cache, then test_distributed_frozen_replica) held it, then failed with started_cluster did not yield a value a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (the one above)

The other DNS modules in that batch passed, including test_dns_cache and test_host_regexp_multiple_ptr_records. All 160 checks completed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-173335

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_http_failover docker network lock timeout in the targeted integration check: #123750

@PedroTadim PedroTadim assigned PedroTadim and unassigned PedroTadim Oct 5, 2026
@PedroTadim
PedroTadim enabled auto-merge October 8, 2026 10:44
alexey-milovidov pushed a commit to raimannma/ClickHouse that referenced this pull request Oct 11, 2026
… and flaky checks

A cluster that pins a container address (`add_instance(ipv4_address=...` or
`ipv6_address=...)`) is placed on the single subnet of `docker_compose_net.yml`, so
`ClickHouseCluster.start()` takes the host-wide `/tmp/docker_net.lock` and holds it until
`shutdown()`; a waiter gives up after 10 minutes.

Since the PR workflow became targeted-only (7859137), the targeted check runs its
selection with `-n 3 --dist=loadfile` and nothing routes such modules apart. xdist starts the
units with the most tests first, which in a DNS-heavy selection are the fixed-address modules.
On ClickHouse#123699 `test_dns_cache` (held 515 s), `test_distributed_frozen_replica` (163 s) and
`test_http_failover` started together; the third needed 678 s, hit the 600 s lock timeout, and
all 6 of its tests errored at setup. In other targeted jobs the second holder routinely waits
400-541 s of its budget.

In the targeted and flaky checks, keep at most one such module in the parallel phase and move
the others to the sequential `-n 1` phase, which starts after the parallel pytest exits:
- targeted (`--dist=loadfile`): the module with the largest `TEST_DURATIONS` entry stays parallel;
- flaky (`--dist=each`): every worker runs every module, so all of them move, together with the
  existing `dist_each_sequential` modules.

The modules are detected from their source: a non-None `ipv4_address=`/`ipv6_address=` keyword,
which is what makes `add_instance` set `with_net_trics` (11 modules today, equal to an AST census
of `add_instance` calls). A suite (`test_x`) or extensionless (`test_x/test`) selector is resolved
to its module files first, for this check and for the `dist_each_sequential` prefixes. This
replaces the `test_dns_cache` special case of the flaky check.
Normal batches, bugfix validation and the retry phase are unchanged.

Related: ClickHouse#123699

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`Common.ReverseDNS` disables the cache of the process-wide `DNSResolver`
and never re-enables it, so every suite that runs after it in
`unit_tests_dbms` sees a non-default resolver. `DNSResolver.DropCacheDuringUpdate`
re-enabled it at its start to work around that, which in turn changed the
state seen by later suites depending on test order (review comment on
the `setDisableCacheFlag(false)` line).

Re-enable the cache, the default, when `Common.ReverseDNS` exits, and drop
the reset from `DropCacheDuringUpdate`, so neither test changes the
singleton for the tests that follow. Both tests use the public API only,
so the unit-test bugfix validation overlay still compiles on the merge base.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
auto-merge was automatically disabled October 12, 2026 20:25

Head branch was pushed to by a user without write access

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 13, 2026
Merged via the queue into ClickHouse:master with commit 5865380 Oct 13, 2026
177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 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-bugfix Pull request with bugfix, not backported by default 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.

3 participants